1
0
Fork 0
mirror of https://gitlab.com/famedly/conduit.git synced 2025-08-06 17:40:59 +00:00

Ran cargo fmt

This commit is contained in:
tezlm 2023-10-04 23:33:09 -07:00
parent 8d7982900a
commit f77e26c525
No known key found for this signature in database
GPG key ID: 649733FCD94AFBBA
3 changed files with 322 additions and 169 deletions

View file

@ -61,16 +61,24 @@ impl service::rooms::alias::Data for KeyValueDatabase {
fn all_local_aliases<'a>( fn all_local_aliases<'a>(
&'a self, &'a self,
) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> { ) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> {
Box::new(self.alias_roomid.iter().map(|(room_alias_bytes, room_id_bytes)| { Box::new(
self.alias_roomid
.iter()
.map(|(room_alias_bytes, room_id_bytes)| {
let room_alias_localpart = utils::string_from_bytes(&room_alias_bytes) let room_alias_localpart = utils::string_from_bytes(&room_alias_bytes)
.map_err(|_| Error::bad_database("Invalid alias bytes in aliasid_alias."))?; .map_err(|_| {
Error::bad_database("Invalid alias bytes in aliasid_alias.")
})?;
let room_id = utils::string_from_bytes(&room_id_bytes) let room_id = utils::string_from_bytes(&room_id_bytes)
.map_err(|_| Error::bad_database("Invalid room_id bytes in aliasid_alias."))? .map_err(|_| {
Error::bad_database("Invalid room_id bytes in aliasid_alias.")
})?
.try_into() .try_into()
.map_err(|_| Error::bad_database("Invalid room_id in aliasid_alias."))?; .map_err(|_| Error::bad_database("Invalid room_id in aliasid_alias."))?;
Ok((room_id, room_alias_localpart)) Ok((room_id, room_alias_localpart))
})) }),
)
} }
} }

View file

