Skip to main content

tuwunel_api/client/backup/
keys_room.rs

1use axum::extract::State;
2use ruma::api::client::backup::{
3	add_backup_keys_for_room::{self, v3::Response as AddResponse},
4	delete_backup_keys_for_room::{self, v3::Response as DeleteResponse},
5	get_backup_keys_for_room::{self, v3::Response as GetResponse},
6};
7use tuwunel_core::{Result, utils::stream::IterStream};
8
9use super::format_count_etag;
10use crate::Ruma;
11
12/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}`
13///
14/// Add the received backup keys to the database.
15///
16/// - Only manipulating the most recently created version of the backup is
17///   allowed
18/// - Adds the keys to the backup
19/// - Returns the new number of keys in this backup and the etag
20pub(crate) async fn add_backup_keys_for_room_route(
21	State(services): State<crate::State>,
22	body: Ruma<add_backup_keys_for_room::v3::Request>,
23) -> Result<add_backup_keys_for_room::v3::Response> {
24	let keys = body
25		.sessions
26		.iter()
27		.map(|(session_id, key_data)| (body.room_id.as_ref(), session_id.as_str(), key_data))
28		.stream();
29
30	let metadata = services
31		.key_backups
32		.add_keys(body.sender_user(), &body.version, keys)
33		.await?;
34
35	let (count, etag) = format_count_etag(metadata)?;
36
37	Ok(AddResponse { count, etag })
38}
39
40/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}`
41///
42/// Retrieves all keys from the backup for a given room.
43pub(crate) async fn get_backup_keys_for_room_route(
44	State(services): State<crate::State>,
45	body: Ruma<get_backup_keys_for_room::v3::Request>,
46) -> Result<get_backup_keys_for_room::v3::Response> {
47	let sessions = services
48		.key_backups
49		.get_room(body.sender_user(), &body.version, &body.room_id)
50		.await;
51
52	Ok(GetResponse { sessions })
53}
54
55/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`
56///
57/// Delete the keys from the backup for a given room.
58pub(crate) async fn delete_backup_keys_for_room_route(
59	State(services): State<crate::State>,
60	body: Ruma<delete_backup_keys_for_room::v3::Request>,
61) -> Result<delete_backup_keys_for_room::v3::Response> {
62	let metadata = services
63		.key_backups
64		.delete_room_keys(body.sender_user(), &body.version, &body.room_id)
65		.await?;
66
67	let (count, etag) = format_count_etag(metadata)?;
68
69	Ok(DeleteResponse { count, etag })
70}