run cargo fix for rust 2024 changes and rustfmt

Signed-off-by: June Clementine Strawberry <strawberry@puppygock.gay>
This commit is contained in:
June Clementine Strawberry 2025-02-23 01:17:45 -05:00
parent e97952b7f6
commit a1e1f40ded
No known key found for this signature in database
320 changed files with 2212 additions and 2039 deletions

View file

@ -1,6 +1,6 @@
use ruma::{api::appservice::Registration, events::room::message::RoomMessageEventContent}; use ruma::{api::appservice::Registration, events::room::message::RoomMessageEventContent};
use crate::{admin_command, Result}; use crate::{Result, admin_command};
#[admin_command] #[admin_command]
pub(super) async fn register(&self) -> Result<RoomMessageEventContent> { pub(super) async fn register(&self) -> Result<RoomMessageEventContent> {

View file

@ -3,9 +3,9 @@ use std::{fmt, time::SystemTime};
use conduwuit::Result; use conduwuit::Result;
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::{ use futures::{
Future, FutureExt,
io::{AsyncWriteExt, BufWriter}, io::{AsyncWriteExt, BufWriter},
lock::Mutex, lock::Mutex,
Future, FutureExt,
}; };
use ruma::EventId; use ruma::EventId;
@ -21,7 +21,7 @@ impl Command<'_> {
pub(crate) fn write_fmt( pub(crate) fn write_fmt(
&self, &self,
arguments: fmt::Arguments<'_>, arguments: fmt::Arguments<'_>,
) -> impl Future<Output = Result> + Send + '_ { ) -> impl Future<Output = Result> + Send + '_ + use<'_> {
let buf = format!("{arguments}"); let buf = format!("{arguments}");
self.output.lock().then(|mut output| async move { self.output.lock().then(|mut output| async move {
output.write_all(buf.as_bytes()).await.map_err(Into::into) output.write_all(buf.as_bytes()).await.map_err(Into::into)

View file

@ -6,19 +6,19 @@ use std::{
}; };
use conduwuit::{ use conduwuit::{
debug_error, err, info, trace, utils, Error, PduEvent, PduId, RawPduId, Result, debug_error, err, info, trace, utils,
utils::{ utils::{
stream::{IterStream, ReadyExt}, stream::{IterStream, ReadyExt},
string::EMPTY, string::EMPTY,
}, },
warn, Error, PduEvent, PduId, RawPduId, Result, warn,
}; };
use futures::{FutureExt, StreamExt, TryStreamExt}; use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::{ use ruma::{
api::{client::error::ErrorKind, federation::event::get_room_state},
events::room::message::RoomMessageEventContent,
CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomOrAliasId, RoomId, RoomVersionId, CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomOrAliasId, RoomId, RoomVersionId,
ServerName, ServerName,
api::{client::error::ErrorKind, federation::event::get_room_state},
events::room::message::RoomMessageEventContent,
}; };
use service::rooms::{ use service::rooms::{
short::{ShortEventId, ShortRoomId}, short::{ShortEventId, ShortRoomId},
@ -209,18 +209,21 @@ pub(super) async fn get_remote_pdu_list(
for pdu in list { for pdu in list {
if force { if force {
if let Err(e) = self.get_remote_pdu(Box::from(pdu), server.clone()).await { match self.get_remote_pdu(Box::from(pdu), server.clone()).await {
failed_count = failed_count.saturating_add(1); | Err(e) => {
self.services failed_count = failed_count.saturating_add(1);
.admin self.services
.send_message(RoomMessageEventContent::text_plain(format!( .admin
"Failed to get remote PDU, ignoring error: {e}" .send_message(RoomMessageEventContent::text_plain(format!(
))) "Failed to get remote PDU, ignoring error: {e}"
.await )))
.ok(); .await
warn!("Failed to get remote PDU, ignoring error: {e}"); .ok();
} else { warn!("Failed to get remote PDU, ignoring error: {e}");
success_count = success_count.saturating_add(1); },
| _ => {
success_count = success_count.saturating_add(1);
},
} }
} else { } else {
self.get_remote_pdu(Box::from(pdu), server.clone()).await?; self.get_remote_pdu(Box::from(pdu), server.clone()).await?;
@ -957,7 +960,7 @@ pub(super) async fn database_stats(
self.services self.services
.db .db
.iter() .iter()
.filter(|(&name, _)| map_name.is_empty() || map_name == name) .filter(|&(&name, _)| map_name.is_empty() || map_name == name)
.try_stream() .try_stream()
.try_for_each(|(&name, map)| { .try_for_each(|(&name, map)| {
let res = map.property(&property).expect("invalid property"); let res = map.property(&property).expect("invalid property");

View file

@ -1,7 +1,7 @@
use conduwuit::Err; use conduwuit::Err;
use ruma::events::room::message::RoomMessageEventContent; use ruma::events::room::message::RoomMessageEventContent;
use crate::{admin_command, admin_command_dispatch, Result}; use crate::{Result, admin_command, admin_command_dispatch};
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, clap::Subcommand)] #[derive(Debug, clap::Subcommand)]

View file

@ -3,7 +3,7 @@ use std::fmt::Write;
use conduwuit::Result; use conduwuit::Result;
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
events::room::message::RoomMessageEventContent, OwnedRoomId, RoomId, ServerName, UserId, OwnedRoomId, RoomId, ServerName, UserId, events::room::message::RoomMessageEventContent,
}; };
use crate::{admin_command, get_room_info}; use crate::{admin_command, get_room_info};

View file

@ -1,12 +1,12 @@
use std::time::Duration; use std::time::Duration;
use conduwuit::{ use conduwuit::{
debug, debug_info, debug_warn, error, info, trace, utils::time::parse_timepoint_ago, Result, Result, debug, debug_info, debug_warn, error, info, trace, utils::time::parse_timepoint_ago,
}; };
use conduwuit_service::media::Dim; use conduwuit_service::media::Dim;
use ruma::{ use ruma::{
events::room::message::RoomMessageEventContent, EventId, Mxc, MxcUri, OwnedMxcUri, EventId, Mxc, MxcUri, OwnedMxcUri, OwnedServerName, ServerName,
OwnedServerName, ServerName, events::room::message::RoomMessageEventContent,
}; };
use crate::{admin_command, utils::parse_local_user_id}; use crate::{admin_command, utils::parse_local_user_id};
@ -41,103 +41,106 @@ pub(super) async fn delete(
let mut mxc_urls = Vec::with_capacity(4); let mut mxc_urls = Vec::with_capacity(4);
// parsing the PDU for any MXC URLs begins here // parsing the PDU for any MXC URLs begins here
if let Ok(event_json) = self.services.rooms.timeline.get_pdu_json(&event_id).await { match self.services.rooms.timeline.get_pdu_json(&event_id).await {
if let Some(content_key) = event_json.get("content") { | Ok(event_json) => {
debug!("Event ID has \"content\"."); if let Some(content_key) = event_json.get("content") {
let content_obj = content_key.as_object(); debug!("Event ID has \"content\".");
let content_obj = content_key.as_object();
if let Some(content) = content_obj { if let Some(content) = content_obj {
// 1. attempts to parse the "url" key // 1. attempts to parse the "url" key
debug!("Attempting to go into \"url\" key for main media file"); debug!("Attempting to go into \"url\" key for main media file");
if let Some(url) = content.get("url") { if let Some(url) = content.get("url") {
debug!("Got a URL in the event ID {event_id}: {url}"); debug!("Got a URL in the event ID {event_id}: {url}");
if url.to_string().starts_with("\"mxc://") { if url.to_string().starts_with("\"mxc://") {
debug!("Pushing URL {url} to list of MXCs to delete"); debug!("Pushing URL {url} to list of MXCs to delete");
let final_url = url.to_string().replace('"', ""); let final_url = url.to_string().replace('"', "");
mxc_urls.push(final_url); mxc_urls.push(final_url);
} else {
info!(
"Found a URL in the event ID {event_id} but did not start with \
mxc://, ignoring"
);
}
}
// 2. attempts to parse the "info" key
debug!("Attempting to go into \"info\" key for thumbnails");
if let Some(info_key) = content.get("info") {
debug!("Event ID has \"info\".");
let info_obj = info_key.as_object();
if let Some(info) = info_obj {
if let Some(thumbnail_url) = info.get("thumbnail_url") {
debug!("Found a thumbnail_url in info key: {thumbnail_url}");
if thumbnail_url.to_string().starts_with("\"mxc://") {
debug!(
"Pushing thumbnail URL {thumbnail_url} to list of MXCs \
to delete"
);
let final_thumbnail_url =
thumbnail_url.to_string().replace('"', "");
mxc_urls.push(final_thumbnail_url);
} else {
info!(
"Found a thumbnail URL in the event ID {event_id} but \
did not start with mxc://, ignoring"
);
}
} else { } else {
info!( info!(
"No \"thumbnail_url\" key in \"info\" key, assuming no \ "Found a URL in the event ID {event_id} but did not start \
thumbnails." with mxc://, ignoring"
); );
} }
} }
}
// 3. attempts to parse the "file" key // 2. attempts to parse the "info" key
debug!("Attempting to go into \"file\" key"); debug!("Attempting to go into \"info\" key for thumbnails");
if let Some(file_key) = content.get("file") { if let Some(info_key) = content.get("info") {
debug!("Event ID has \"file\"."); debug!("Event ID has \"info\".");
let file_obj = file_key.as_object(); let info_obj = info_key.as_object();
if let Some(file) = file_obj { if let Some(info) = info_obj {
if let Some(url) = file.get("url") { if let Some(thumbnail_url) = info.get("thumbnail_url") {
debug!("Found url in file key: {url}"); debug!("Found a thumbnail_url in info key: {thumbnail_url}");
if url.to_string().starts_with("\"mxc://") { if thumbnail_url.to_string().starts_with("\"mxc://") {
debug!("Pushing URL {url} to list of MXCs to delete"); debug!(
let final_url = url.to_string().replace('"', ""); "Pushing thumbnail URL {thumbnail_url} to list of \
mxc_urls.push(final_url); MXCs to delete"
);
let final_thumbnail_url =
thumbnail_url.to_string().replace('"', "");
mxc_urls.push(final_thumbnail_url);
} else {
info!(
"Found a thumbnail URL in the event ID {event_id} \
but did not start with mxc://, ignoring"
);
}
} else { } else {
info!( info!(
"Found a URL in the event ID {event_id} but did not \ "No \"thumbnail_url\" key in \"info\" key, assuming no \
start with mxc://, ignoring" thumbnails."
); );
} }
} else {
info!("No \"url\" key in \"file\" key.");
} }
} }
// 3. attempts to parse the "file" key
debug!("Attempting to go into \"file\" key");
if let Some(file_key) = content.get("file") {
debug!("Event ID has \"file\".");
let file_obj = file_key.as_object();
if let Some(file) = file_obj {
if let Some(url) = file.get("url") {
debug!("Found url in file key: {url}");
if url.to_string().starts_with("\"mxc://") {
debug!("Pushing URL {url} to list of MXCs to delete");
let final_url = url.to_string().replace('"', "");
mxc_urls.push(final_url);
} else {
info!(
"Found a URL in the event ID {event_id} but did not \
start with mxc://, ignoring"
);
}
} else {
info!("No \"url\" key in \"file\" key.");
}
}
}
} else {
return Ok(RoomMessageEventContent::text_plain(
"Event ID does not have a \"content\" key or failed parsing the \
event ID JSON.",
));
} }
} else { } else {
return Ok(RoomMessageEventContent::text_plain( return Ok(RoomMessageEventContent::text_plain(
"Event ID does not have a \"content\" key or failed parsing the event \ "Event ID does not have a \"content\" key, this is not a message or an \
ID JSON.", event type that contains media.",
)); ));
} }
} else { },
| _ => {
return Ok(RoomMessageEventContent::text_plain( return Ok(RoomMessageEventContent::text_plain(
"Event ID does not have a \"content\" key, this is not a message or an \ "Event ID does not exist or is not known to us.",
event type that contains media.",
)); ));
} },
} else {
return Ok(RoomMessageEventContent::text_plain(
"Event ID does not exist or is not known to us.",
));
} }
if mxc_urls.is_empty() { if mxc_urls.is_empty() {

View file

@ -8,7 +8,7 @@ use std::{
use clap::{CommandFactory, Parser}; use clap::{CommandFactory, Parser};
use conduwuit::{ use conduwuit::{
debug, error, Error, Result, debug, error,
log::{ log::{
capture, capture,
capture::Capture, capture::Capture,
@ -16,24 +16,24 @@ use conduwuit::{
}, },
trace, trace,
utils::string::{collect_stream, common_prefix}, utils::string::{collect_stream, common_prefix},
warn, Error, Result, warn,
}; };
use futures::{future::FutureExt, io::BufWriter, AsyncWriteExt}; use futures::{AsyncWriteExt, future::FutureExt, io::BufWriter};
use ruma::{ use ruma::{
EventId,
events::{ events::{
relation::InReplyTo, relation::InReplyTo,
room::message::{Relation::Reply, RoomMessageEventContent}, room::message::{Relation::Reply, RoomMessageEventContent},
}, },
EventId,
}; };
use service::{ use service::{
admin::{CommandInput, CommandOutput, ProcessorFuture, ProcessorResult},
Services, Services,
admin::{CommandInput, CommandOutput, ProcessorFuture, ProcessorResult},
}; };
use tracing::Level; use tracing::Level;
use tracing_subscriber::{filter::LevelFilter, EnvFilter}; use tracing_subscriber::{EnvFilter, filter::LevelFilter};
use crate::{admin, admin::AdminCommand, Command}; use crate::{Command, admin, admin::AdminCommand};
#[must_use] #[must_use]
pub(super) fn complete(line: &str) -> String { complete_command(AdminCommand::command(), line) } pub(super) fn complete(line: &str) -> String { complete_command(AdminCommand::command(), line) }

View file

@ -1,7 +1,7 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, RoomId, UserId}; use ruma::{RoomId, UserId, events::room::message::RoomMessageEventContent};
use crate::{admin_command, admin_command_dispatch}; use crate::{admin_command, admin_command_dispatch};

View file

@ -2,13 +2,12 @@ use std::{borrow::Cow, collections::BTreeMap, ops::Deref};
use clap::Subcommand; use clap::Subcommand;
use conduwuit::{ use conduwuit::{
apply, at, is_zero, Err, Result, apply, at, is_zero,
utils::{ utils::{
IterStream,
stream::{ReadyExt, TryIgnore, TryParallelExt}, stream::{ReadyExt, TryIgnore, TryParallelExt},
string::EMPTY, string::EMPTY,
IterStream,
}, },
Err, Result,
}; };
use futures::{FutureExt, StreamExt, TryStreamExt}; use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::events::room::message::RoomMessageEventContent; use ruma::events::room::message::RoomMessageEventContent;

View file

@ -1,7 +1,7 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::{utils::time, Result}; use conduwuit::{Result, utils::time};
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, OwnedServerName}; use ruma::{OwnedServerName, events::room::message::RoomMessageEventContent};
use crate::{admin_command, admin_command_dispatch}; use crate::{admin_command, admin_command_dispatch};

View file

@ -1,7 +1,7 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::{Error, Result}; use conduwuit::{Error, Result};
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName, UserId}; use ruma::{RoomId, ServerName, UserId, events::room::message::RoomMessageEventContent};
use crate::Command; use crate::Command;

View file

@ -1,7 +1,7 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::{utils::stream::TryTools, PduCount, Result}; use conduwuit::{PduCount, Result, utils::stream::TryTools};
use futures::TryStreamExt; use futures::TryStreamExt;
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomOrAliasId}; use ruma::{OwnedRoomOrAliasId, events::room::message::RoomMessageEventContent};
use crate::{admin_command, admin_command_dispatch}; use crate::{admin_command, admin_command_dispatch};

View file

@ -1,7 +1,7 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, ServerName, UserId}; use ruma::{ServerName, UserId, events::room::message::RoomMessageEventContent};
use service::sending::Destination; use service::sending::Destination;
use crate::Command; use crate::Command;

View file

@ -1,6 +1,6 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use ruma::{events::room::message::RoomMessageEventContent, OwnedEventId, OwnedRoomOrAliasId}; use ruma::{OwnedEventId, OwnedRoomOrAliasId, events::room::message::RoomMessageEventContent};
use crate::{admin_command, admin_command_dispatch}; use crate::{admin_command, admin_command_dispatch};

View file

@ -2,7 +2,7 @@ use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use futures::stream::StreamExt; use futures::stream::StreamExt;
use ruma::{ use ruma::{
events::room::message::RoomMessageEventContent, OwnedDeviceId, OwnedRoomId, OwnedUserId, OwnedDeviceId, OwnedRoomId, OwnedUserId, events::room::message::RoomMessageEventContent,
}; };
use crate::{admin_command, admin_command_dispatch}; use crate::{admin_command, admin_command_dispatch};

View file

@ -4,10 +4,10 @@ use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
events::room::message::RoomMessageEventContent, OwnedRoomAliasId, OwnedRoomId, RoomId, OwnedRoomAliasId, OwnedRoomId, RoomId, events::room::message::RoomMessageEventContent,
}; };
use crate::{escape_html, Command}; use crate::{Command, escape_html};
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
pub(crate) enum RoomAliasCommand { pub(crate) enum RoomAliasCommand {

View file

@ -1,8 +1,8 @@
use conduwuit::Result; use conduwuit::Result;
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId}; use ruma::{OwnedRoomId, events::room::message::RoomMessageEventContent};
use crate::{admin_command, get_room_info, PAGE_SIZE}; use crate::{PAGE_SIZE, admin_command, get_room_info};
#[admin_command] #[admin_command]
pub(super) async fn list_rooms( pub(super) async fn list_rooms(

View file

@ -1,9 +1,9 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, RoomId}; use ruma::{RoomId, events::room::message::RoomMessageEventContent};
use crate::{get_room_info, Command, PAGE_SIZE}; use crate::{Command, PAGE_SIZE, get_room_info};
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
pub(crate) enum RoomDirectoryCommand { pub(crate) enum RoomDirectoryCommand {

View file

@ -1,7 +1,7 @@
use clap::Subcommand; use clap::Subcommand;
use conduwuit::{utils::ReadyExt, Result}; use conduwuit::{Result, utils::ReadyExt};
use futures::StreamExt; use futures::StreamExt;
use ruma::{events::room::message::RoomMessageEventContent, RoomId}; use ruma::{RoomId, events::room::message::RoomMessageEventContent};
use crate::{admin_command, admin_command_dispatch}; use crate::{admin_command, admin_command_dispatch};

View file

@ -1,14 +1,14 @@
use api::client::leave_room; use api::client::leave_room;
use clap::Subcommand; use clap::Subcommand;
use conduwuit::{ use conduwuit::{
debug, error, info, Result, debug, error, info,
utils::{IterStream, ReadyExt}, utils::{IterStream, ReadyExt},
warn, Result, warn,
}; };
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
events::room::message::RoomMessageEventContent, OwnedRoomId, RoomAliasId, RoomId, OwnedRoomId, RoomAliasId, RoomId, RoomOrAliasId,
RoomOrAliasId, events::room::message::RoomMessageEventContent,
}; };
use crate::{admin_command, admin_command_dispatch, get_room_info}; use crate::{admin_command, admin_command_dispatch, get_room_info};
@ -124,41 +124,42 @@ async fn ban_room(
locally, if not using get_alias_helper to fetch room ID remotely" locally, if not using get_alias_helper to fetch room ID remotely"
); );
let room_id = if let Ok(room_id) = self let room_id = match self
.services .services
.rooms .rooms
.alias .alias
.resolve_local_alias(room_alias) .resolve_local_alias(room_alias)
.await .await
{ {
room_id | Ok(room_id) => room_id,
} else { | _ => {
debug!( debug!(
"We don't have this room alias to a room ID locally, attempting to fetch room \ "We don't have this room alias to a room ID locally, attempting to fetch \
ID over federation" room ID over federation"
); );
match self match self
.services .services
.rooms .rooms
.alias .alias
.resolve_alias(room_alias, None) .resolve_alias(room_alias, None)
.await .await
{ {
| Ok((room_id, servers)) => { | Ok((room_id, servers)) => {
debug!( debug!(
?room_id, ?room_id,
?servers, ?servers,
"Got federation response fetching room ID for {room_id}" "Got federation response fetching room ID for {room_id}"
); );
room_id room_id
}, },
| Err(e) => { | Err(e) => {
return Ok(RoomMessageEventContent::notice_plain(format!( return Ok(RoomMessageEventContent::notice_plain(format!(
"Failed to resolve room alias {room_alias} to a room ID: {e}" "Failed to resolve room alias {room_alias} to a room ID: {e}"
))); )));
}, },
} }
},
}; };
self.services.rooms.metadata.ban_room(&room_id, true); self.services.rooms.metadata.ban_room(&room_id, true);
@ -321,51 +322,55 @@ async fn ban_list_of_rooms(
if room_alias_or_id.is_room_alias_id() { if room_alias_or_id.is_room_alias_id() {
match RoomAliasId::parse(room_alias_or_id) { match RoomAliasId::parse(room_alias_or_id) {
| Ok(room_alias) => { | Ok(room_alias) => {
let room_id = if let Ok(room_id) = self let room_id = match self
.services .services
.rooms .rooms
.alias .alias
.resolve_local_alias(room_alias) .resolve_local_alias(room_alias)
.await .await
{ {
room_id | Ok(room_id) => room_id,
} else { | _ => {
debug!( debug!(
"We don't have this room alias to a room ID locally, \ "We don't have this room alias to a room ID locally, \
attempting to fetch room ID over federation" attempting to fetch room ID over federation"
); );
match self match self
.services .services
.rooms .rooms
.alias .alias
.resolve_alias(room_alias, None) .resolve_alias(room_alias, None)
.await .await
{ {
| Ok((room_id, servers)) => { | Ok((room_id, servers)) => {
debug!( debug!(
?room_id, ?room_id,
?servers, ?servers,
"Got federation response fetching room ID for {room}", "Got federation response fetching room ID for \
); {room}",
room_id
},
| Err(e) => {
// don't fail if force blocking
if force {
warn!(
"Failed to resolve room alias {room} to a room \
ID: {e}"
); );
continue; room_id
} },
| Err(e) => {
// don't fail if force blocking
if force {
warn!(
"Failed to resolve room alias {room} to a \
room ID: {e}"
);
continue;
}
return Ok(RoomMessageEventContent::text_plain(format!( return Ok(RoomMessageEventContent::text_plain(
"Failed to resolve room alias {room} to a room ID: \ format!(
{e}" "Failed to resolve room alias {room} to a \
))); room ID: {e}"
}, ),
} ));
},
}
},
}; };
room_ids.push(room_id); room_ids.push(room_id);
@ -537,41 +542,42 @@ async fn unban_room(
locally, if not using get_alias_helper to fetch room ID remotely" locally, if not using get_alias_helper to fetch room ID remotely"
); );
let room_id = if let Ok(room_id) = self let room_id = match self
.services .services
.rooms .rooms
.alias .alias
.resolve_local_alias(room_alias) .resolve_local_alias(room_alias)
.await .await
{ {
room_id | Ok(room_id) => room_id,
} else { | _ => {
debug!( debug!(
"We don't have this room alias to a room ID locally, attempting to fetch room \ "We don't have this room alias to a room ID locally, attempting to fetch \
ID over federation" room ID over federation"
); );
match self match self
.services .services
.rooms .rooms
.alias .alias
.resolve_alias(room_alias, None) .resolve_alias(room_alias, None)
.await .await
{ {
| Ok((room_id, servers)) => { | Ok((room_id, servers)) => {
debug!( debug!(
?room_id, ?room_id,
?servers, ?servers,
"Got federation response fetching room ID for room {room}" "Got federation response fetching room ID for room {room}"
); );
room_id room_id
}, },
| Err(e) => { | Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!( return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}" "Failed to resolve room alias {room} to a room ID: {e}"
))); )));
}, },
} }
},
}; };
self.services.rooms.metadata.ban_room(&room_id, false); self.services.rooms.metadata.ban_room(&room_id, false);

View file

@ -1,6 +1,6 @@
use std::{fmt::Write, path::PathBuf, sync::Arc}; use std::{fmt::Write, path::PathBuf, sync::Arc};
use conduwuit::{info, utils::time, warn, Err, Result}; use conduwuit::{Err, Result, info, utils::time, warn};
use ruma::events::room::message::RoomMessageEventContent; use ruma::events::room::message::RoomMessageEventContent;
use crate::admin_command; use crate::admin_command;

View file

@ -2,23 +2,23 @@ use std::{collections::BTreeMap, fmt::Write as _};
use api::client::{full_user_deactivate, join_room_by_id_helper, leave_room}; use api::client::{full_user_deactivate, join_room_by_id_helper, leave_room};
use conduwuit::{ use conduwuit::{
debug_warn, error, info, is_equal_to, PduBuilder, Result, debug_warn, error, info, is_equal_to,
utils::{self, ReadyExt}, utils::{self, ReadyExt},
warn, PduBuilder, Result, warn,
}; };
use conduwuit_api::client::{leave_all_rooms, update_avatar_url, update_displayname}; use conduwuit_api::client::{leave_all_rooms, update_avatar_url, update_displayname};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
EventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, RoomId, UserId,
events::{ events::{
RoomAccountDataEventType, StateEventType,
room::{ room::{
message::RoomMessageEventContent, message::RoomMessageEventContent,
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent}, power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
redaction::RoomRedactionEventContent, redaction::RoomRedactionEventContent,
}, },
tag::{TagEvent, TagEventContent, TagInfo}, tag::{TagEvent, TagEventContent, TagInfo},
RoomAccountDataEventType, StateEventType,
}, },
EventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, RoomId, UserId,
}; };
use crate::{ use crate::{

View file

@ -1,4 +1,4 @@
use conduwuit_core::{err, Err, Result}; use conduwuit_core::{Err, Result, err};
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId}; use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
use service::Services; use service::Services;

View file

@ -3,34 +3,35 @@ use std::fmt::Write;
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
debug_info, error, info, is_equal_to, utils, utils::ReadyExt, warn, Error, PduBuilder, Result, Error, PduBuilder, Result, debug_info, error, info, is_equal_to, utils, utils::ReadyExt, warn,
}; };
use futures::{FutureExt, StreamExt}; use futures::{FutureExt, StreamExt};
use register::RegistrationKind; use register::RegistrationKind;
use ruma::{ use ruma::{
OwnedRoomId, UserId,
api::client::{ api::client::{
account::{ account::{
change_password, check_registration_token_validity, deactivate, get_3pids, ThirdPartyIdRemovalStatus, change_password, check_registration_token_validity,
get_username_availability, deactivate, get_3pids, get_username_availability,
register::{self, LoginType}, register::{self, LoginType},
request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn,
whoami, ThirdPartyIdRemovalStatus, whoami,
}, },
error::ErrorKind, error::ErrorKind,
uiaa::{AuthFlow, AuthType, UiaaInfo}, uiaa::{AuthFlow, AuthType, UiaaInfo},
}, },
events::{ events::{
GlobalAccountDataEventType, StateEventType,
room::{ room::{
message::RoomMessageEventContent, message::RoomMessageEventContent,
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent}, power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
}, },
GlobalAccountDataEventType, StateEventType,
}, },
push, OwnedRoomId, UserId, push,
}; };
use service::Services; use service::Services;
use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH, join_room_by_id_helper};
use crate::Ruma; use crate::Ruma;
const RANDOM_USER_ID_LENGTH: usize = 10; const RANDOM_USER_ID_LENGTH: usize = 10;
@ -218,12 +219,20 @@ pub(crate) async fn register_route(
}; };
if body.body.login_type == Some(LoginType::ApplicationService) { if body.body.login_type == Some(LoginType::ApplicationService) {
if let Some(ref info) = body.appservice_info { match body.appservice_info {
if !info.is_user_match(&user_id) { | Some(ref info) =>
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace.")); if !info.is_user_match(&user_id) {
} return Err(Error::BadRequest(
} else { ErrorKind::Exclusive,
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token.")); "User is not in namespace.",
));
},
| _ => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing appservice token.",
));
},
} }
} else if services.appservice.is_exclusive_user_id(&user_id).await { } else if services.appservice.is_exclusive_user_id(&user_id).await {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice.")); return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
@ -256,33 +265,39 @@ pub(crate) async fn register_route(
}; };
if !skip_auth { if !skip_auth {
if let Some(auth) = &body.auth { match &body.auth {
let (worked, uiaainfo) = services | Some(auth) => {
.uiaa let (worked, uiaainfo) = services
.try_auth( .uiaa
&UserId::parse_with_server_name("", services.globals.server_name()) .try_auth(
.expect("we know this is valid"), &UserId::parse_with_server_name("", services.globals.server_name())
"".into(), .expect("we know this is valid"),
auth, "".into(),
&uiaainfo, auth,
) &uiaainfo,
.await?; )
if !worked { .await?;
return Err(Error::Uiaa(uiaainfo)); if !worked {
} return Err(Error::Uiaa(uiaainfo));
// Success! }
} else if let Some(json) = body.json_body { // Success!
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); },
services.uiaa.create( | _ => match body.json_body {
&UserId::parse_with_server_name("", services.globals.server_name()) | Some(json) => {
.expect("we know this is valid"), uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
"".into(), services.uiaa.create(
&uiaainfo, &UserId::parse_with_server_name("", services.globals.server_name())
&json, .expect("we know this is valid"),
); "".into(),
return Err(Error::Uiaa(uiaainfo)); &uiaainfo,
} else { &json,
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); );
return Err(Error::Uiaa(uiaainfo));
},
| _ => {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
},
},
} }
} }
@ -463,7 +478,7 @@ pub(crate) async fn register_route(
} }
if let Some(room_server_name) = room.server_name() { if let Some(room_server_name) = room.server_name() {
if let Err(e) = join_room_by_id_helper( match join_room_by_id_helper(
&services, &services,
&user_id, &user_id,
&room_id, &room_id,
@ -475,10 +490,15 @@ pub(crate) async fn register_route(
.boxed() .boxed()
.await .await
{ {
// don't return this error so we don't fail registrations | Err(e) => {
error!("Failed to automatically join room {room} for user {user_id}: {e}"); // don't return this error so we don't fail registrations
} else { error!(
info!("Automatically joined room {room} for user {user_id}"); "Failed to automatically join room {room} for user {user_id}: {e}"
);
},
| _ => {
info!("Automatically joined room {room} for user {user_id}");
},
}; };
} }
} }
@ -532,26 +552,32 @@ pub(crate) async fn change_password_route(
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { match &body.auth {
let (worked, uiaainfo) = services | Some(auth) => {
.uiaa let (worked, uiaainfo) = services
.try_auth(sender_user, sender_device, auth, &uiaainfo) .uiaa
.await?; .try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { },
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); | _ => match body.json_body {
services | Some(json) => {
.uiaa uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.create(sender_user, sender_device, &uiaainfo, &json); services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { },
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); | _ => {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
},
},
} }
services services
@ -636,25 +662,31 @@ pub(crate) async fn deactivate_route(
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { match &body.auth {
let (worked, uiaainfo) = services | Some(auth) => {
.uiaa let (worked, uiaainfo) = services
.try_auth(sender_user, sender_device, auth, &uiaainfo) .uiaa
.await?; .try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { },
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); | _ => match body.json_body {
services | Some(json) => {
.uiaa uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.create(sender_user, sender_device, &uiaainfo, &json); services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { },
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); | _ => {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
},
},
} }
// Remove profile pictures and display name // Remove profile pictures and display name
@ -809,7 +841,7 @@ pub async fn full_user_deactivate(
power_levels_content.users.remove(user_id); power_levels_content.users.remove(user_id);
// ignore errors so deactivation doesn't fail // ignore errors so deactivation doesn't fail
if let Err(e) = services match services
.rooms .rooms
.timeline .timeline
.build_and_append_pdu( .build_and_append_pdu(
@ -820,9 +852,12 @@ pub async fn full_user_deactivate(
) )
.await .await
{ {
warn!(%room_id, %user_id, "Failed to demote user's own power level: {e}"); | Err(e) => {
} else { warn!(%room_id, %user_id, "Failed to demote user's own power level: {e}");
info!("Demoted {user_id} in {room_id} as part of account deactivation"); },
| _ => {
info!("Demoted {user_id} in {room_id} as part of account deactivation");
},
} }
} }
} }

