2020-07-30 16:14:47 +00:00
|
|
|
use super::State;
|
|
|
|
use crate::{ConduitResult, Database, Error, Ruma};
|
|
|
|
use ruma::api::client::{
|
|
|
|
error::ErrorKind,
|
|
|
|
r0::to_device::{self, send_event_to_device},
|
|
|
|
};
|
|
|
|
|
|
|
|
#[cfg(feature = "conduit_bin")]
|
|
|
|
use rocket::put;
|
|
|
|
|
|
|
|
#[cfg_attr(
|
|
|
|
feature = "conduit_bin",
|
|
|
|
put("/_matrix/client/r0/sendToDevice/<_>/<_>", data = "<body>")
|
|
|
|
)]
|
2020-10-21 19:28:02 +00:00
|
|
|
pub async fn send_event_to_device_route(
|
2020-07-30 16:14:47 +00:00
|
|
|
db: State<'_, Database>,
|
2020-09-08 15:32:03 +00:00
|
|
|
body: Ruma<send_event_to_device::Request<'_>>,
|
2020-07-30 16:14:47 +00:00
|
|
|
) -> ConduitResult<send_event_to_device::Response> {
|
2020-10-18 18:33:12 +00:00
|
|
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
2020-12-08 09:33:44 +00:00
|
|
|
let sender_device = body.sender_device.as_deref();
|
2020-08-25 11:24:38 +00:00
|
|
|
|
|
|
|
// Check if this is a new transaction id
|
|
|
|
if db
|
|
|
|
.transaction_ids
|
2020-10-18 18:33:12 +00:00
|
|
|
.existing_txnid(sender_user, sender_device, &body.txn_id)?
|
2020-08-25 11:24:38 +00:00
|
|
|
.is_some()
|
|
|
|
{
|
|
|
|
return Ok(send_event_to_device::Response.into());
|
|
|
|
}
|
2020-07-30 16:14:47 +00:00
|
|
|
|
|
|
|
for (target_user_id, map) in &body.messages {
|
|
|
|
for (target_device_id_maybe, event) in map {
|
|
|
|
match target_device_id_maybe {
|
|
|
|
to_device::DeviceIdOrAllDevices::DeviceId(target_device_id) => {
|
|
|
|
db.users.add_to_device_event(
|
2020-10-18 18:33:12 +00:00
|
|
|
sender_user,
|
2020-07-30 16:14:47 +00:00
|
|
|
&target_user_id,
|
|
|
|
&target_device_id,
|
|
|
|
&body.event_type,
|
|
|
|
serde_json::from_str(event.get()).map_err(|_| {
|
|
|
|
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
|
|
|
|
})?,
|
|
|
|
&db.globals,
|
|
|
|
)?
|
|
|
|
}
|
|
|
|
|
|
|
|
to_device::DeviceIdOrAllDevices::AllDevices => {
|
|
|
|
for target_device_id in db.users.all_device_ids(&target_user_id) {
|
|
|
|
db.users.add_to_device_event(
|
2020-10-18 18:33:12 +00:00
|
|
|
sender_user,
|
2020-07-30 16:14:47 +00:00
|
|
|
&target_user_id,
|
|
|
|
&target_device_id?,
|
|
|
|
&body.event_type,
|
|
|
|
serde_json::from_str(event.get()).map_err(|_| {
|
|
|
|
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
|
|
|
|
})?,
|
|
|
|
&db.globals,
|
|
|
|
)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-25 11:24:38 +00:00
|
|
|
// Save transaction id with empty data
|
|
|
|
db.transaction_ids
|
2020-10-18 18:33:12 +00:00
|
|
|
.add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
|
2020-08-25 11:24:38 +00:00
|
|
|
|
2020-10-21 19:28:02 +00:00
|
|
|
db.flush().await?;
|
|
|
|
|
2020-07-30 16:14:47 +00:00
|
|
|
Ok(send_event_to_device::Response.into())
|
|
|
|
}
|