1
0
Fork 0
mirror of https://gitlab.com/famedly/conduit.git synced 2025-06-27 16:35:59 +00:00
conduit/src/api/client_server/message.rs

269 lines
8.9 KiB
Rust
Raw Normal View History

2023-02-20 22:59:45 +01:00
use crate::{
service::{pdu::PduBuilder, rooms::timeline::PduCount},
services, utils, Error, Result, Ruma,
};
use ruma::{
api::client::{
error::ErrorKind,
2022-02-18 15:33:14 +01:00
message::{get_message_events, send_message_event},
},
2023-02-26 16:29:06 +01:00
events::{StateEventType, TimelineEventType},
};
2022-01-04 14:30:13 +01:00
use std::{
collections::{BTreeMap, HashSet},
sync::Arc,
};
2020-07-30 18:14:47 +02:00
2021-08-31 19:14:37 +02:00
/// # `PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}`
///
/// Send a message event into the room.
///
/// - Is a NOOP if the txn id was already used before and returns the same event id again
/// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is allowed
2020-09-14 20:23:19 +02:00
pub async fn send_message_event_route(
2022-12-14 13:09:10 +01:00
body: Ruma<send_message_event::v3::Request>,
2022-02-18 15:33:14 +01:00
) -> Result<send_message_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref();
2020-08-25 13:24:38 +02:00
2021-08-03 11:10:58 +02:00
let mutex_state = Arc::clone(
2022-10-05 20:34:31 +02:00
services()
.globals
2021-08-03 11:10:58 +02:00
.roomid_mutex_state
2021-07-13 15:44:25 +02:00
.write()
.await
2021-07-13 15:44:25 +02:00
.entry(body.room_id.clone())
.or_default(),
);
2021-08-03 11:10:58 +02:00
let state_lock = mutex_state.lock().await;
2021-07-13 15:44:25 +02:00
// Forbid m.room.encrypted if encryption is disabled
2023-02-26 16:29:06 +01:00
if TimelineEventType::RoomEncrypted == body.event_type.to_string().into()
&& !services().globals.allow_encryption()
2022-04-06 21:31:29 +02:00
{
return Err(Error::BadRequest(
2024-04-07 20:46:18 +01:00
ErrorKind::forbidden(),
"Encryption has been disabled",
));
}
2020-08-25 13:24:38 +02:00
// Check if this is a new transaction id
if let Some(response) =
2022-10-05 20:34:31 +02:00
services()
.transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)?
2020-08-25 13:24:38 +02:00
{
// The client might have sent a txnid of the /sendToDevice endpoint
// This txnid has no response associated with it
if response.is_empty() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to use txn id already used for an incompatible endpoint.",
));
}
2021-11-27 00:30:28 +01:00
let event_id = utils::string_from_bytes(&response)
.map_err(|_| Error::bad_database("Invalid txnid bytes in database."))?
.try_into()
.map_err(|_| Error::bad_database("Invalid event id in txnid data."))?;
2022-02-18 15:33:14 +01:00
return Ok(send_message_event::v3::Response { event_id });
2020-08-25 13:24:38 +02:00
}
2020-07-30 18:14:47 +02:00
let mut unsigned = BTreeMap::new();
2022-01-17 14:35:38 +01:00
unsigned.insert("transaction_id".to_owned(), body.txn_id.to_string().into());
2020-07-30 18:14:47 +02:00
let event_id = services()
.rooms
.timeline
.build_and_append_pdu(
PduBuilder {
event_type: body.event_type.to_string().into(),
content: serde_json::from_str(body.body.body.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid JSON body."))?,
unsigned: Some(unsigned),
state_key: None,
redacts: None,
},
sender_user,
&body.room_id,
&state_lock,
)
.await?;
2020-07-30 18:14:47 +02:00
services().transaction_ids.add_txnid(
sender_user,
sender_device,
&body.txn_id,
event_id.as_bytes(),
)?;
2021-08-03 11:10:58 +02:00
drop(state_lock);
2021-07-13 15:44:25 +02:00
2022-02-18 15:33:14 +01:00
Ok(send_message_event::v3::Response::new(
(*event_id).to_owned(),
))
2020-07-30 18:14:47 +02:00
}
2021-08-31 19:14:37 +02:00
/// # `GET /_matrix/client/r0/rooms/{roomId}/messages`
///
/// Allows paginating through room history.
///
/// - Only works if the user is joined (TODO: always allow, but only show events where the user was
/// joined, depending on history_visibility)
pub async fn get_message_events_route(
2022-12-14 13:09:10 +01:00
body: Ruma<get_message_events::v3::Request>,
2022-02-18 15:33:14 +01:00
) -> Result<get_message_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
2022-01-04 14:30:13 +01:00
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
2020-07-30 18:14:47 +02:00
2022-04-06 21:31:29 +02:00
let from = match body.from.clone() {
2023-02-20 22:59:45 +01:00
Some(from) => PduCount::try_from_string(&from)?,
2022-04-06 21:31:29 +02:00
None => match body.dir {
2023-02-26 16:29:06 +01:00
ruma::api::Direction::Forward => PduCount::min(),
ruma::api::Direction::Backward => PduCount::max(),
2022-04-06 21:31:29 +02:00
},
};
2020-07-30 18:14:47 +02:00
2023-02-20 22:59:45 +01:00
let to = body
.to
.as_ref()
2023-12-23 19:48:14 -08:00
.and_then(|t| PduCount::try_from_string(t).ok());
2020-07-30 18:14:47 +02:00
services()
.rooms
.lazy_loading
.lazy_load_confirm_delivery(sender_user, sender_device, &body.room_id, from)
.await?;
2022-01-05 18:15:00 +01:00
2023-07-02 16:06:54 +02:00
let limit = u64::from(body.limit).min(100) as usize;
2020-07-30 18:14:47 +02:00
2022-01-04 14:30:13 +01:00
let next_token;
2022-02-18 15:33:14 +01:00
let mut resp = get_message_events::v3::Response::new();
2022-01-04 14:30:13 +01:00
let mut lazy_loaded = HashSet::new();
2020-07-30 18:14:47 +02:00
match body.dir {
2023-02-26 16:29:06 +01:00
ruma::api::Direction::Forward => {
let events_after: Vec<_> = services()
2020-07-30 18:14:47 +02:00
.rooms
2022-10-05 09:34:25 +02:00
.timeline
.pdus_after(sender_user, &body.room_id, from)?
2020-07-30 18:14:47 +02:00
.take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events
2023-02-22 15:49:55 +01:00
.filter(|(_, pdu)| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false)
})
2023-02-20 22:59:45 +01:00
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.collect();
2020-07-30 18:14:47 +02:00
2022-01-04 14:30:13 +01:00
for (_, event) in &events_after {
/* TODO: Remove this when these are resolved:
* https://github.com/vector-im/element-android/issues/3417
* https://github.com/vector-im/element-web/issues/21034
2022-10-05 09:34:25 +02:00
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
2022-01-20 00:10:39 +01:00
sender_user,
sender_device,
2022-01-04 14:30:13 +01:00
&body.room_id,
&event.sender,
)? {
lazy_loaded.insert(event.sender.clone());
}
*/
lazy_loaded.insert(event.sender.clone());
2022-01-04 14:30:13 +01:00
}
next_token = events_after.last().map(|(count, _)| count).copied();
2020-07-30 18:14:47 +02:00
let events_after: Vec<_> = events_after
2020-07-30 18:14:47 +02:00
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
2020-07-30 18:14:47 +02:00
2023-02-20 22:59:45 +01:00
resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify());
2022-01-04 14:30:13 +01:00
resp.chunk = events_after;
2020-07-30 18:14:47 +02:00
}
2023-02-26 16:29:06 +01:00
ruma::api::Direction::Backward => {
2023-02-20 22:59:45 +01:00
services()
.rooms
.timeline
.backfill_if_required(&body.room_id, from)
.await?;
let events_before: Vec<_> = services()
2020-07-30 18:14:47 +02:00
.rooms
2022-10-05 09:34:25 +02:00
.timeline
.pdus_until(sender_user, &body.room_id, from)?
2020-07-30 18:14:47 +02:00
.take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events
2023-02-22 15:49:55 +01:00
.filter(|(_, pdu)| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false)
})
2023-02-20 22:59:45 +01:00
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.collect();
2020-07-30 18:14:47 +02:00
2022-01-04 14:30:13 +01:00
for (_, event) in &events_before {
/* TODO: Remove this when these are resolved:
* https://github.com/vector-im/element-android/issues/3417
* https://github.com/vector-im/element-web/issues/21034
2022-10-05 09:34:25 +02:00
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
2022-01-20 00:10:39 +01:00
sender_user,
sender_device,
2022-01-04 14:30:13 +01:00
&body.room_id,
&event.sender,
)? {
lazy_loaded.insert(event.sender.clone());
}
*/
lazy_loaded.insert(event.sender.clone());
2022-01-04 14:30:13 +01:00
}
next_token = events_before.last().map(|(count, _)| count).copied();
2020-07-30 18:14:47 +02:00
let events_before: Vec<_> = events_before
2020-07-30 18:14:47 +02:00
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
2020-07-30 18:14:47 +02:00
2023-02-20 22:59:45 +01:00
resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify());
2022-01-04 14:30:13 +01:00
resp.chunk = events_before;
}
}
2022-01-04 14:30:13 +01:00
resp.state = Vec::new();
for ll_id in &lazy_loaded {
2022-10-05 20:34:31 +02:00
if let Some(member_event) = services().rooms.state_accessor.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
ll_id.as_str(),
)? {
2022-01-04 14:30:13 +01:00
resp.state.push(member_event.to_state_event());
2020-07-30 18:14:47 +02:00
}
}
2022-01-04 14:30:13 +01:00
// TODO: enable again when we are sure clients can handle it
/*
2022-01-04 14:30:13 +01:00
if let Some(next_token) = next_token {
2022-10-05 09:34:25 +02:00
services().rooms.lazy_loading.lazy_load_mark_sent(
2022-01-20 00:10:39 +01:00
sender_user,
sender_device,
2022-01-04 14:30:13 +01:00
&body.room_id,
lazy_loaded,
2022-01-04 14:30:13 +01:00
next_token,
);
}
*/
2022-01-04 14:30:13 +01:00
Ok(resp)
2020-07-30 18:14:47 +02:00
}