View file

@ -1,6 +1,7 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err}; use conduwuit::{Err, err};
use ruma::{ use ruma::{
RoomId, UserId,
api::client::config::{ api::client::config::{
get_global_account_data, get_room_account_data, set_global_account_data, get_global_account_data, get_room_account_data, set_global_account_data,
set_room_account_data, set_room_account_data,
@ -10,12 +11,11 @@ use ruma::{
GlobalAccountDataEventType, RoomAccountDataEventType, GlobalAccountDataEventType, RoomAccountDataEventType,
}, },
serde::Raw, serde::Raw,
RoomId, UserId,
}; };
use serde::Deserialize; use serde::Deserialize;
use serde_json::{json, value::RawValue as RawJsonValue}; use serde_json::{json, value::RawValue as RawJsonValue};
use crate::{service::Services, Result, Ruma}; use crate::{Result, Ruma, service::Services};
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}` /// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
/// ///

View file

@ -1,10 +1,10 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{debug, Err, Result}; use conduwuit::{Err, Result, debug};
use futures::StreamExt; use futures::StreamExt;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use ruma::{ use ruma::{
api::client::alias::{create_alias, delete_alias, get_alias},
OwnedServerName, RoomAliasId, RoomId, OwnedServerName, RoomAliasId, RoomId,
api::client::alias::{create_alias, delete_alias, get_alias},
}; };
use service::Services; use service::Services;
@ -128,18 +128,26 @@ async fn room_available_servers(
// insert our server as the very first choice if in list, else check if we can // insert our server as the very first choice if in list, else check if we can
// prefer the room alias server first // prefer the room alias server first
if let Some(server_index) = servers match servers
.iter() .iter()
.position(|server_name| services.globals.server_is_ours(server_name)) .position(|server_name| services.globals.server_is_ours(server_name))
{ {
servers.swap_remove(server_index); | Some(server_index) => {
servers.insert(0, services.globals.server_name().to_owned()); servers.swap_remove(server_index);
} else if let Some(alias_server_index) = servers servers.insert(0, services.globals.server_name().to_owned());
.iter() },
.position(|server| server == room_alias.server_name()) | _ => {
{ match servers
servers.swap_remove(alias_server_index); .iter()
servers.insert(0, room_alias.server_name().into()); .position(|server| server == room_alias.server_name())
{
| Some(alias_server_index) => {
servers.swap_remove(alias_server_index);
servers.insert(0, room_alias.server_name().into());
},
| _ => {},
}
},
} }
servers servers

View file

@ -1,5 +1,5 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err, Result}; use conduwuit::{Err, Result, err};
use ruma::api::{appservice::ping, client::appservice::request_ping}; use ruma::api::{appservice::ping, client::appservice::request_ping};
use crate::Ruma; use crate::Ruma;

View file

@ -1,6 +1,7 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err}; use conduwuit::{Err, err};
use ruma::{ use ruma::{
UInt,
api::client::backup::{ api::client::backup::{
add_backup_keys, add_backup_keys_for_room, add_backup_keys_for_session, add_backup_keys, add_backup_keys_for_room, add_backup_keys_for_session,
create_backup_version, delete_backup_keys, delete_backup_keys_for_room, create_backup_version, delete_backup_keys, delete_backup_keys_for_room,
@ -8,7 +9,6 @@ use ruma::{
get_backup_keys_for_room, get_backup_keys_for_session, get_latest_backup_info, get_backup_keys_for_room, get_backup_keys_for_session, get_latest_backup_info,
update_backup_version, update_backup_version,
}, },
UInt,
}; };
use crate::{Result, Ruma}; use crate::{Result, Ruma};

View file

@ -3,11 +3,11 @@ use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{Result, Server}; use conduwuit::{Result, Server};
use ruma::{ use ruma::{
RoomVersionId,
api::client::discovery::get_capabilities::{ api::client::discovery::get_capabilities::{
self, Capabilities, GetLoginTokenCapability, RoomVersionStability, self, Capabilities, GetLoginTokenCapability, RoomVersionStability,
RoomVersionsCapability, ThirdPartyIdChangesCapability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
}, },
RoomVersionId,
}; };
use serde_json::json; use serde_json::json;

View file

@ -1,23 +1,22 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, err, ref_at, Err, PduEvent, Result, at, err, ref_at,
utils::{ utils::{
IterStream,
future::TryExtExt, future::TryExtExt,
stream::{BroadbandExt, ReadyExt, TryIgnore, WidebandExt}, stream::{BroadbandExt, ReadyExt, TryIgnore, WidebandExt},
IterStream,
}, },
Err, PduEvent, Result,
}; };
use futures::{ use futures::{
future::{join, join3, try_join3, OptionFuture},
FutureExt, StreamExt, TryFutureExt, TryStreamExt, FutureExt, StreamExt, TryFutureExt, TryStreamExt,
future::{OptionFuture, join, join3, try_join3},
}; };
use ruma::{api::client::context::get_context, events::StateEventType, OwnedEventId, UserId}; use ruma::{OwnedEventId, UserId, api::client::context::get_context, events::StateEventType};
use service::rooms::{lazy_loading, lazy_loading::Options, short::ShortStateKey}; use service::rooms::{lazy_loading, lazy_loading::Options, short::ShortStateKey};
use crate::{ use crate::{
client::message::{event_filter, ignored_filter, lazy_loading_witness, visibility_filter},
Ruma, Ruma,
client::message::{event_filter, ignored_filter, lazy_loading_witness, visibility_filter},
}; };
const LIMIT_MAX: usize = 100; const LIMIT_MAX: usize = 100;

View file

@ -1,18 +1,18 @@
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{err, Err}; use conduwuit::{Err, err};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch,
api::client::{ api::client::{
device::{self, delete_device, delete_devices, get_device, get_devices, update_device}, device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
error::ErrorKind, error::ErrorKind,
uiaa::{AuthFlow, AuthType, UiaaInfo}, uiaa::{AuthFlow, AuthType, UiaaInfo},
}, },
MilliSecondsSinceUnixEpoch,
}; };
use super::SESSION_ID_LENGTH; use super::SESSION_ID_LENGTH;
use crate::{utils, Error, Result, Ruma}; use crate::{Error, Result, Ruma, utils};
/// # `GET /_matrix/client/r0/devices` /// # `GET /_matrix/client/r0/devices`
/// ///
@ -107,25 +107,31 @@ pub(crate) async fn delete_device_route(
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { match &body.auth {
let (worked, uiaainfo) = services | Some(auth) => {
.uiaa let (worked, uiaainfo) = services
.try_auth(sender_user, sender_device, auth, &uiaainfo) .uiaa
.await?; .try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked { if !worked {
return Err!(Uiaa(uiaainfo)); return Err!(Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { },
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); | _ => match body.json_body {
services | Some(json) => {
.uiaa uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.create(sender_user, sender_device, &uiaainfo, &json); services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
return Err!(Uiaa(uiaainfo)); return Err!(Uiaa(uiaainfo));
} else { },
return Err!(Request(NotJson("Not json."))); | _ => {
return Err!(Request(NotJson("Not json.")));
},
},
} }
services services
@ -164,25 +170,31 @@ pub(crate) async fn delete_devices_route(
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { match &body.auth {
let (worked, uiaainfo) = services | Some(auth) => {
.uiaa let (worked, uiaainfo) = services
.try_auth(sender_user, sender_device, auth, &uiaainfo) .uiaa
.await?; .try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { },
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); | _ => match body.json_body {
services | Some(json) => {
.uiaa uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.create(sender_user, sender_device, &uiaainfo, &json); services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { },
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); | _ => {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
},
},
} }
for device_id in &body.devices { for device_id in &body.devices {

View file

@ -1,8 +1,9 @@
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{info, warn, Err, Error, Result}; use conduwuit::{Err, Error, Result, info, warn};
use futures::{StreamExt, TryFutureExt}; use futures::{StreamExt, TryFutureExt};
use ruma::{ use ruma::{
OwnedRoomId, RoomId, ServerName, UInt, UserId,
api::{ api::{
client::{ client::{
directory::{ directory::{
@ -16,13 +17,13 @@ use ruma::{
}, },
directory::{Filter, PublicRoomJoinRule, PublicRoomsChunk, RoomNetwork}, directory::{Filter, PublicRoomJoinRule, PublicRoomsChunk, RoomNetwork},
events::{ events::{
StateEventType,
room::{ room::{
join_rules::{JoinRule, RoomJoinRulesEventContent}, join_rules::{JoinRule, RoomJoinRulesEventContent},
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent}, power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
}, },
StateEventType,
}, },
uint, OwnedRoomId, RoomId, ServerName, UInt, UserId, uint,
}; };
use service::Services; use service::Services;
@ -365,30 +366,34 @@ async fn user_can_publish_room(
user_id: &UserId, user_id: &UserId,
room_id: &RoomId, room_id: &RoomId,
) -> Result<bool> { ) -> Result<bool> {
if let Ok(event) = services match services
.rooms .rooms
.state_accessor .state_accessor
.room_state_get(room_id, &StateEventType::RoomPowerLevels, "") .room_state_get(room_id, &StateEventType::RoomPowerLevels, "")
.await .await
{ {
serde_json::from_str(event.content.get()) | Ok(event) => serde_json::from_str(event.content.get())
.map_err(|_| Error::bad_database("Invalid event content for m.room.power_levels")) .map_err(|_| Error::bad_database("Invalid event content for m.room.power_levels"))
.map(|content: RoomPowerLevelsEventContent| { .map(|content: RoomPowerLevelsEventContent| {
RoomPowerLevels::from(content) RoomPowerLevels::from(content)
.user_can_send_state(user_id, StateEventType::RoomHistoryVisibility) .user_can_send_state(user_id, StateEventType::RoomHistoryVisibility)
}) }),
} else if let Ok(event) = services | _ => {
.rooms match services
.state_accessor .rooms
.room_state_get(room_id, &StateEventType::RoomCreate, "") .state_accessor
.await .room_state_get(room_id, &StateEventType::RoomCreate, "")
{ .await
Ok(event.sender == user_id) {
} else { | Ok(event) => Ok(event.sender == user_id),
return Err(Error::BadRequest( | _ => {
ErrorKind::forbidden(), return Err(Error::BadRequest(
"User is not allowed to publish this room", ErrorKind::forbidden(),
)); "User is not allowed to publish this room",
));
},
}
},
} }
} }

View file

@ -1,9 +1,10 @@
use std::collections::{BTreeMap, HashMap, HashSet}; use std::collections::{BTreeMap, HashMap, HashSet};
use axum::extract::State; use axum::extract::State;
use conduwuit::{debug, err, info, result::NotFound, utils, Err, Error, Result}; use conduwuit::{Err, Error, Result, debug, err, info, result::NotFound, utils};
use futures::{stream::FuturesUnordered, StreamExt}; use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{ use ruma::{
OneTimeKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
@ -17,14 +18,13 @@ use ruma::{
}, },
encryption::CrossSigningKey, encryption::CrossSigningKey,
serde::Raw, serde::Raw,
OneTimeKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
}; };
use serde_json::json; use serde_json::json;
use super::SESSION_ID_LENGTH; use super::SESSION_ID_LENGTH;
use crate::{ use crate::{
service::{users::parse_master_key, Services},
Ruma, Ruma,
service::{Services, users::parse_master_key},
}; };
/// # `POST /_matrix/client/r0/keys/upload` /// # `POST /_matrix/client/r0/keys/upload`
@ -126,7 +126,7 @@ pub(crate) async fn upload_signing_keys_route(
auth_error: None, auth_error: None,
}; };
if let Ok(exists) = check_for_new_keys( match check_for_new_keys(
services, services,
sender_user, sender_user,
body.self_signing_key.as_ref(), body.self_signing_key.as_ref(),
@ -136,32 +136,45 @@ pub(crate) async fn upload_signing_keys_route(
.await .await
.inspect_err(|e| info!(?e)) .inspect_err(|e| info!(?e))
{ {
if let Some(result) = exists { | Ok(exists) => {
// No-op, they tried to reupload the same set of keys if let Some(result) = exists {
// (lost connection for example) // No-op, they tried to reupload the same set of keys
return Ok(result); // (lost connection for example)
} return Ok(result);
debug!("Skipping UIA in accordance with MSC3967, the user didn't have any existing keys"); }
// Some of the keys weren't found, so we let them upload debug!(
} else if let Some(auth) = &body.auth { "Skipping UIA in accordance with MSC3967, the user didn't have any existing keys"
let (worked, uiaainfo) = services );
.uiaa // Some of the keys weren't found, so we let them upload
.try_auth(sender_user, sender_device, auth, &uiaainfo) },
.await?; | _ => {
match &body.auth {
| Some(auth) => {
let (worked, uiaainfo) = services
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { },
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); | _ => match body.json_body {
services | Some(json) => {
.uiaa uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.create(sender_user, sender_device, &uiaainfo, &json); services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { },
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); | _ => {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
},
},
}
},
} }
services services
@ -471,37 +484,40 @@ where
.collect(); .collect();
while let Some((server, response)) = futures.next().await { while let Some((server, response)) = futures.next().await {
if let Ok(response) = response { match response {
for (user, master_key) in response.master_keys { | Ok(response) => {
let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?; for (user, master_key) in response.master_keys {
let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?;
if let Ok(our_master_key) = services if let Ok(our_master_key) = services
.users .users
.get_key(&master_key_id, sender_user, &user, &allowed_signatures) .get_key(&master_key_id, sender_user, &user, &allowed_signatures)
.await .await
{ {
let (_, mut our_master_key) = parse_master_key(&user, &our_master_key)?; let (_, mut our_master_key) = parse_master_key(&user, &our_master_key)?;
master_key.signatures.append(&mut our_master_key.signatures); master_key.signatures.append(&mut our_master_key.signatures);
}
let json = serde_json::to_value(master_key).expect("to_value always works");
let raw = serde_json::from_value(json).expect("Raw::from_value always works");
services
.users
.add_cross_signing_keys(
&user, &raw, &None, &None,
false, /* Dont notify. A notification would trigger another key
* request resulting in an endless loop */
)
.await?;
if let Some(raw) = raw {
master_keys.insert(user.clone(), raw);
}
} }
let json = serde_json::to_value(master_key).expect("to_value always works");
let raw = serde_json::from_value(json).expect("Raw::from_value always works");
services
.users
.add_cross_signing_keys(
&user, &raw, &None, &None,
false, /* Dont notify. A notification would trigger another key request
* resulting in an endless loop */
)
.await?;
if let Some(raw) = raw {
master_keys.insert(user.clone(), raw);
}
}
self_signing_keys.extend(response.self_signing_keys); self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys); device_keys.extend(response.device_keys);
} else { },
failures.insert(server.to_string(), json!({})); | _ => {
failures.insert(server.to_string(), json!({}));
},
} }
} }

View file

@ -3,16 +3,16 @@ use std::time::Duration;
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
err, Err, Result, err,
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize}, utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
Err, Result,
}; };
use conduwuit_service::{ use conduwuit_service::{
media::{Dim, FileMeta, CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN, MXC_LENGTH},
Services, Services,
media::{CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN, Dim, FileMeta, MXC_LENGTH},
}; };
use reqwest::Url; use reqwest::Url;
use ruma::{ use ruma::{
Mxc, UserId,
api::client::{ api::client::{
authenticated_media::{ authenticated_media::{
get_content, get_content_as_filename, get_content_thumbnail, get_media_config, get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
@ -20,7 +20,6 @@ use ruma::{
}, },
media::create_content, media::create_content,
}, },
Mxc, UserId,
}; };
use crate::Ruma; use crate::Ruma;

View file

@ -3,21 +3,20 @@
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
err, Err, Result, err,
utils::{content_disposition::make_content_disposition, math::ruma_from_usize}, utils::{content_disposition::make_content_disposition, math::ruma_from_usize},
Err, Result,
}; };
use conduwuit_service::media::{Dim, FileMeta, CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN}; use conduwuit_service::media::{CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN, Dim, FileMeta};
use reqwest::Url; use reqwest::Url;
use ruma::{ use ruma::{
Mxc,
api::client::media::{ api::client::media::{
create_content, get_content, get_content_as_filename, get_content_thumbnail, create_content, get_content, get_content_as_filename, get_content_thumbnail,
get_media_config, get_media_preview, get_media_config, get_media_preview,
}, },
Mxc,
}; };
use crate::{client::create_content_route, Ruma, RumaResponse}; use crate::{Ruma, RumaResponse, client::create_content_route};
/// # `GET /_matrix/media/v3/config` /// # `GET /_matrix/media/v3/config`
/// ///
@ -142,46 +141,52 @@ pub(crate) async fn get_content_legacy_route(
media_id: &body.media_id, media_id: &body.media_id,
}; };
if let Some(FileMeta { match services.media.get(&mxc).await? {
content, | Some(FileMeta {
content_type, content,
content_disposition, content_type,
}) = services.media.get(&mxc).await? content_disposition,
{ }) => {
let content_disposition = let content_disposition = make_content_disposition(
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None); content_disposition.as_ref(),
content_type.as_deref(),
None,
);
Ok(get_content::v3::Response { Ok(get_content::v3::Response {
file: content.expect("entire file contents"), file: content.expect("entire file contents"),
content_type: content_type.map(Into::into), content_type: content_type.map(Into::into),
content_disposition: Some(content_disposition), content_disposition: Some(content_disposition),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
}) })
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { },
let response = services | _ =>
.media if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
.fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms) let response = services
.await .media
.map_err(|e| { .fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms)
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) .await
})?; .map_err(|e| {
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}"))))
})?;
let content_disposition = make_content_disposition( let content_disposition = make_content_disposition(
response.content_disposition.as_ref(), response.content_disposition.as_ref(),
response.content_type.as_deref(), response.content_type.as_deref(),
None, None,
); );
Ok(get_content::v3::Response { Ok(get_content::v3::Response {
file: response.file, file: response.file,
content_type: response.content_type, content_type: response.content_type,
content_disposition: Some(content_disposition), content_disposition: Some(content_disposition),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
}) })
} else { } else {
Err!(Request(NotFound("Media not found."))) Err!(Request(NotFound("Media not found.")))
},
} }
} }
@ -227,49 +232,52 @@ pub(crate) async fn get_content_as_filename_legacy_route(
media_id: &body.media_id, media_id: &body.media_id,
}; };
if let Some(FileMeta { match services.media.get(&mxc).await? {
content, | Some(FileMeta {
content_type, content,
content_disposition, content_type,
}) = services.media.get(&mxc).await? content_disposition,
{ }) => {
let content_disposition = make_content_disposition( let content_disposition = make_content_disposition(
content_disposition.as_ref(), content_disposition.as_ref(),
content_type.as_deref(), content_type.as_deref(),
Some(&body.filename), Some(&body.filename),
); );
Ok(get_content_as_filename::v3::Response { Ok(get_content_as_filename::v3::Response {
file: content.expect("entire file contents"), file: content.expect("entire file contents"),
content_type: content_type.map(Into::into), content_type: content_type.map(Into::into),
content_disposition: Some(content_disposition), content_disposition: Some(content_disposition),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
}) })
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { },
let response = services | _ =>
.media if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
.fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms) let response = services
.await .media
.map_err(|e| { .fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms)
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) .await
})?; .map_err(|e| {
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}"))))
})?;
let content_disposition = make_content_disposition( let content_disposition = make_content_disposition(
response.content_disposition.as_ref(), response.content_disposition.as_ref(),
response.content_type.as_deref(), response.content_type.as_deref(),
None, None,
); );
Ok(get_content_as_filename::v3::Response { Ok(get_content_as_filename::v3::Response {
content_disposition: Some(content_disposition), content_disposition: Some(content_disposition),
content_type: response.content_type, content_type: response.content_type,
file: response.file, file: response.file,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
}) })
} else { } else {
Err!(Request(NotFound("Media not found."))) Err!(Request(NotFound("Media not found.")))
},
} }
} }
@ -315,46 +323,52 @@ pub(crate) async fn get_content_thumbnail_legacy_route(
}; };
let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?; let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?;
if let Some(FileMeta { match services.media.get_thumbnail(&mxc, &dim).await? {
content, | Some(FileMeta {
content_type, content,
content_disposition, content_type,
}) = services.media.get_thumbnail(&mxc, &dim).await? content_disposition,
{ }) => {
let content_disposition = let content_disposition = make_content_disposition(
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None); content_disposition.as_ref(),
content_type.as_deref(),
None,
);
Ok(get_content_thumbnail::v3::Response { Ok(get_content_thumbnail::v3::Response {
file: content.expect("entire file contents"), file: content.expect("entire file contents"),
content_type: content_type.map(Into::into), content_type: content_type.map(Into::into),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition: Some(content_disposition), content_disposition: Some(content_disposition),
}) })
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { },
let response = services | _ =>
.media if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
.fetch_remote_thumbnail_legacy(&body) let response = services
.await .media
.map_err(|e| { .fetch_remote_thumbnail_legacy(&body)
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) .await
})?; .map_err(|e| {
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}"))))
})?;
let content_disposition = make_content_disposition( let content_disposition = make_content_disposition(
response.content_disposition.as_ref(), response.content_disposition.as_ref(),
response.content_type.as_deref(), response.content_type.as_deref(),
None, None,
); );
Ok(get_content_thumbnail::v3::Response { Ok(get_content_thumbnail::v3::Response {
file: response.file, file: response.file,
content_type: response.content_type, content_type: response.content_type,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition: Some(content_disposition), content_disposition: Some(content_disposition),
}) })
} else { } else {
Err!(Request(NotFound("Media not found."))) Err!(Request(NotFound("Media not found.")))
},
} }
} }

View file

@ -9,51 +9,51 @@ use std::{
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
at, debug, debug_info, debug_warn, err, error, info, Err, PduEvent, Result, StateKey, at, debug, debug_info, debug_warn, err, error, info,
pdu::{gen_event_id_canonical_json, PduBuilder}, pdu::{PduBuilder, gen_event_id_canonical_json},
result::FlatOk, result::FlatOk,
state_res, trace, state_res, trace,
utils::{self, shuffle, IterStream, ReadyExt}, utils::{self, IterStream, ReadyExt, shuffle},
warn, Err, PduEvent, Result, StateKey, warn,
}; };
use futures::{join, FutureExt, StreamExt, TryFutureExt}; use futures::{FutureExt, StreamExt, TryFutureExt, join};
use ruma::{ use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedUserId, RoomId, RoomVersionId, ServerName, UserId,
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
knock::knock_room, knock::knock_room,
membership::{ membership::{
ban_user, forget_room, get_member_events, invite_user, join_room_by_id, ThirdPartySigned, ban_user, forget_room, get_member_events, invite_user,
join_room_by_id_or_alias, join_room_by_id, join_room_by_id_or_alias,
joined_members::{self, v3::RoomMember}, joined_members::{self, v3::RoomMember},
joined_rooms, kick_user, leave_room, unban_user, ThirdPartySigned, joined_rooms, kick_user, leave_room, unban_user,
}, },
}, },
federation::{self, membership::create_invite}, federation::{self, membership::create_invite},
}, },
canonical_json::to_canonical_value, canonical_json::to_canonical_value,
events::{ events::{
StateEventType,
room::{ room::{
join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent}, join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
message::RoomMessageEventContent, message::RoomMessageEventContent,
}, },
StateEventType,
}, },
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedUserId, RoomId, RoomVersionId, ServerName, UserId,
}; };
use service::{ use service::{
Services,
appservice::RegistrationInfo, appservice::RegistrationInfo,
pdu::gen_event_id, pdu::gen_event_id,
rooms::{ rooms::{
state::RoomMutexGuard, state::RoomMutexGuard,
state_compressor::{CompressedState, HashSetCompressStateEvent}, state_compressor::{CompressedState, HashSetCompressStateEvent},
}, },
Services,
}; };
use crate::{client::full_user_deactivate, Ruma}; use crate::{Ruma, client::full_user_deactivate};
/// Checks if the room is banned in any way possible and the sender user is not /// Checks if the room is banned in any way possible and the sender user is not
/// an admin. /// an admin.
@ -507,43 +507,54 @@ pub(crate) async fn invite_user_route(
) )
.await?; .await?;
if let invite_user::v3::InvitationRecipient::UserId { user_id } = &body.recipient { match &body.recipient {
let sender_ignored_recipient = services.users.user_is_ignored(sender_user, user_id); | invite_user::v3::InvitationRecipient::UserId { user_id } => {
let recipient_ignored_by_sender = services.users.user_is_ignored(user_id, sender_user); let sender_ignored_recipient = services.users.user_is_ignored(sender_user, user_id);
let recipient_ignored_by_sender =
services.users.user_is_ignored(user_id, sender_user);
let (sender_ignored_recipient, recipient_ignored_by_sender) = let (sender_ignored_recipient, recipient_ignored_by_sender) =
join!(sender_ignored_recipient, recipient_ignored_by_sender); join!(sender_ignored_recipient, recipient_ignored_by_sender);
if sender_ignored_recipient { if sender_ignored_recipient {
return Err!(Request(Forbidden( return Err!(Request(Forbidden(
"You cannot invite users you have ignored to rooms." "You cannot invite users you have ignored to rooms."
))); )));
}
if let Ok(target_user_membership) = services
.rooms
.state_accessor
.get_member(&body.room_id, user_id)
.await
{
if target_user_membership.membership == MembershipState::Ban {
return Err!(Request(Forbidden("User is banned from this room.")));
} }
}
if recipient_ignored_by_sender { if let Ok(target_user_membership) = services
// silently drop the invite to the recipient if they've been ignored by the .rooms
// sender, pretend it worked .state_accessor
return Ok(invite_user::v3::Response {}); .get_member(&body.room_id, user_id)
} .await
{
if target_user_membership.membership == MembershipState::Ban {
return Err!(Request(Forbidden("User is banned from this room.")));
}
}
invite_helper(&services, sender_user, user_id, &body.room_id, body.reason.clone(), false) if recipient_ignored_by_sender {
// silently drop the invite to the recipient if they've been ignored by the
// sender, pretend it worked
return Ok(invite_user::v3::Response {});
}
invite_helper(
&services,
sender_user,
user_id,
&body.room_id,
body.reason.clone(),
false,
)
.boxed() .boxed()
.await?; .await?;
Ok(invite_user::v3::Response {}) Ok(invite_user::v3::Response {})
} else { },
Err!(Request(NotFound("User not found."))) | _ => {
Err!(Request(NotFound("User not found.")))
},
} }
} }
@ -1830,38 +1841,46 @@ async fn remote_leave_room(
.collect() .collect()
.await; .await;
if let Ok(invite_state) = services match services
.rooms .rooms
.state_cache .state_cache
.invite_state(user_id, room_id) .invite_state(user_id, room_id)
.await .await
{ {
servers.extend( | Ok(invite_state) => {
invite_state servers.extend(
.iter() invite_state
.filter_map(|event| event.get_field("sender").ok().flatten()) .iter()
.filter_map(|sender: &str| UserId::parse(sender).ok()) .filter_map(|event| event.get_field("sender").ok().flatten())
.map(|user| user.server_name().to_owned()), .filter_map(|sender: &str| UserId::parse(sender).ok())
); .map(|user| user.server_name().to_owned()),
} else if let Ok(knock_state) = services );
.rooms },
.state_cache | _ => {
.knock_state(user_id, room_id) match services
.await .rooms
{ .state_cache
servers.extend( .knock_state(user_id, room_id)
knock_state .await
.iter() {
.filter_map(|event| event.get_field("sender").ok().flatten()) | Ok(knock_state) => {
.filter_map(|sender: &str| UserId::parse(sender).ok()) servers.extend(
.filter_map(|sender| { knock_state
if !services.globals.user_is_local(sender) { .iter()
Some(sender.server_name().to_owned()) .filter_map(|event| event.get_field("sender").ok().flatten())
} else { .filter_map(|sender: &str| UserId::parse(sender).ok())
None .filter_map(|sender| {
} if !services.globals.user_is_local(sender) {
}), Some(sender.server_name().to_owned())
); } else {
None
}
}),
);
},
| _ => {},
}
},
} }
if let Some(room_id_server_name) = room_id.server_name() { if let Some(room_id_server_name) = room_id.server_name() {

View file

@ -1,30 +1,29 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, Event, PduCount, PduEvent, Result, at,
utils::{ utils::{
IterStream, ReadyExt,
result::{FlatOk, LogErr}, result::{FlatOk, LogErr},
stream::{BroadbandExt, TryIgnore, WidebandExt}, stream::{BroadbandExt, TryIgnore, WidebandExt},
IterStream, ReadyExt,
}, },
Event, PduCount, PduEvent, Result,
}; };
use futures::{future::OptionFuture, pin_mut, FutureExt, StreamExt, TryFutureExt}; use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut};
use ruma::{ use ruma::{
RoomId, UserId,
api::{ api::{
client::{filter::RoomEventFilter, message::get_message_events},
Direction, Direction,
client::{filter::RoomEventFilter, message::get_message_events},
}, },
events::{AnyStateEvent, StateEventType, TimelineEventType, TimelineEventType::*}, events::{AnyStateEvent, StateEventType, TimelineEventType, TimelineEventType::*},
serde::Raw, serde::Raw,
RoomId, UserId,
}; };
use service::{ use service::{
Services,
rooms::{ rooms::{
lazy_loading, lazy_loading,
lazy_loading::{Options, Witness}, lazy_loading::{Options, Witness},
timeline::PdusIterItem, timeline::PdusIterItem,
}, },
Services,
}; };
use crate::Ruma; use crate::Ruma;

View file

@ -70,37 +70,38 @@ pub(crate) async fn get_presence_route(
} }
} }
if let Some(presence) = presence_event { match presence_event {
let status_msg = if presence | Some(presence) => {
.content let status_msg = if presence
.status_msg
.as_ref()
.is_some_and(String::is_empty)
{
None
} else {
presence.content.status_msg
};
let last_active_ago = match presence.content.currently_active {
| Some(true) => None,
| _ => presence
.content .content
.last_active_ago .status_msg
.map(|millis| Duration::from_millis(millis.into())), .as_ref()
}; .is_some_and(String::is_empty)
{
None
} else {
presence.content.status_msg
};
Ok(get_presence::v3::Response { let last_active_ago = match presence.content.currently_active {
// TODO: Should ruma just use the presenceeventcontent type here? | Some(true) => None,
status_msg, | _ => presence
currently_active: presence.content.currently_active, .content
last_active_ago, .last_active_ago
presence: presence.content.presence, .map(|millis| Duration::from_millis(millis.into())),
}) };
} else {
Err(Error::BadRequest( Ok(get_presence::v3::Response {
// TODO: Should ruma just use the presenceeventcontent type here?
status_msg,
currently_active: presence.content.currently_active,
last_active_ago,
presence: presence.content.presence,
})
},
| _ => Err(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"Presence state for this user was not found", "Presence state for this user was not found",
)) )),
} }
} }

View file

@ -2,12 +2,14 @@ use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
Err, Error, Result,
pdu::PduBuilder, pdu::PduBuilder,
utils::{stream::TryIgnore, IterStream}, utils::{IterStream, stream::TryIgnore},
warn, Err, Error, Result, warn,
}; };
use futures::{future::join3, StreamExt, TryStreamExt}; use futures::{StreamExt, TryStreamExt, future::join3};
use ruma::{ use ruma::{
OwnedMxcUri, OwnedRoomId, UserId,
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
@ -19,7 +21,6 @@ use ruma::{
}, },
events::room::member::{MembershipState, RoomMemberEventContent}, events::room::member::{MembershipState, RoomMemberEventContent},
presence::PresenceState, presence::PresenceState,
OwnedMxcUri, OwnedRoomId, UserId,
}; };
use service::Services; use service::Services;

View file

@ -1,6 +1,7 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err}; use conduwuit::{Err, err};
use ruma::{ use ruma::{
CanonicalJsonObject, CanonicalJsonValue,
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
push::{ push::{
@ -10,14 +11,13 @@ use ruma::{
}, },
}, },
events::{ events::{
push_rules::{PushRulesEvent, PushRulesEventContent},
GlobalAccountDataEventType, GlobalAccountDataEventType,
push_rules::{PushRulesEvent, PushRulesEventContent},
}, },
push::{ push::{
InsertPushRuleError, PredefinedContentRuleId, PredefinedOverrideRuleId, InsertPushRuleError, PredefinedContentRuleId, PredefinedOverrideRuleId,
RemovePushRuleError, Ruleset, RemovePushRuleError, Ruleset,
}, },
CanonicalJsonObject, CanonicalJsonValue,
}; };
use service::Services; use service::Services;

View file

@ -1,14 +1,14 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err, PduCount}; use conduwuit::{Err, PduCount, err};
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch,
api::client::{read_marker::set_read_marker, receipt::create_receipt}, api::client::{read_marker::set_read_marker, receipt::create_receipt},
events::{ events::{
receipt::{ReceiptThread, ReceiptType},
RoomAccountDataEventType, RoomAccountDataEventType,
receipt::{ReceiptThread, ReceiptType},
}, },
MilliSecondsSinceUnixEpoch,
}; };
use crate::{Result, Ruma}; use crate::{Result, Ruma};

View file

@ -3,7 +3,7 @@ use ruma::{
api::client::redact::redact_event, events::room::redaction::RoomRedactionEventContent, api::client::redact::redact_event, events::room::redaction::RoomRedactionEventContent,
}; };
use crate::{service::pdu::PduBuilder, Result, Ruma}; use crate::{Result, Ruma, service::pdu::PduBuilder};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`
/// ///