@ -9,6 +9,7 @@ use clap::{Parser, Subcommand};
use regex::Regex; use regex::Regex;
use ruma::{ use ruma::{
events::{ events::{
relation::InReplyTo,
room::{ room::{
canonical_alias::RoomCanonicalAliasEventContent, canonical_alias::RoomCanonicalAliasEventContent,
create::RoomCreateEventContent, create::RoomCreateEventContent,
@ -16,12 +17,12 @@ use ruma::{
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent}, history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
join_rules::{JoinRule, RoomJoinRulesEventContent}, join_rules::{JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
message::{RoomMessageEventContent, Relation::Reply}, message::{Relation::Reply, RoomMessageEventContent},
name::RoomNameEventContent, name::RoomNameEventContent,
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
TimelineEventType, relation::InReplyTo, TimelineEventType,
}, },
EventId, OwnedRoomAliasId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId, EventId, OwnedRoomAliasId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
}; };
@ -170,9 +171,7 @@ enum UserCommand {
#[derive(Subcommand)] #[derive(Subcommand)]
enum RoomCommand { enum RoomCommand {
/// List all rooms the server knows about /// List all rooms the server knows about
List { List { page: Option<usize> },
page: Option<usize>,
},
#[command(subcommand)] #[command(subcommand)]
/// Manage rooms' aliases /// Manage rooms' aliases
@ -235,9 +234,7 @@ enum RoomDirectoryCommand {
/// List rooms that are published /// List rooms that are published
// TODO: is this really necessary? // TODO: is this really necessary?
List { List { page: Option<usize> },
page: Option<usize>,
},
} }
#[cfg_attr(test, derive(Debug))] #[cfg_attr(test, derive(Debug))]
@ -360,9 +357,15 @@ impl Service {
.expect("Database data for admin room alias must be valid") .expect("Database data for admin room alias must be valid")
.expect("Admin room must exist"); .expect("Admin room must exist");
let send_message = |mut message: RoomMessageEventContent, reply: Option<Arc<EventId>>, mutex_lock: &MutexGuard<'_, ()>| { let send_message = |mut message: RoomMessageEventContent,
reply: Option<Arc<EventId>>,
mutex_lock: &MutexGuard<'_, ()>| {
if let Some(reply) = reply { if let Some(reply) = reply {
message.relates_to = Some(Reply { in_reply_to: InReplyTo { event_id: reply.into() } }) message.relates_to = Some(Reply {
in_reply_to: InReplyTo {
event_id: reply.into(),
},
})
} }
services() services()
@ -489,7 +492,9 @@ impl Service {
let reply_message_content = match command { let reply_message_content = match command {
AdminCommand::Appservice(command) => match command { AdminCommand::Appservice(command) => match command {
AppserviceCommand::Register => { AppserviceCommand::Register => {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" if body.len() > 2
&& body[0].trim().starts_with("```")
&& body.last().unwrap().trim() == "```"
{ {
let appservice_config = body[1..body.len() - 1].join("\n"); let appservice_config = body[1..body.len() - 1].join("\n");
let parsed_config = let parsed_config =
@ -524,17 +529,19 @@ impl Service {
"Failed to unregister appservice: {e}" "Failed to unregister appservice: {e}"
)), )),
}, },
AppserviceCommand::Show { appservice_identifier } => { AppserviceCommand::Show {
appservice_identifier,
} => {
match services() match services()
.appservice .appservice
.get_registration(&appservice_identifier) { .get_registration(&appservice_identifier)
{
Ok(Some(config)) => { Ok(Some(config)) => {
let config_str = serde_yaml::to_string(&config) let config_str = serde_yaml::to_string(&config)
.expect("config should've been validated on register"); .expect("config should've been validated on register");
let output = format!( let output = format!(
"Config for {}:\n\n```yaml\n{}\n```", "Config for {}:\n\n```yaml\n{}\n```",
appservice_identifier, appservice_identifier, config_str,
config_str,
); );
let output_html = format!( let output_html = format!(
"Config for {}:\n\n<pre><code class=\"language-yaml\">{}</code></pre>", "Config for {}:\n\n<pre><code class=\"language-yaml\">{}</code></pre>",
@ -542,8 +549,10 @@ impl Service {
escape_html(&config_str), escape_html(&config_str),
); );
RoomMessageEventContent::text_html(output, output_html) RoomMessageEventContent::text_html(output, output_html)
}, }
Ok(None) => RoomMessageEventContent::text_plain("Appservice does not exist."), Ok(None) => {
RoomMessageEventContent::text_plain("Appservice does not exist.")
}
Err(_) => RoomMessageEventContent::text_plain("Failed to get appservice."), Err(_) => RoomMessageEventContent::text_plain("Failed to get appservice."),
} }
} }
@ -568,11 +577,12 @@ impl Service {
RoomMessageEventContent::text_plain("Failed to get appservices.") RoomMessageEventContent::text_plain("Failed to get appservices.")
} }
} }
} },
AdminCommand::User(command) => match command { AdminCommand::User(command) => match command {
UserCommand::List => match services().users.list_local_users() { UserCommand::List => match services().users.list_local_users() {
Ok(users) => { Ok(users) => {
let mut msg: String = format!("Found {} local user account(s):\n", users.len()); let mut msg: String =
format!("Found {} local user account(s):\n", users.len());
msg += &users.join("\n"); msg += &users.join("\n");
RoomMessageEventContent::text_plain(&msg) RoomMessageEventContent::text_plain(&msg)
} }
@ -640,7 +650,10 @@ impl Service {
"Created user with user_id: {user_id} and password: {password}" "Created user with user_id: {user_id} and password: {password}"
)) ))
} }
UserCommand::Deactivate { leave_rooms, user_id } => { UserCommand::Deactivate {
leave_rooms,
user_id,
} => {
let user_id = Arc::<UserId>::from(user_id); let user_id = Arc::<UserId>::from(user_id);
if services().users.exists(&user_id)? { if services().users.exists(&user_id)? {
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
@ -702,9 +715,11 @@ impl Service {
"Couldn't reset the password for user {user_id}: {e}" "Couldn't reset the password for user {user_id}: {e}"
)), )),
} }
}, }
UserCommand::DeactivateAll { leave_rooms, force } => { UserCommand::DeactivateAll { leave_rooms, force } => {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" if body.len() > 2
&& body[0].trim().starts_with("```")
&& body.last().unwrap().trim() == "```"
{ {
let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>(); let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
@ -761,24 +776,42 @@ impl Service {
"Expected code block in command body. Add --help for details.", "Expected code block in command body. Add --help for details.",
) )
} }
},
} }
},
AdminCommand::Room(command) => match command { AdminCommand::Room(command) => match command {
RoomCommand::List { page } => { RoomCommand::List { page } => {
// TODO: i know there's a way to do this with clap, but i can't seem to find it // TODO: i know there's a way to do this with clap, but i can't seem to find it
let page = page.unwrap_or(1); let page = page.unwrap_or(1);
let mut rooms = services().rooms.metadata.iter_ids() let mut rooms = services()
.rooms
.metadata
.iter_ids()
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.map(|id| ( .map(|id| {
(
id.clone(), id.clone(),
services().rooms.state_cache.room_joined_count(&id).ok().flatten().unwrap_or(0), services()
services().rooms.state_accessor.get_name(&id).ok().flatten().unwrap_or(id.to_string()), .rooms
)) .state_cache
.room_joined_count(&id)
.ok()
.flatten()
.unwrap_or(0),
services()
.rooms
.state_accessor
.get_name(&id)
.ok()
.flatten()
.unwrap_or(id.to_string()),
)
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1); rooms.sort_by_key(|r| r.1);
rooms.reverse(); rooms.reverse();
let rooms: Vec<_> = rooms.into_iter() let rooms: Vec<_> = rooms
.into_iter()
.skip(page.saturating_sub(1) * PAGE_SIZE) .skip(page.saturating_sub(1) * PAGE_SIZE)
.take(PAGE_SIZE) .take(PAGE_SIZE)
.collect(); .collect();
@ -791,7 +824,9 @@ impl Service {
"Rooms:\n{}", "Rooms:\n{}",
rooms rooms
.iter() .iter()
.map(|(id, members, name)| format!("{id}\tMembers: {members}\tName: {name}")) .map(|(id, members, name)| format!(
"{id}\tMembers: {members}\tName: {name}"
))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n") .join("\n")
); );
@ -810,13 +845,30 @@ impl Service {
RoomMessageEventContent::text_html(output_plain, output_html) RoomMessageEventContent::text_html(output_plain, output_html)
} }
// TODO: clean up and deduplicate code // TODO: clean up and deduplicate code
RoomCommand::Alias(command) => { RoomCommand::Alias(command) => match command {
match command { RoomAliasCommand::Set {
RoomAliasCommand::Set { ref room_alias_localpart, .. } | RoomAliasCommand::Remove { ref room_alias_localpart } | RoomAliasCommand::Which { ref room_alias_localpart } => { ref room_alias_localpart,
let room_alias_str = format!("#{}:{}", room_alias_localpart, services().globals.server_name()); ..
}
| RoomAliasCommand::Remove {
ref room_alias_localpart,
}
| RoomAliasCommand::Which {
ref room_alias_localpart,
} => {
let room_alias_str = format!(
"#{}:{}",
room_alias_localpart,
services().globals.server_name()
);
let room_alias = match RoomAliasId::parse_box(room_alias_str) { let room_alias = match RoomAliasId::parse_box(room_alias_str) {
Ok(alias) => alias, Ok(alias) => alias,
Err(err) => return Ok(RoomMessageEventContent::text_plain(format!("Failed to parse alias: {}", err))), Err(err) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse alias: {}",
err
)))
}
}; };
match command { match command {
@ -835,93 +887,170 @@ impl Service {
} }
(_, Err(err)) => RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {}", err)), (_, Err(err)) => RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {}", err)),
} }
}, }
RoomAliasCommand::Remove { .. } => { RoomAliasCommand::Remove { .. } => {
match services().rooms.alias.resolve_local_alias(&room_alias) { match services().rooms.alias.resolve_local_alias(&room_alias) {
Ok(Some(id)) => match services().rooms.alias.remove_alias(&room_alias) { Ok(Some(id)) => {
Ok(()) => RoomMessageEventContent::text_plain(format!("Removed alias from {}", id)), match services().rooms.alias.remove_alias(&room_alias) {
Err(err) => RoomMessageEventContent::text_plain(format!("Failed to remove alias: {}", err)), Ok(()) => RoomMessageEventContent::text_plain(format!(
"Removed alias from {}",
id
)),
Err(err) => RoomMessageEventContent::text_plain(
format!("Failed to remove alias: {}", err),
),
}
}
Ok(None) => {
RoomMessageEventContent::text_plain("Alias isn't in use.")
}
Err(err) => RoomMessageEventContent::text_plain(format!(
"Unable to lookup alias: {}",
err
)),
} }
Ok(None) => RoomMessageEventContent::text_plain("Alias isn't in use."),
Err(err) => RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {}", err)),
} }
},
RoomAliasCommand::Which { .. } => { RoomAliasCommand::Which { .. } => {
match services().rooms.alias.resolve_local_alias(&room_alias) { match services().rooms.alias.resolve_local_alias(&room_alias) {
Ok(Some(id)) => RoomMessageEventContent::text_plain(format!("Alias resolves to {}", id)), Ok(Some(id)) => RoomMessageEventContent::text_plain(format!(
Ok(None) => RoomMessageEventContent::text_plain("Alias isn't in use."), "Alias resolves to {}",
Err(err) => RoomMessageEventContent::text_plain(&format!("Unable to lookup alias: {}", err)), id
)),
Ok(None) => {
RoomMessageEventContent::text_plain("Alias isn't in use.")
}
Err(err) => RoomMessageEventContent::text_plain(&format!(
"Unable to lookup alias: {}",
err
)),
}
} }
},
RoomAliasCommand::List { .. } => unreachable!(), RoomAliasCommand::List { .. } => unreachable!(),
} }
} }
RoomAliasCommand::List { room_id } => match room_id { RoomAliasCommand::List { room_id } => match room_id {
Some(room_id) => { Some(room_id) => {
let aliases: Result<Vec<_>, _> = services().rooms.alias.local_aliases_for_room(&room_id).collect(); let aliases: Result<Vec<_>, _> = services()
.rooms
.alias
.local_aliases_for_room(&room_id)
.collect();
match aliases { match aliases {
Ok(aliases) => { Ok(aliases) => {
let plain_list: String = aliases.iter() let plain_list: String = aliases
.iter()
.map(|alias| format!("- {}\n", alias)) .map(|alias| format!("- {}\n", alias))
.collect(); .collect();
let html_list: String = aliases.iter() let html_list: String = aliases
.map(|alias| format!("<li>{}</li>\n", escape_html(&alias.to_string()))) .iter()
.map(|alias| {
format!(
"<li>{}</li>\n",
escape_html(&alias.to_string())
)
})
.collect(); .collect();
let plain = format!("Aliases for {}:\n{}", room_id, plain_list); let plain = format!("Aliases for {}:\n{}", room_id, plain_list);
let html = format!("Aliases for {}:\n<ul>{}</ul>", room_id, html_list); let html =
format!("Aliases for {}:\n<ul>{}</ul>", room_id, html_list);
RoomMessageEventContent::text_html(plain, html) RoomMessageEventContent::text_html(plain, html)
}, }
Err(err) => RoomMessageEventContent::text_plain(&format!("Unable to list aliases: {}", err)), Err(err) => RoomMessageEventContent::text_plain(&format!(
"Unable to list aliases: {}",
err
)),
} }
} }
None => { None => {
let aliases: Result<Vec<_>, _> = services().rooms.alias.all_local_aliases().collect(); let aliases: Result<Vec<_>, _> =
services().rooms.alias.all_local_aliases().collect();
match aliases { match aliases {
Ok(aliases) => { Ok(aliases) => {
let server_name = services().globals.server_name(); let server_name = services().globals.server_name();
let plain_list: String = aliases.iter() let plain_list: String = aliases
.map(|(id, alias)| format!("- #{}:{} -> {}\n", alias, server_name, id)) .iter()
.map(|(id, alias)| {
format!("- #{}:{} -> {}\n", alias, server_name, id)
})
.collect(); .collect();
let html_list: String = aliases.iter() let html_list: String = aliases
.map(|(id, alias)| format!("<li>#{}:{} -> {}</li>\n", escape_html(&alias.to_string()), server_name, escape_html(&id.to_string()))) .iter()
.map(|(id, alias)| {
format!(
"<li>#{}:{} -> {}</li>\n",
escape_html(&alias.to_string()),
server_name,
escape_html(&id.to_string())
)
})
.collect(); .collect();
let plain = format!("Aliases:\n{}", plain_list); let plain = format!("Aliases:\n{}", plain_list);
let html = format!("Aliases:\n<ul>{}</ul>", html_list); let html = format!("Aliases:\n<ul>{}</ul>", html_list);
RoomMessageEventContent::text_html(plain, html) RoomMessageEventContent::text_html(plain, html)
}
Err(err) => RoomMessageEventContent::text_plain(&format!(
"Unable to list aliases: {}",
err
)),
}
}
},
}, },
Err(err) => RoomMessageEventContent::text_plain(&format!("Unable to list aliases: {}", err)),
}
}
}
}
}
RoomCommand::Directory(command) => match command { RoomCommand::Directory(command) => match command {
RoomDirectoryCommand::Publish { room_id } => match services().rooms.directory.set_public(&room_id) { RoomDirectoryCommand::Publish { room_id } => {
match services().rooms.directory.set_public(&room_id) {
Ok(()) => RoomMessageEventContent::text_plain("Room published"), Ok(()) => RoomMessageEventContent::text_plain("Room published"),
Err(err) => RoomMessageEventContent::text_plain(&format!("Unable to update room: {}", err)), Err(err) => RoomMessageEventContent::text_plain(&format!(
"Unable to update room: {}",
err
)),
} }
RoomDirectoryCommand::Unpublish { room_id } => match services().rooms.directory.set_not_public(&room_id) { }
RoomDirectoryCommand::Unpublish { room_id } => {
match services().rooms.directory.set_not_public(&room_id) {
Ok(()) => RoomMessageEventContent::text_plain("Room unpublished"), Ok(()) => RoomMessageEventContent::text_plain("Room unpublished"),
Err(err) => RoomMessageEventContent::text_plain(&format!("Unable to update room: {}", err)), Err(err) => RoomMessageEventContent::text_plain(&format!(
"Unable to update room: {}",
err
)),
}
} }
RoomDirectoryCommand::List { page } => { RoomDirectoryCommand::List { page } => {
let page = page.unwrap_or(1); let page = page.unwrap_or(1);
let mut rooms = services().rooms.directory.public_rooms() let mut rooms = services()
.rooms
.directory
.public_rooms()
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.map(|id| ( .map(|id| {
(
id.clone(), id.clone(),
services().rooms.state_cache.room_joined_count(&id).ok().flatten().unwrap_or(0), services()
services().rooms.state_accessor.get_name(&id).ok().flatten().unwrap_or(id.to_string()), .rooms
)) .state_cache
.room_joined_count(&id)
.ok()
.flatten()
.unwrap_or(0),
services()
.rooms
.state_accessor
.get_name(&id)
.ok()
.flatten()
.unwrap_or(id.to_string()),
)
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1); rooms.sort_by_key(|r| r.1);
rooms.reverse(); rooms.reverse();
let rooms: Vec<_> = rooms.into_iter() let rooms: Vec<_> = rooms
.into_iter()
.skip(page.saturating_sub(1) * PAGE_SIZE) .skip(page.saturating_sub(1) * PAGE_SIZE)
.take(PAGE_SIZE) .take(PAGE_SIZE)
.collect(); .collect();
@ -934,7 +1063,9 @@ impl Service {
"Rooms:\n{}", "Rooms:\n{}",
rooms rooms
.iter() .iter()
.map(|(id, members, name)| format!("{id}\tMembers: {members}\tName: {name}")) .map(|(id, members, name)| format!(
"{id}\tMembers: {members}\tName: {name}"
))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n") .join("\n")
); );
@ -952,8 +1083,8 @@ impl Service {
); );
RoomMessageEventContent::text_html(output_plain, output_html) RoomMessageEventContent::text_html(output_plain, output_html)
} }
} },
} },
AdminCommand::Federation(command) => match command { AdminCommand::Federation(command) => match command {
FederationCommand::DisableRoom { room_id } => { FederationCommand::DisableRoom { room_id } => {
services().rooms.metadata.disable_room(&room_id, true)?; services().rooms.metadata.disable_room(&room_id, true)?;
@ -982,9 +1113,11 @@ impl Service {
); );
} }
RoomMessageEventContent::text_plain(&msg) RoomMessageEventContent::text_plain(&msg)
}, }
FederationCommand::SignJson => { FederationCommand::SignJson => {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" if body.len() > 2
&& body[0].trim().starts_with("```")
&& body.last().unwrap().trim() == "```"
{ {
let string = body[1..body.len() - 1].join("\n"); let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) { match serde_json::from_str(&string) {
@ -999,16 +1132,20 @@ impl Service {
.expect("canonical json is valid json"); .expect("canonical json is valid json");
RoomMessageEventContent::text_plain(json_text) RoomMessageEventContent::text_plain(json_text)
} }
Err(e) => RoomMessageEventContent::text_plain(format!("Invalid json: {e}")), Err(e) => {
RoomMessageEventContent::text_plain(format!("Invalid json: {e}"))
}
} }
} else { } else {
RoomMessageEventContent::text_plain( RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.", "Expected code block in command body. Add --help for details.",
) )
} }
}, }
FederationCommand::VerifyJson => { FederationCommand::VerifyJson => {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" if body.len() > 2
&& body[0].trim().starts_with("```")
&& body.last().unwrap().trim() == "```"
{ {
let string = body[1..body.len() - 1].join("\n"); let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) { match serde_json::from_str(&string) {
@ -1023,26 +1160,30 @@ impl Service {
let pub_key_map = pub_key_map.read().unwrap(); let pub_key_map = pub_key_map.read().unwrap();
match ruma::signatures::verify_json(&pub_key_map, &value) { 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!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Signature verification failed: {e}" "Signature verification failed: {e}"
)), )),
} }
} }
Err(e) => RoomMessageEventContent::text_plain(format!("Invalid json: {e}")), Err(e) => {
RoomMessageEventContent::text_plain(format!("Invalid json: {e}"))
}
} }
} else { } else {
RoomMessageEventContent::text_plain( RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.", "Expected code block in command body. Add --help for details.",
) )
} }
},
} }
},
AdminCommand::Server(command) => match command { AdminCommand::Server(command) => match command {
ServerCommand::ShowConfig => { ServerCommand::ShowConfig => {
// Construct and send the response // Construct and send the response
RoomMessageEventContent::text_plain(format!("{}", services().globals.config)) RoomMessageEventContent::text_plain(format!("{}", services().globals.config))
}, }
ServerCommand::MemoryUsage => { ServerCommand::MemoryUsage => {
let response1 = services().memory_usage(); let response1 = services().memory_usage();
let response2 = services().globals.db.memory_usage(); let response2 = services().globals.db.memory_usage();
@ -1050,18 +1191,18 @@ impl Service {
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
"Services:\n{response1}\n\nDatabase:\n{response2}" "Services:\n{response1}\n\nDatabase:\n{response2}"
)) ))
}, }
ServerCommand::ClearDatabaseCaches { amount } => { ServerCommand::ClearDatabaseCaches { amount } => {
services().globals.db.clear_caches(amount); services().globals.db.clear_caches(amount);
RoomMessageEventContent::text_plain("Done.") RoomMessageEventContent::text_plain("Done.")
}, }
ServerCommand::ClearServiceCaches { amount } => { ServerCommand::ClearServiceCaches { amount } => {
services().clear_caches(amount); services().clear_caches(amount);
RoomMessageEventContent::text_plain("Done.") RoomMessageEventContent::text_plain("Done.")
},
} }
},
AdminCommand::Debug(command) => match command { AdminCommand::Debug(command) => match command {
DebugCommand::GetAuthChain { event_id } => { DebugCommand::GetAuthChain { event_id } => {
let event_id = Arc::<EventId>::from(event_id); let event_id = Arc::<EventId>::from(event_id);
@ -1088,9 +1229,11 @@ impl Service {
} else { } else {
RoomMessageEventContent::text_plain("Event not found.") RoomMessageEventContent::text_plain("Event not found.")
} }
}, }
DebugCommand::ParsePdu => { DebugCommand::ParsePdu => {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" if body.len() > 2
&& body[0].trim().starts_with("```")
&& body.last().unwrap().trim() == "```"
{ {
let string = body[1..body.len() - 1].join("\n"); let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) { match serde_json::from_str(&string) {
@ -1102,9 +1245,9 @@ impl Service {
match serde_json::from_value::<PduEvent>( match serde_json::from_value::<PduEvent>(
serde_json::to_value(value).expect("value is json"), serde_json::to_value(value).expect("value is json"),
) { ) {
Ok(pdu) => RoomMessageEventContent::text_plain(format!( Ok(pdu) => RoomMessageEventContent::text_plain(
"EventId: {event_id:?}\n{pdu:#?}" format!("EventId: {event_id:?}\n{pdu:#?}"),
)), ),
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"EventId: {event_id:?}\nCould not parse event: {e}" "EventId: {event_id:?}\nCould not parse event: {e}"
)), )),
@ -1122,7 +1265,7 @@ impl Service {
} else { } else {
RoomMessageEventContent::text_plain("Expected code block in command body.") RoomMessageEventContent::text_plain("Expected code block in command body.")
} }
}, }
DebugCommand::GetPdu { event_id } => { DebugCommand::GetPdu { event_id } => {
let mut outlier = false; let mut outlier = false;
let mut pdu_json = services() let mut pdu_json = services()
@ -1160,8 +1303,8 @@ impl Service {
} }
None => RoomMessageEventContent::text_plain("PDU not found."), None => RoomMessageEventContent::text_plain("PDU not found."),
} }
},
} }
},
}; };
Ok(reply_message_content) Ok(reply_message_content)
@ -1567,7 +1710,9 @@ impl Service {
} }
fn escape_html(s: &str) -> String { fn escape_html(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;") s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
} }
#[cfg(test)] #[cfg(test)]