View file

@ -1,22 +1,21 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, PduCount, Result, at,
utils::{result::FlatOk, stream::WidebandExt, IterStream, ReadyExt}, utils::{IterStream, ReadyExt, result::FlatOk, stream::WidebandExt},
PduCount, Result,
}; };
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
EventId, RoomId, UInt, UserId,
api::{ api::{
Direction,
client::relations::{ client::relations::{
get_relating_events, get_relating_events_with_rel_type, get_relating_events, get_relating_events_with_rel_type,
get_relating_events_with_rel_type_and_event_type, get_relating_events_with_rel_type_and_event_type,
}, },
Direction,
}, },
events::{relation::RelationType, TimelineEventType}, events::{TimelineEventType, relation::RelationType},
EventId, RoomId, UInt, UserId,
}; };
use service::{rooms::timeline::PdusIterItem, Services}; use service::{Services, rooms::timeline::PdusIterItem};
use crate::Ruma; use crate::Ruma;

View file

@ -2,22 +2,22 @@ use std::time::Duration;
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{info, utils::ReadyExt, Err}; use conduwuit::{Err, info, utils::ReadyExt};
use rand::Rng; use rand::Rng;
use ruma::{ use ruma::{
EventId, RoomId, UserId,
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
room::{report_content, report_room}, room::{report_content, report_room},
}, },
events::room::message, events::room::message,
int, EventId, RoomId, UserId, int,
}; };
use tokio::time::sleep; use tokio::time::sleep;
use crate::{ use crate::{
debug_info, Error, Result, Ruma, debug_info,
service::{pdu::PduEvent, Services}, service::{Services, pdu::PduEvent},
Error, Result, Ruma,
}; };
/// # `POST /_matrix/client/v3/rooms/{roomId}/report` /// # `POST /_matrix/client/v3/rooms/{roomId}/report`

View file

@ -2,15 +2,17 @@ use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
debug_info, debug_warn, err, error, info, pdu::PduBuilder, warn, Err, Error, Result, StateKey, Err, Error, Result, StateKey, debug_info, debug_warn, err, error, info, pdu::PduBuilder, warn,
}; };
use futures::FutureExt; use futures::FutureExt;
use ruma::{ use ruma::{
CanonicalJsonObject, Int, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId, RoomVersionId,
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
room::{self, create_room}, room::{self, create_room},
}, },
events::{ events::{
TimelineEventType,
room::{ room::{
canonical_alias::RoomCanonicalAliasEventContent, canonical_alias::RoomCanonicalAliasEventContent,
create::RoomCreateEventContent, create::RoomCreateEventContent,
@ -22,16 +24,14 @@ use ruma::{
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
TimelineEventType,
}, },
int, int,
serde::{JsonObject, Raw}, serde::{JsonObject, Raw},
CanonicalJsonObject, Int, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId, RoomVersionId,
}; };
use serde_json::{json, value::to_raw_value}; use serde_json::{json, value::to_raw_value};
use service::{appservice::RegistrationInfo, Services}; use service::{Services, appservice::RegistrationInfo};
use crate::{client::invite_helper, Ruma}; use crate::{Ruma, client::invite_helper};
/// # `POST /_matrix/client/v3/createRoom` /// # `POST /_matrix/client/v3/createRoom`
/// ///
@ -68,10 +68,9 @@ pub(crate) async fn create_room_route(
)); ));
} }
let room_id: OwnedRoomId = if let Some(custom_room_id) = &body.room_id { let room_id: OwnedRoomId = match &body.room_id {
custom_room_id_check(&services, custom_room_id)? | Some(custom_room_id) => custom_room_id_check(&services, custom_room_id)?,
} else { | _ => RoomId::new(&services.server.name),
RoomId::new(&services.server.name)
}; };
// check if room ID doesn't already exist instead of erroring on auth check // check if room ID doesn't already exist instead of erroring on auth check
@ -114,10 +113,10 @@ pub(crate) async fn create_room_route(
.await; .await;
let state_lock = services.rooms.state.mutex.lock(&room_id).await; let state_lock = services.rooms.state.mutex.lock(&room_id).await;
let alias: Option<OwnedRoomAliasId> = if let Some(alias) = body.room_alias_name.as_ref() { let alias: Option<OwnedRoomAliasId> = match body.room_alias_name.as_ref() {
Some(room_alias_check(&services, alias, body.appservice_info.as_ref()).await?) | Some(alias) =>
} else { Some(room_alias_check(&services, alias, body.appservice_info.as_ref()).await?),
None | _ => None,
}; };
let room_version = match body.room_version.clone() { let room_version = match body.room_version.clone() {

View file

@ -1,9 +1,9 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err, Event, Result}; use conduwuit::{Err, Event, Result, err};
use futures::{future::try_join, FutureExt, TryFutureExt}; use futures::{FutureExt, TryFutureExt, future::try_join};
use ruma::api::client::room::get_room_event; use ruma::api::client::room::get_room_event;
use crate::{client::is_ignored_pdu, Ruma}; use crate::{Ruma, client::is_ignored_pdu};
/// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}` /// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}`
/// ///

View file

@ -1,8 +1,7 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, Err, PduEvent, Result, at,
utils::{stream::TryTools, BoolExt}, utils::{BoolExt, stream::TryTools},
Err, PduEvent, Result,
}; };
use futures::TryStreamExt; use futures::TryStreamExt;
use ruma::api::client::room::initial_sync::v3::{PaginationChunk, Request, Response}; use ruma::api::client::room::initial_sync::v3::{PaginationChunk, Request, Response};

View file

@ -1,19 +1,20 @@
use std::cmp::max; use std::cmp::max;
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, info, pdu::PduBuilder, Error, Result, StateKey}; use conduwuit::{Error, Result, StateKey, err, info, pdu::PduBuilder};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
CanonicalJsonObject, RoomId, RoomVersionId,
api::client::{error::ErrorKind, room::upgrade_room}, api::client::{error::ErrorKind, room::upgrade_room},
events::{ events::{
StateEventType, TimelineEventType,
room::{ room::{
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
tombstone::RoomTombstoneEventContent, tombstone::RoomTombstoneEventContent,
}, },
StateEventType, TimelineEventType,
}, },
int, CanonicalJsonObject, RoomId, RoomVersionId, int,
}; };
use serde_json::{json, value::to_raw_value}; use serde_json::{json, value::to_raw_value};

View file

@ -2,23 +2,22 @@ use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, is_true, Err, PduEvent, Result, at, is_true,
result::FlatOk, result::FlatOk,
utils::{stream::ReadyExt, IterStream}, utils::{IterStream, stream::ReadyExt},
Err, PduEvent, Result,
}; };
use futures::{future::OptionFuture, FutureExt, StreamExt, TryFutureExt, TryStreamExt}; use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, future::OptionFuture};
use ruma::{ use ruma::{
OwnedRoomId, RoomId, UInt, UserId,
api::client::search::search_events::{ api::client::search::search_events::{
self, self,
v3::{Criteria, EventContextResult, ResultCategories, ResultRoomEvents, SearchResult}, v3::{Criteria, EventContextResult, ResultCategories, ResultRoomEvents, SearchResult},
}, },
events::AnyStateEvent, events::AnyStateEvent,
serde::Raw, serde::Raw,
OwnedRoomId, RoomId, UInt, UserId,
}; };
use search_events::v3::{Request, Response}; use search_events::v3::{Request, Response};
use service::{rooms::search::RoomQuery, Services}; use service::{Services, rooms::search::RoomQuery};
use crate::Ruma; use crate::Ruma;

View file

@ -1,11 +1,11 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err}; use conduwuit::{Err, err};
use ruma::{api::client::message::send_message_event, events::MessageLikeEventType}; use ruma::{api::client::message::send_message_event, events::MessageLikeEventType};
use serde_json::from_str; use serde_json::from_str;
use crate::{service::pdu::PduBuilder, utils, Result, Ruma}; use crate::{Result, Ruma, service::pdu::PduBuilder, utils};
/// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}` /// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`
/// ///

View file

@ -2,9 +2,10 @@ use std::time::Duration;
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{debug, err, info, utils::ReadyExt, warn, Err}; use conduwuit::{Err, debug, err, info, utils::ReadyExt, warn};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
OwnedUserId, UserId,
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
session::{ session::{
@ -21,12 +22,11 @@ use ruma::{
}, },
uiaa, uiaa,
}, },
OwnedUserId, UserId,
}; };
use service::uiaa::SESSION_ID_LENGTH; use service::uiaa::SESSION_ID_LENGTH;
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{utils, utils::hash, Error, Result, Ruma}; use crate::{Error, Result, Ruma, utils, utils::hash};
/// # `GET /_matrix/client/v3/login` /// # `GET /_matrix/client/v3/login`
/// ///
@ -139,18 +139,20 @@ pub(crate) async fn login_route(
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?; })?;
if let Some(ref info) = body.appservice_info { match body.appservice_info {
if !info.is_user_match(&user_id) { | Some(ref info) =>
if !info.is_user_match(&user_id) {
return Err(Error::BadRequest(
ErrorKind::Exclusive,
"User is not in namespace.",
));
},
| _ => {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Exclusive, ErrorKind::MissingToken,
"User is not in namespace.", "Missing appservice token.",
)); ));
} },
} else {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing appservice token.",
));
} }
user_id user_id
@ -259,26 +261,32 @@ pub(crate) async fn login_token_route(
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { match &body.auth {
let (worked, uiaainfo) = services | Some(auth) => {
.uiaa let (worked, uiaainfo) = services
.try_auth(sender_user, sender_device, auth, &uiaainfo) .uiaa
.await?; .try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body.as_ref() { },
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); | _ => match body.json_body.as_ref() {
services | Some(json) => {
.uiaa uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.create(sender_user, sender_device, &uiaainfo, json); services
.uiaa
.create(sender_user, sender_device, &uiaainfo, json);
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { },
return Err!(Request(NotJson("No JSON body was sent when required."))); | _ => {
return Err!(Request(NotJson("No JSON body was sent when required.")));
},
},
} }
let login_token = utils::random_string(TOKEN_LENGTH); let login_token = utils::random_string(TOKEN_LENGTH);

View file

@ -5,18 +5,18 @@ use std::{
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
utils::{future::TryExtExt, stream::IterStream},
Err, Result, Err, Result,
utils::{future::TryExtExt, stream::IterStream},
}; };
use futures::{future::OptionFuture, StreamExt, TryFutureExt}; use futures::{StreamExt, TryFutureExt, future::OptionFuture};
use ruma::{ use ruma::{
api::client::space::get_hierarchy, OwnedRoomId, OwnedServerName, RoomId, UInt, UserId, OwnedRoomId, OwnedServerName, RoomId, UInt, UserId, api::client::space::get_hierarchy,
}; };
use service::{ use service::{
rooms::spaces::{
get_parent_children_via, summary_to_chunk, PaginationToken, SummaryAccessibility,
},
Services, Services,
rooms::spaces::{
PaginationToken, SummaryAccessibility, get_parent_children_via, summary_to_chunk,
},
}; };
use crate::Ruma; use crate::Ruma;

View file

@ -1,19 +1,19 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, pdu::PduBuilder, utils::BoolExt, Err, PduEvent, Result}; use conduwuit::{Err, PduEvent, Result, err, pdu::PduBuilder, utils::BoolExt};
use futures::TryStreamExt; use futures::TryStreamExt;
use ruma::{ use ruma::{
OwnedEventId, RoomId, UserId,
api::client::state::{get_state_events, get_state_events_for_key, send_state_event}, api::client::state::{get_state_events, get_state_events_for_key, send_state_event},
events::{ events::{
AnyStateEventContent, StateEventType,
room::{ room::{
canonical_alias::RoomCanonicalAliasEventContent, canonical_alias::RoomCanonicalAliasEventContent,
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent}, history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
join_rules::{JoinRule, RoomJoinRulesEventContent}, join_rules::{JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
}, },
AnyStateEventContent, StateEventType,
}, },
serde::Raw, serde::Raw,
OwnedEventId, RoomId, UserId,
}; };
use service::Services; use service::Services;

View file

@ -3,25 +3,25 @@ mod v4;
mod v5; mod v5;
use conduwuit::{ use conduwuit::{
utils::{
stream::{BroadbandExt, ReadyExt, TryIgnore},
IterStream,
},
PduCount, PduCount,
utils::{
IterStream,
stream::{BroadbandExt, ReadyExt, TryIgnore},
},
}; };
use futures::{pin_mut, StreamExt}; use futures::{StreamExt, pin_mut};
use ruma::{ use ruma::{
RoomId, UserId,
directory::RoomTypeFilter, directory::RoomTypeFilter,
events::TimelineEventType::{ events::TimelineEventType::{
self, Beacon, CallInvite, PollStart, RoomEncrypted, RoomMessage, Sticker, self, Beacon, CallInvite, PollStart, RoomEncrypted, RoomMessage, Sticker,
}, },
RoomId, UserId,
}; };
pub(crate) use self::{ pub(crate) use self::{
v3::sync_events_route, v4::sync_events_v4_route, v5::sync_events_v5_route, v3::sync_events_route, v4::sync_events_v4_route, v5::sync_events_v5_route,
}; };
use crate::{service::Services, Error, PduEvent, Result}; use crate::{Error, PduEvent, Result, service::Services};
pub(crate) const DEFAULT_BUMP_TYPES: &[TimelineEventType; 6] = pub(crate) const DEFAULT_BUMP_TYPES: &[TimelineEventType; 6] =
&[CallInvite, PollStart, Beacon, RoomEncrypted, RoomMessage, Sticker]; &[CallInvite, PollStart, Beacon, RoomEncrypted, RoomMessage, Sticker];

View file

@ -6,57 +6,55 @@ use std::{
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, err, error, extract_variant, is_equal_to, pair_of, PduCount, PduEvent, Result, at, err, error, extract_variant, is_equal_to, pair_of,
pdu::{Event, EventHash}, pdu::{Event, EventHash},
ref_at, ref_at,
result::FlatOk, result::FlatOk,
utils::{ utils::{
self, self, BoolExt, IterStream, ReadyExt, TryFutureExtExt,
math::ruma_from_u64, math::ruma_from_u64,
stream::{BroadbandExt, Tools, TryExpect, WidebandExt}, stream::{BroadbandExt, Tools, TryExpect, WidebandExt},
BoolExt, IterStream, ReadyExt, TryFutureExtExt,
}, },
PduCount, PduEvent, Result,
}; };
use conduwuit_service::{ use conduwuit_service::{
Services,
rooms::{ rooms::{
lazy_loading, lazy_loading,
lazy_loading::{Options, Witness}, lazy_loading::{Options, Witness},
short::ShortStateHash, short::ShortStateHash,
}, },
Services,
}; };
use futures::{ use futures::{
future::{join, join3, join4, join5, try_join, try_join4, OptionFuture},
FutureExt, StreamExt, TryFutureExt, TryStreamExt, FutureExt, StreamExt, TryFutureExt, TryStreamExt,
future::{OptionFuture, join, join3, join4, join5, try_join, try_join4},
}; };
use ruma::{ use ruma::{
DeviceId, EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId,
api::client::{ api::client::{
filter::FilterDefinition, filter::FilterDefinition,
sync::sync_events::{ sync::sync_events::{
self, self, DeviceLists, UnreadNotificationsCount,
v3::{ v3::{
Ephemeral, Filter, GlobalAccountData, InviteState, InvitedRoom, JoinedRoom, Ephemeral, Filter, GlobalAccountData, InviteState, InvitedRoom, JoinedRoom,
KnockState, KnockedRoom, LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms, KnockState, KnockedRoom, LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms,
State as RoomState, Timeline, ToDevice, State as RoomState, Timeline, ToDevice,
}, },
DeviceLists, UnreadNotificationsCount,
}, },
uiaa::UiaaResponse, uiaa::UiaaResponse,
}, },
events::{ events::{
presence::{PresenceEvent, PresenceEventContent},
room::member::{MembershipState, RoomMemberEventContent},
AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType, AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType,
TimelineEventType::*, TimelineEventType::*,
presence::{PresenceEvent, PresenceEventContent},
room::member::{MembershipState, RoomMemberEventContent},
}, },
serde::Raw, serde::Raw,
uint, DeviceId, EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId, uint,
}; };
use service::rooms::short::{ShortEventId, ShortStateKey}; use service::rooms::short::{ShortEventId, ShortStateKey};
use super::{load_timeline, share_encrypted_room}; use super::{load_timeline, share_encrypted_room};
use crate::{client::ignored_filter, Ruma, RumaResponse}; use crate::{Ruma, RumaResponse, client::ignored_filter};
#[derive(Default)] #[derive(Default)]
struct StateChanges { struct StateChanges {
@ -168,8 +166,8 @@ pub(crate) async fn build_sync_events(
let full_state = body.body.full_state; let full_state = body.body.full_state;
let filter = match body.body.filter.as_ref() { let filter = match body.body.filter.as_ref() {
| None => FilterDefinition::default(), | None => FilterDefinition::default(),
| Some(Filter::FilterDefinition(ref filter)) => filter.clone(), | Some(Filter::FilterDefinition(filter)) => filter.clone(),
| Some(Filter::FilterId(ref filter_id)) => services | Some(Filter::FilterId(filter_id)) => services
.users .users
.get_filter(sender_user, filter_id) .get_filter(sender_user, filter_id)
.await .await
@ -1016,34 +1014,37 @@ async fn calculate_state_incremental<'a>(
let lazy_state_ids: OptionFuture<_> = witness let lazy_state_ids: OptionFuture<_> = witness
.filter(|_| !full_state && !encrypted_room) .filter(|_| !full_state && !encrypted_room)
.map(|witness| { .map(|witness| {
witness StreamExt::into_future(
.iter() witness
.stream() .iter()
.broad_filter_map(|user_id| state_get_shorteventid(user_id)) .stream()
.into_future() .broad_filter_map(|user_id| state_get_shorteventid(user_id)),
)
}) })
.into(); .into();
let state_diff: OptionFuture<_> = (!full_state && state_changed) let state_diff: OptionFuture<_> = (!full_state && state_changed)
.then(|| { .then(|| {
services StreamExt::into_future(
.rooms services
.state_accessor .rooms
.state_added((since_shortstatehash, current_shortstatehash)) .state_accessor
.boxed() .state_added((since_shortstatehash, current_shortstatehash))
.into_future() .boxed(),
)
}) })
.into(); .into();
let current_state_ids: OptionFuture<_> = full_state let current_state_ids: OptionFuture<_> = full_state
.then(|| { .then(|| {
services StreamExt::into_future(
.rooms services
.state_accessor .rooms
.state_full_shortids(current_shortstatehash) .state_accessor
.expect_ok() .state_full_shortids(current_shortstatehash)
.boxed() .expect_ok()
.into_future() .boxed(),
)
}) })
.into(); .into();

View file

@ -6,37 +6,37 @@ use std::{
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
debug, error, extract_variant, Error, PduCount, Result, debug, error, extract_variant,
utils::{ utils::{
math::{ruma_from_usize, usize_from_ruma, usize_from_u64_truncated},
BoolExt, IterStream, ReadyExt, TryFutureExtExt, BoolExt, IterStream, ReadyExt, TryFutureExtExt,
math::{ruma_from_usize, usize_from_ruma, usize_from_u64_truncated},
}, },
warn, Error, PduCount, Result, warn,
}; };
use futures::{FutureExt, StreamExt, TryFutureExt}; use futures::{FutureExt, StreamExt, TryFutureExt};
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId,
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
sync::sync_events::{ sync::sync_events::{
self, self, DeviceLists, UnreadNotificationsCount,
v4::{SlidingOp, SlidingSyncRoomHero}, v4::{SlidingOp, SlidingSyncRoomHero},
DeviceLists, UnreadNotificationsCount,
}, },
}, },
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent},
AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType, AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType,
TimelineEventType::*, TimelineEventType::*,
room::member::{MembershipState, RoomMemberEventContent},
}, },
serde::Raw, serde::Raw,
uint, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId, uint,
}; };
use service::rooms::read_receipt::pack_receipts; use service::rooms::read_receipt::pack_receipts;
use super::{load_timeline, share_encrypted_room}; use super::{load_timeline, share_encrypted_room};
use crate::{ use crate::{
client::{filter_rooms, ignored_filter, sync::v5::TodoRooms, DEFAULT_BUMP_TYPES},
Ruma, Ruma,
client::{DEFAULT_BUMP_TYPES, filter_rooms, ignored_filter, sync::v5::TodoRooms},
}; };
pub(crate) const SINGLE_CONNECTION_SYNC: &str = "single_connection_sync"; pub(crate) const SINGLE_CONNECTION_SYNC: &str = "single_connection_sync";
@ -700,14 +700,13 @@ pub(crate) async fn sync_events_v4_route(
.await .await
.ok() .ok()
.or(name), .or(name),
avatar: if let Some(heroes_avatar) = heroes_avatar { avatar: match heroes_avatar {
ruma::JsOption::Some(heroes_avatar) | Some(heroes_avatar) => ruma::JsOption::Some(heroes_avatar),
} else { | _ => match services.rooms.state_accessor.get_avatar(room_id).await {
match services.rooms.state_accessor.get_avatar(room_id).await {
| ruma::JsOption::Some(avatar) => ruma::JsOption::from_option(avatar.url), | ruma::JsOption::Some(avatar) => ruma::JsOption::from_option(avatar.url),
| ruma::JsOption::Null => ruma::JsOption::Null, | ruma::JsOption::Null => ruma::JsOption::Null,
| ruma::JsOption::Undefined => ruma::JsOption::Undefined, | ruma::JsOption::Undefined => ruma::JsOption::Undefined,
} },
}, },
initial: Some(roomsince == &0), initial: Some(roomsince == &0),
is_dm: None, is_dm: None,

View file

@ -6,32 +6,33 @@ use std::{
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
debug, error, extract_variant, trace, Error, Result, TypeStateKey, debug, error, extract_variant, trace,
utils::{ utils::{
math::{ruma_from_usize, usize_from_ruma},
BoolExt, IterStream, ReadyExt, TryFutureExtExt, BoolExt, IterStream, ReadyExt, TryFutureExtExt,
math::{ruma_from_usize, usize_from_ruma},
}, },
warn, Error, Result, TypeStateKey, warn,
}; };
use futures::{FutureExt, StreamExt, TryFutureExt}; use futures::{FutureExt, StreamExt, TryFutureExt};
use ruma::{ use ruma::{
DeviceId, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId,
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
sync::sync_events::{self, DeviceLists, UnreadNotificationsCount}, sync::sync_events::{self, DeviceLists, UnreadNotificationsCount},
}, },
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent},
AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType, TimelineEventType, AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType, TimelineEventType,
room::member::{MembershipState, RoomMemberEventContent},
}, },
serde::Raw, serde::Raw,
uint, DeviceId, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId, uint,
}; };
use service::{rooms::read_receipt::pack_receipts, PduCount}; use service::{PduCount, rooms::read_receipt::pack_receipts};
use super::{filter_rooms, share_encrypted_room}; use super::{filter_rooms, share_encrypted_room};
use crate::{ use crate::{
client::{ignored_filter, sync::load_timeline, DEFAULT_BUMP_TYPES},
Ruma, Ruma,
client::{DEFAULT_BUMP_TYPES, ignored_filter, sync::load_timeline},
}; };
type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::v5::Request); type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::v5::Request);
@ -572,14 +573,13 @@ async fn process_rooms(
.await .await
.ok() .ok()
.or(name), .or(name),
avatar: if let Some(heroes_avatar) = heroes_avatar { avatar: match heroes_avatar {
ruma::JsOption::Some(heroes_avatar) | Some(heroes_avatar) => ruma::JsOption::Some(heroes_avatar),
} else { | _ => match services.rooms.state_accessor.get_avatar(room_id).await {
match services.rooms.state_accessor.get_avatar(room_id).await {
| ruma::JsOption::Some(avatar) => ruma::JsOption::from_option(avatar.url), | ruma::JsOption::Some(avatar) => ruma::JsOption::from_option(avatar.url),
| ruma::JsOption::Null => ruma::JsOption::Null, | ruma::JsOption::Null => ruma::JsOption::Null,
| ruma::JsOption::Undefined => ruma::JsOption::Undefined, | ruma::JsOption::Undefined => ruma::JsOption::Undefined,
} },
}, },
initial: Some(roomsince == &0), initial: Some(roomsince == &0),
is_dm: None, is_dm: None,

View file

@ -4,8 +4,8 @@ use axum::extract::State;
use ruma::{ use ruma::{
api::client::tag::{create_tag, delete_tag, get_tags}, api::client::tag::{create_tag, delete_tag, get_tags},
events::{ events::{
tag::{TagEvent, TagEventContent},
RoomAccountDataEventType, RoomAccountDataEventType,
tag::{TagEvent, TagEventContent},
}, },
}; };

View file

@ -1,5 +1,5 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{at, PduCount, PduEvent}; use conduwuit::{PduCount, PduEvent, at};
use futures::StreamExt; use futures::StreamExt;
use ruma::{api::client::threads::get_threads, uint}; use ruma::{api::client::threads::get_threads, uint};

View file

@ -1,8 +1,8 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{utils::math::Tried, Err}; use conduwuit::{Err, utils::math::Tried};
use ruma::api::client::typing::create_typing_event; use ruma::api::client::typing::create_typing_event;
use crate::{utils, Result, Ruma}; use crate::{Result, Ruma, utils};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`
/// ///
@ -27,37 +27,40 @@ pub(crate) async fn create_typing_event_route(
return Err!(Request(Forbidden("You are not in this room."))); return Err!(Request(Forbidden("You are not in this room.")));
} }
if let Typing::Yes(duration) = body.state { match body.state {
let duration = utils::clamp( | Typing::Yes(duration) => {
duration.as_millis().try_into().unwrap_or(u64::MAX), let duration = utils::clamp(
duration.as_millis().try_into().unwrap_or(u64::MAX),
services
.server
.config
.typing_client_timeout_min_s
.try_mul(1000)?,
services
.server
.config
.typing_client_timeout_max_s
.try_mul(1000)?,
);
services services
.server .rooms
.config .typing
.typing_client_timeout_min_s .typing_add(
.try_mul(1000)?, sender_user,
&body.room_id,
utils::millis_since_unix_epoch()
.checked_add(duration)
.expect("user typing timeout should not get this high"),
)
.await?;
},
| _ => {
services services
.server .rooms
.config .typing
.typing_client_timeout_max_s .typing_remove(sender_user, &body.room_id)
.try_mul(1000)?, .await?;
); },
services
.rooms
.typing
.typing_add(
sender_user,
&body.room_id,
utils::millis_since_unix_epoch()
.checked_add(duration)
.expect("user typing timeout should not get this high"),
)
.await?;
} else {
services
.rooms
.typing
.typing_remove(sender_user, &body.room_id)
.await?;
} }
// ping presence // ping presence

View file

@ -5,6 +5,7 @@ use axum_client_ip::InsecureClientIp;
use conduwuit::Err; use conduwuit::Err;
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
OwnedRoomId,
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
@ -19,7 +20,6 @@ use ruma::{
}, },
events::room::member::MembershipState, events::room::member::MembershipState,
presence::PresenceState, presence::PresenceState,
OwnedRoomId,
}; };
use super::{update_avatar_url, update_displayname}; use super::{update_avatar_url, update_displayname};
@ -499,15 +499,18 @@ pub(crate) async fn get_profile_key_route(
.users .users
.set_timezone(&body.user_id, response.tz.clone()); .set_timezone(&body.user_id, response.tz.clone());
if let Some(value) = response.custom_profile_fields.get(&body.key_name) { match response.custom_profile_fields.get(&body.key_name) {
profile_key_value.insert(body.key_name.clone(), value.clone()); | Some(value) => {
services.users.set_profile_key( profile_key_value.insert(body.key_name.clone(), value.clone());
&body.user_id, services.users.set_profile_key(
&body.key_name, &body.user_id,
Some(value.clone()), &body.key_name,
); Some(value.clone()),
} else { );
return Err!(Request(NotFound("The requested profile key does not exist."))); },
| _ => {
return Err!(Request(NotFound("The requested profile key does not exist.")));
},
} }
if profile_key_value.is_empty() { if profile_key_value.is_empty() {
@ -524,14 +527,17 @@ pub(crate) async fn get_profile_key_route(
return Err!(Request(NotFound("Profile was not found."))); return Err!(Request(NotFound("Profile was not found.")));
} }
if let Ok(value) = services match services
.users .users
.profile_key(&body.user_id, &body.key_name) .profile_key(&body.user_id, &body.key_name)
.await .await
{ {
profile_key_value.insert(body.key_name.clone(), value); | Ok(value) => {
} else { profile_key_value.insert(body.key_name.clone(), value);
return Err!(Request(NotFound("The requested profile key does not exist."))); },
| _ => {
return Err!(Request(NotFound("The requested profile key does not exist.")));
},
} }
if profile_key_value.is_empty() { if profile_key_value.is_empty() {

View file

@ -1,6 +1,6 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use axum::{extract::State, response::IntoResponse, Json}; use axum::{Json, extract::State, response::IntoResponse};
use futures::StreamExt; use futures::StreamExt;
use ruma::api::client::discovery::get_supported_versions; use ruma::api::client::discovery::get_supported_versions;

View file

@ -1,11 +1,11 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::utils::TryFutureExtExt; use conduwuit::utils::TryFutureExtExt;
use futures::{pin_mut, StreamExt}; use futures::{StreamExt, pin_mut};
use ruma::{ use ruma::{
api::client::user_directory::search_users, api::client::user_directory::search_users,
events::{ events::{
room::join_rules::{JoinRule, RoomJoinRulesEventContent},
StateEventType, StateEventType,
room::join_rules::{JoinRule, RoomJoinRulesEventContent},
}, },
}; };

View file

@ -1,10 +1,10 @@
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
use axum::extract::State; use axum::extract::State;
use base64::{engine::general_purpose, Engine as _}; use base64::{Engine as _, engine::general_purpose};
use conduwuit::{utils, Err}; use conduwuit::{Err, utils};
use hmac::{Hmac, Mac}; use hmac::{Hmac, Mac};
use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch, UserId}; use ruma::{SecondsSinceUnixEpoch, UserId, api::client::voip::get_turn_server_info};
use sha1::Sha1; use sha1::Sha1;
use crate::{Result, Ruma}; use crate::{Result, Ruma};

View file

@ -1,4 +1,4 @@
use axum::{extract::State, response::IntoResponse, Json}; use axum::{Json, extract::State, response::IntoResponse};
use ruma::api::client::{ use ruma::api::client::{
discovery::{ discovery::{
discover_homeserver::{self, HomeserverInfo, SlidingSyncProxyInfo}, discover_homeserver::{self, HomeserverInfo, SlidingSyncProxyInfo},

View file

@ -7,7 +7,7 @@ pub mod server;
extern crate conduwuit_core as conduwuit; extern crate conduwuit_core as conduwuit;
extern crate conduwuit_service as service; extern crate conduwuit_service as service;
pub(crate) use conduwuit::{debug_info, pdu::PduEvent, utils, Error, Result}; pub(crate) use conduwuit::{Error, Result, debug_info, pdu::PduEvent, utils};
pub(crate) use self::router::{Ruma, RumaResponse, State}; pub(crate) use self::router::{Ruma, RumaResponse, State};

View file

@ -8,12 +8,12 @@ pub mod state;
use std::str::FromStr; use std::str::FromStr;
use axum::{ use axum::{
Router,
response::{IntoResponse, Redirect}, response::{IntoResponse, Redirect},
routing::{any, get, post}, routing::{any, get, post},
Router,
}; };
use conduwuit::{err, Server}; use conduwuit::{Server, err};
use http::{uri, Uri}; use http::{Uri, uri};
use self::handler::RouterExt; use self::handler::RouterExt;
pub(super) use self::{args::Args as Ruma, response::RumaResponse, state::State}; pub(super) use self::{args::Args as Ruma, response::RumaResponse, state::State};

View file

@ -2,15 +2,15 @@ use std::{mem, ops::Deref};
use axum::{async_trait, body::Body, extract::FromRequest}; use axum::{async_trait, body::Body, extract::FromRequest};
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use conduwuit::{debug, debug_warn, err, trace, utils::string::EMPTY, Error, Result}; use conduwuit::{Error, Result, debug, debug_warn, err, trace, utils::string::EMPTY};
use ruma::{ use ruma::{
api::IncomingRequest, CanonicalJsonObject, CanonicalJsonValue, DeviceId, OwnedDeviceId, CanonicalJsonObject, CanonicalJsonValue, DeviceId, OwnedDeviceId, OwnedServerName,
OwnedServerName, OwnedUserId, ServerName, UserId, OwnedUserId, ServerName, UserId, api::IncomingRequest,
}; };
use service::Services; use service::Services;
use super::{auth, auth::Auth, request, request::Request}; use super::{auth, auth::Auth, request, request::Request};
use crate::{service::appservice::RegistrationInfo, State}; use crate::{State, service::appservice::RegistrationInfo};
/// Extractor for Ruma request structs /// Extractor for Ruma request structs
pub(crate) struct Args<T> { pub(crate) struct Args<T> {

View file

@ -1,12 +1,14 @@
use axum::RequestPartsExt; use axum::RequestPartsExt;
use axum_extra::{ use axum_extra::{
headers::{authorization::Bearer, Authorization},
typed_header::TypedHeaderRejectionReason,
TypedHeader, TypedHeader,
headers::{Authorization, authorization::Bearer},
typed_header::TypedHeaderRejectionReason,
}; };
use conduwuit::{debug_error, err, warn, Err, Error, Result}; use conduwuit::{Err, Error, Result, debug_error, err, warn};
use ruma::{ use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
api::{ api::{
AuthScheme, IncomingRequest, Metadata,
client::{ client::{
directory::get_public_rooms, directory::get_public_rooms,
error::ErrorKind, error::ErrorKind,
@ -16,14 +18,12 @@ use ruma::{
voip::get_turn_server_info, voip::get_turn_server_info,
}, },
federation::openid::get_openid_userinfo, federation::openid::get_openid_userinfo,
AuthScheme, IncomingRequest, Metadata,
}, },
server_util::authorization::XMatrix, server_util::authorization::XMatrix,
CanonicalJsonObject, CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
}; };
use service::{ use service::{
server_keys::{PubKeyMap, PubKeys},
Services, Services,
server_keys::{PubKeyMap, PubKeys},
}; };
use super::request::Request; use super::request::Request;
@ -56,12 +56,12 @@ pub(super) async fn auth(
}; };
let token = if let Some(token) = token { let token = if let Some(token) = token {
if let Some(reg_info) = services.appservice.find_from_token(token).await { match services.appservice.find_from_token(token).await {
Token::Appservice(Box::new(reg_info)) | Some(reg_info) => Token::Appservice(Box::new(reg_info)),
} else if let Ok((user_id, device_id)) = services.users.find_from_token(token).await { | _ => match services.users.find_from_token(token).await {
Token::User((user_id, device_id)) | Ok((user_id, device_id)) => Token::User((user_id, device_id)),
} else { | _ => Token::Invalid,
Token::Invalid },
} }
} else { } else {
Token::None Token::None

View file

@ -1,8 +1,8 @@
use axum::{ use axum::{
Router,
extract::FromRequestParts, extract::FromRequestParts,
response::IntoResponse, response::IntoResponse,
routing::{on, MethodFilter}, routing::{MethodFilter, on},
Router,
}; };
use conduwuit::Result; use conduwuit::Result;
use futures::{Future, TryFutureExt}; use futures::{Future, TryFutureExt};

View file

@ -1,8 +1,8 @@
use std::str; use std::str;
use axum::{extract::Path, RequestExt, RequestPartsExt}; use axum::{RequestExt, RequestPartsExt, extract::Path};
use bytes::Bytes; use bytes::Bytes;
use conduwuit::{err, Result}; use conduwuit::{Result, err};
use http::request::Parts; use http::request::Parts;
use serde::Deserialize; use serde::Deserialize;
use service::Services; use service::Services;

View file

@ -1,9 +1,9 @@
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use bytes::BytesMut; use bytes::BytesMut;
use conduwuit::{error, Error}; use conduwuit::{Error, error};
use http::StatusCode; use http::StatusCode;
use http_body_util::Full; use http_body_util::Full;
use ruma::api::{client::uiaa::UiaaResponse, OutgoingResponse}; use ruma::api::{OutgoingResponse, client::uiaa::UiaaResponse};
pub(crate) struct RumaResponse<T>(pub(crate) T) pub(crate) struct RumaResponse<T>(pub(crate) T)
where where

View file

@ -2,11 +2,11 @@ use std::cmp;
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
utils::{stream::TryTools, IterStream, ReadyExt},
PduCount, Result, PduCount, Result,
utils::{IterStream, ReadyExt, stream::TryTools},
}; };
use futures::{FutureExt, StreamExt, TryStreamExt}; use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::{api::federation::backfill::get_backfill, uint, MilliSecondsSinceUnixEpoch}; use ruma::{MilliSecondsSinceUnixEpoch, api::federation::backfill::get_backfill, uint};
use super::AccessCheck; use super::AccessCheck;
use crate::Ruma; use crate::Ruma;

View file

@ -1,6 +1,6 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Result}; use conduwuit::{Result, err};
use ruma::{api::federation::event::get_event, MilliSecondsSinceUnixEpoch, RoomId}; use ruma::{MilliSecondsSinceUnixEpoch, RoomId, api::federation::event::get_event};
use super::AccessCheck; use super::AccessCheck;
use crate::Ruma; use crate::Ruma;

View file

@ -1,11 +1,11 @@
use std::{borrow::Borrow, iter::once}; use std::{borrow::Borrow, iter::once};
use axum::extract::State; use axum::extract::State;
use conduwuit::{utils::stream::ReadyExt, Error, Result}; use conduwuit::{Error, Result, utils::stream::ReadyExt};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
api::{client::error::ErrorKind, federation::authorization::get_event_authorization},
RoomId, RoomId,
api::{client::error::ErrorKind, federation::authorization::get_event_authorization},
}; };
use super::AccessCheck; use super::AccessCheck;

View file

@ -1,8 +1,8 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{Error, Result}; use conduwuit::{Error, Result};
use ruma::{ use ruma::{
api::{client::error::ErrorKind, federation::event::get_missing_events},
CanonicalJsonValue, EventId, RoomId, CanonicalJsonValue, EventId, RoomId,
api::{client::error::ErrorKind, federation::event::get_missing_events},
}; };
use super::AccessCheck; use super::AccessCheck;

View file

@ -1,11 +1,11 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
utils::stream::{BroadbandExt, IterStream},
Err, Result, Err, Result,
utils::stream::{BroadbandExt, IterStream},
}; };
use futures::{FutureExt, StreamExt}; use futures::{FutureExt, StreamExt};
use ruma::api::federation::space::get_hierarchy; use ruma::api::federation::space::get_hierarchy;
use service::rooms::spaces::{get_parent_children_via, Identifier, SummaryAccessibility}; use service::rooms::spaces::{Identifier, SummaryAccessibility, get_parent_children_via};
use crate::Ruma; use crate::Ruma;

View file

@ -1,12 +1,12 @@
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use base64::{engine::general_purpose, Engine as _}; use base64::{Engine as _, engine::general_purpose};
use conduwuit::{err, utils, utils::hash::sha256, warn, Err, Error, PduEvent, Result}; use conduwuit::{Err, Error, PduEvent, Result, err, utils, utils::hash::sha256, warn};
use ruma::{ use ruma::{
CanonicalJsonValue, OwnedUserId, UserId,
api::{client::error::ErrorKind, federation::membership::create_invite}, api::{client::error::ErrorKind, federation::membership::create_invite},
events::room::member::{MembershipState, RoomMemberEventContent}, events::room::member::{MembershipState, RoomMemberEventContent},
serde::JsonObject, serde::JsonObject,
CanonicalJsonValue, OwnedUserId, UserId,
}; };
use service::pdu::gen_event_id; use service::pdu::gen_event_id;

View file

@ -3,15 +3,15 @@ use std::{
time::{Duration, SystemTime}, time::{Duration, SystemTime},
}; };
use axum::{extract::State, response::IntoResponse, Json}; use axum::{Json, extract::State, response::IntoResponse};
use conduwuit::{utils::timepoint_from_now, Result}; use conduwuit::{Result, utils::timepoint_from_now};
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch, Signatures,
api::{ api::{
federation::discovery::{get_server_keys, OldVerifyKey, ServerSigningKeys},
OutgoingResponse, OutgoingResponse,
federation::discovery::{OldVerifyKey, ServerSigningKeys, get_server_keys},
}, },
serde::Raw, serde::Raw,
MilliSecondsSinceUnixEpoch, Signatures,
}; };
/// # `GET /_matrix/key/v2/server` /// # `GET /_matrix/key/v2/server`

View file

@ -1,22 +1,22 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{debug_info, utils::IterStream, warn, Err}; use conduwuit::{Err, debug_info, utils::IterStream, warn};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
CanonicalJsonObject, OwnedUserId, RoomId, RoomVersionId, UserId,
api::{client::error::ErrorKind, federation::membership::prepare_join_event}, api::{client::error::ErrorKind, federation::membership::prepare_join_event},
events::{ events::{
StateEventType,
room::{ room::{
join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent}, join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
}, },
StateEventType,
}, },
CanonicalJsonObject, OwnedUserId, RoomId, RoomVersionId, UserId,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use crate::{ use crate::{
service::{pdu::PduBuilder, Services},
Error, Result, Ruma, Error, Result, Ruma,
service::{Services, pdu::PduBuilder},
}; };
/// # `GET /_matrix/federation/v1/make_join/{roomId}/{userId}` /// # `GET /_matrix/federation/v1/make_join/{roomId}/{userId}`

View file

@ -1,15 +1,15 @@
use RoomVersionId::*;
use axum::extract::State; use axum::extract::State;
use conduwuit::{debug_warn, Err}; use conduwuit::{Err, debug_warn};
use ruma::{ use ruma::{
RoomVersionId,
api::{client::error::ErrorKind, federation::knock::create_knock_event_template}, api::{client::error::ErrorKind, federation::knock::create_knock_event_template},
events::room::member::{MembershipState, RoomMemberEventContent}, events::room::member::{MembershipState, RoomMemberEventContent},
RoomVersionId,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use tracing::warn; use tracing::warn;
use RoomVersionId::*;
use crate::{service::pdu::PduBuilder, Error, Result, Ruma}; use crate::{Error, Result, Ruma, service::pdu::PduBuilder};
/// # `GET /_matrix/federation/v1/make_knock/{roomId}/{userId}` /// # `GET /_matrix/federation/v1/make_knock/{roomId}/{userId}`
/// ///

View file

@ -7,7 +7,7 @@ use ruma::{
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use super::make_join::maybe_strip_event_id; use super::make_join::maybe_strip_event_id;
use crate::{service::pdu::PduBuilder, Ruma}; use crate::{Ruma, service::pdu::PduBuilder};
/// # `GET /_matrix/federation/v1/make_leave/{roomId}/{eventId}` /// # `GET /_matrix/federation/v1/make_leave/{roomId}/{eventId}`
/// ///

View file

@ -1,12 +1,12 @@
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{utils::content_disposition::make_content_disposition, Err, Result}; use conduwuit::{Err, Result, utils::content_disposition::make_content_disposition};
use conduwuit_service::media::{Dim, FileMeta}; use conduwuit_service::media::{Dim, FileMeta};
use ruma::{ use ruma::{
api::federation::authenticated_media::{
get_content, get_content_thumbnail, Content, ContentMetadata, FileOrLocation,
},
Mxc, Mxc,
api::federation::authenticated_media::{
Content, ContentMetadata, FileOrLocation, get_content, get_content_thumbnail,
},
}; };
use crate::Ruma; use crate::Ruma;

View file

@ -1,16 +1,16 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Error, Result}; use conduwuit::{Error, Result, err};
use futures::StreamExt; use futures::StreamExt;
use get_profile_information::v1::ProfileField; use get_profile_information::v1::ProfileField;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use ruma::{ use ruma::{
OwnedServerName,
api::{ api::{
client::error::ErrorKind, client::error::ErrorKind,
federation::query::{get_profile_information, get_room_information}, federation::query::{get_profile_information, get_room_information},
}, },
OwnedServerName,
}; };
use crate::Ruma; use crate::Ruma;

View file

@ -3,20 +3,21 @@ use std::{collections::BTreeMap, net::IpAddr, time::Instant};
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
debug, Err, Error, Result, debug,
debug::INFO_SPAN_LEVEL, debug::INFO_SPAN_LEVEL,
debug_warn, err, error, debug_warn, err, error,
result::LogErr, result::LogErr,
trace, trace,
utils::{ utils::{
stream::{automatic_width, BroadbandExt, TryBroadbandExt},
IterStream, ReadyExt, IterStream, ReadyExt,
stream::{BroadbandExt, TryBroadbandExt, automatic_width},
}, },
warn, Err, Error, Result, warn,
}; };
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt}; use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
use itertools::Itertools; use itertools::Itertools;
use ruma::{ use ruma::{
CanonicalJsonObject, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, ServerName, UserId,
api::{ api::{
client::error::ErrorKind, client::error::ErrorKind,
federation::transactions::{ federation::transactions::{
@ -31,17 +32,16 @@ use ruma::{
events::receipt::{ReceiptEvent, ReceiptEventContent, ReceiptType}, events::receipt::{ReceiptEvent, ReceiptEventContent, ReceiptType},
serde::Raw, serde::Raw,
to_device::DeviceIdOrAllDevices, to_device::DeviceIdOrAllDevices,
CanonicalJsonObject, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, ServerName, UserId,
}; };
use service::{ use service::{
sending::{EDU_LIMIT, PDU_LIMIT},
Services, Services,
sending::{EDU_LIMIT, PDU_LIMIT},
}; };
use utils::millis_since_unix_epoch; use utils::millis_since_unix_epoch;
use crate::{ use crate::{
utils::{self},
Ruma, Ruma,
utils::{self},
}; };
type ResolvedMap = BTreeMap<OwnedEventId, Result>; type ResolvedMap = BTreeMap<OwnedEventId, Result>;

View file

@ -4,22 +4,22 @@ use std::borrow::Borrow;
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{
at, err, Err, Result, at, err,
pdu::gen_event_id_canonical_json, pdu::gen_event_id_canonical_json,
utils::stream::{IterStream, TryBroadbandExt}, utils::stream::{IterStream, TryBroadbandExt},
warn, Err, Result, warn,
}; };
use futures::{FutureExt, StreamExt, TryStreamExt}; use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::{ use ruma::{
api::federation::membership::create_join_event,
events::{
room::member::{MembershipState, RoomMemberEventContent},
StateEventType,
},
CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId,
ServerName, ServerName,
api::federation::membership::create_join_event,
events::{
StateEventType,
room::member::{MembershipState, RoomMemberEventContent},
},
}; };
use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
use service::Services; use service::Services;
use crate::Ruma; use crate::Ruma;

View file

@ -1,15 +1,15 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, pdu::gen_event_id_canonical_json, warn, Err, PduEvent, Result}; use conduwuit::{Err, PduEvent, Result, err, pdu::gen_event_id_canonical_json, warn};
use futures::FutureExt; use futures::FutureExt;
use ruma::{ use ruma::{
api::federation::knock::send_knock,
events::{
room::member::{MembershipState, RoomMemberEventContent},
StateEventType,
},
serde::JsonObject,
OwnedServerName, OwnedUserId, OwnedServerName, OwnedUserId,
RoomVersionId::*, RoomVersionId::*,
api::federation::knock::send_knock,
events::{
StateEventType,
room::member::{MembershipState, RoomMemberEventContent},
},
serde::JsonObject,
}; };
use crate::Ruma; use crate::Ruma;

View file

@ -1,21 +1,21 @@
#![allow(deprecated)] #![allow(deprecated)]
use axum::extract::State; use axum::extract::State;
use conduwuit::{err, Err, Result}; use conduwuit::{Err, Result, err};
use futures::FutureExt; use futures::FutureExt;
use ruma::{ use ruma::{
OwnedRoomId, OwnedUserId, RoomId, ServerName,
api::federation::membership::create_leave_event, api::federation::membership::create_leave_event,
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent},
StateEventType, StateEventType,
room::member::{MembershipState, RoomMemberEventContent},
}, },
OwnedRoomId, OwnedUserId, RoomId, ServerName,
}; };
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
use crate::{ use crate::{
service::{pdu::gen_event_id_canonical_json, Services},
Ruma, Ruma,
service::{Services, pdu::gen_event_id_canonical_json},
}; };
/// # `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}` /// # `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}`

View file

@ -1,9 +1,9 @@
use std::{borrow::Borrow, iter::once}; use std::{borrow::Borrow, iter::once};
use axum::extract::State; use axum::extract::State;
use conduwuit::{at, err, utils::IterStream, Result}; use conduwuit::{Result, at, err, utils::IterStream};
use futures::{FutureExt, StreamExt, TryStreamExt}; use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::{api::federation::event::get_room_state, OwnedEventId}; use ruma::{OwnedEventId, api::federation::event::get_room_state};
use super::AccessCheck; use super::AccessCheck;
use crate::Ruma; use crate::Ruma;

View file

@ -1,9 +1,9 @@
use std::{borrow::Borrow, iter::once}; use std::{borrow::Borrow, iter::once};
use axum::extract::State; use axum::extract::State;
use conduwuit::{at, err, Result}; use conduwuit::{Result, at, err};
use futures::{StreamExt, TryStreamExt}; use futures::{StreamExt, TryStreamExt};
use ruma::{api::federation::event::get_room_state_ids, OwnedEventId}; use ruma::{OwnedEventId, api::federation::event::get_room_state_ids};
use super::AccessCheck; use super::AccessCheck;
use crate::Ruma; use crate::Ruma;

View file

@ -10,8 +10,8 @@ use ruma::api::{
}; };
use crate::{ use crate::{
client::{claim_keys_helper, get_keys_helper},
Ruma, Ruma,
client::{claim_keys_helper, get_keys_helper},
}; };
/// # `GET /_matrix/federation/v1/user/devices/{userId}` /// # `GET /_matrix/federation/v1/user/devices/{userId}`

View file

@ -1,6 +1,6 @@
use conduwuit::{implement, is_false, Err, Result}; use conduwuit::{Err, Result, implement, is_false};
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::{future::OptionFuture, join, FutureExt, StreamExt}; use futures::{FutureExt, StreamExt, future::OptionFuture, join};
use ruma::{EventId, RoomId, ServerName}; use ruma::{EventId, RoomId, ServerName};
pub(super) struct AccessCheck<'a> { pub(super) struct AccessCheck<'a> {

View file

@ -2,7 +2,7 @@
use std::{ use std::{
cell::OnceCell, cell::OnceCell,
ffi::{c_char, c_void, CStr}, ffi::{CStr, c_char, c_void},
fmt::Debug, fmt::Debug,
sync::RwLock, sync::RwLock,
}; };
@ -14,9 +14,8 @@ use tikv_jemalloc_sys as ffi;
use tikv_jemallocator as jemalloc; use tikv_jemallocator as jemalloc;
use crate::{ use crate::{
err, is_equal_to, is_nonzero, Result, err, is_equal_to, is_nonzero,
utils::{math, math::Tried}, utils::{math, math::Tried},
Result,
}; };
#[cfg(feature = "jemalloc_conf")] #[cfg(feature = "jemalloc_conf")]
@ -128,7 +127,7 @@ unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) {
} }
macro_rules! mallctl { macro_rules! mallctl {
($name:expr) => {{ ($name:expr_2021) => {{
thread_local! { thread_local! {
static KEY: OnceCell<Key> = OnceCell::default(); static KEY: OnceCell<Key> = OnceCell::default();
}; };
@ -141,7 +140,7 @@ macro_rules! mallctl {
} }
pub mod this_thread { pub mod this_thread {
use super::{is_nonzero, key, math, Debug, Key, OnceCell, Result}; use super::{Debug, Key, OnceCell, Result, is_nonzero, key, math};
thread_local! { thread_local! {
static ALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() }; static ALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() };
@ -261,18 +260,18 @@ pub fn decay<I: Into<Option<usize>>>(arena: I) -> Result {
} }
pub fn set_muzzy_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> { pub fn set_muzzy_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> {
if let Some(arena) = arena.into() { match arena.into() {
set_by_arena(Some(arena), mallctl!("arena.4096.muzzy_decay_ms"), decay_ms) | Some(arena) =>
} else { set_by_arena(Some(arena), mallctl!("arena.4096.muzzy_decay_ms"), decay_ms),
set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms) | _ => set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms),
} }
} }
pub fn set_dirty_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> { pub fn set_dirty_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> {
if let Some(arena) = arena.into() { match arena.into() {
set_by_arena(Some(arena), mallctl!("arena.4096.dirty_decay_ms"), decay_ms) | Some(arena) =>
} else { set_by_arena(Some(arena), mallctl!("arena.4096.dirty_decay_ms"), decay_ms),
set(&mallctl!("arenas.dirty_decay_ms"), decay_ms) | _ => set(&mallctl!("arenas.dirty_decay_ms"), decay_ms),
} }
} }

View file

@ -4,7 +4,7 @@ use either::Either;
use figment::Figment; use figment::Figment;
use super::DEPRECATED_KEYS; use super::DEPRECATED_KEYS;
use crate::{debug, debug_info, debug_warn, error, warn, Config, Err, Result, Server}; use crate::{Config, Err, Result, Server, debug, debug_info, debug_warn, error, warn};
/// Performs check() with additional checks specific to reloading old config /// Performs check() with additional checks specific to reloading old config
/// with new config. /// with new config.

View file

@ -4,13 +4,13 @@ use std::{
ptr, ptr,
ptr::null_mut, ptr::null_mut,
sync::{ sync::{
atomic::{AtomicPtr, Ordering},
Arc, Arc,
atomic::{AtomicPtr, Ordering},
}, },
}; };
use super::Config; use super::Config;
use crate::{implement, Result}; use crate::{Result, implement};
/// The configuration manager is an indirection to reload the configuration for /// The configuration manager is an indirection to reload the configuration for
/// the server while it is running. In order to not burden or clutter the many /// the server while it is running. In order to not burden or clutter the many

View file

@ -14,18 +14,18 @@ use either::{
Either::{Left, Right}, Either::{Left, Right},
}; };
use figment::providers::{Env, Format, Toml}; use figment::providers::{Env, Format, Toml};
pub use figment::{value::Value as FigmentValue, Figment}; pub use figment::{Figment, value::Value as FigmentValue};
use regex::RegexSet; use regex::RegexSet;
use ruma::{ use ruma::{
api::client::discovery::discover_support::ContactRole, OwnedRoomOrAliasId, OwnedServerName, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
OwnedUserId, RoomVersionId, api::client::discovery::discover_support::ContactRole,
}; };
use serde::{de::IgnoredAny, Deserialize}; use serde::{Deserialize, de::IgnoredAny};
use url::Url; use url::Url;
use self::proxy::ProxyConfig; use self::proxy::ProxyConfig;
pub use self::{check::check, manager::Manager}; pub use self::{check::check, manager::Manager};
use crate::{err, error::Error, utils::sys, Result}; use crate::{Result, err, error::Error, utils::sys};
/// All the config options for conduwuit. /// All the config options for conduwuit.
#[allow(clippy::struct_excessive_bools)] #[allow(clippy::struct_excessive_bools)]

View file

@ -13,7 +13,7 @@ pub use crate::{result::DebugInspect, utils::debug::*};
/// In release-mode it becomes DEBUG level, and possibly subject to elision. /// In release-mode it becomes DEBUG level, and possibly subject to elision.
#[macro_export] #[macro_export]
macro_rules! debug_event { macro_rules! debug_event {
( $level:expr, $($x:tt)+ ) => { ( $level:expr_2021, $($x:tt)+ ) => {
if $crate::debug::logging() { if $crate::debug::logging() {
::tracing::event!( $level, _debug = true, $($x)+ ) ::tracing::event!( $level, _debug = true, $($x)+ )
} else { } else {

View file

@ -165,10 +165,10 @@ macro_rules! err_lev {
use std::{fmt, fmt::Write}; use std::{fmt, fmt::Write};
use tracing::{ use tracing::{
level_enabled, Callsite, Event, __macro_support, __tracing_log, __macro_support, __tracing_log, Callsite, Event, Level,
callsite::DefaultCallsite, callsite::DefaultCallsite,
field::{Field, ValueSet, Visit}, field::{Field, ValueSet, Visit},
Level, level_enabled,
}; };
struct Visitor<'a>(&'a mut String); struct Visitor<'a>(&'a mut String);

View file

@ -152,8 +152,8 @@ impl Error {
/// Generate the error message string. /// Generate the error message string.
pub fn message(&self) -> String { pub fn message(&self) -> String {
match self { match self {
| Self::Federation(ref origin, ref error) => format!("Answer from {origin}: {error}"), | Self::Federation(origin, error) => format!("Answer from {origin}: {error}"),
| Self::Ruma(ref error) => response::ruma_error_message(error), | Self::Ruma(error) => response::ruma_error_message(error),
| _ => format!("{self}"), | _ => format!("{self}"),
} }
} }

View file

@ -1,6 +1,6 @@
use std::{ use std::{
any::Any, any::Any,
panic::{panic_any, RefUnwindSafe, UnwindSafe}, panic::{RefUnwindSafe, UnwindSafe, panic_any},
}; };
use super::Error; use super::Error;

Some files were not shown because too many files have changed in this diff Show more