summaryrefslogtreecommitdiff
path: root/src/api/client_server/state.rs
blob: 8e4ceaf904e42fd18dccdbe618f4e1a05f02b6a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use std::sync::Arc;

use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma, RumaResponse};
use ruma::{
    api::client::{
        error::ErrorKind,
        state::{get_state_events, get_state_events_for_key, send_state_event},
    },
    events::{
        room::canonical_alias::RoomCanonicalAliasEventContent, AnyStateEventContent, StateEventType,
    },
    serde::Raw,
    EventId, RoomId, UserId,
};

/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}`
///
/// Sends a state event into the room.
///
/// - 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
/// - If event is new canonical_alias: Rejects if alias is incorrect
pub async fn send_state_event_for_key_route(
    body: Ruma<send_state_event::v3::Request>,
) -> Result<send_state_event::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    let event_id = send_state_event_for_key_helper(
        sender_user,
        &body.room_id,
        &body.event_type,
        &body.body.body, // Yes, I hate it too
        body.state_key.to_owned(),
    )
    .await?;

    let event_id = (*event_id).to_owned();
    Ok(send_state_event::v3::Response { event_id })
}

/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}`
///
/// Sends a state event into the room.
///
/// - 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
/// - If event is new canonical_alias: Rejects if alias is incorrect
pub async fn send_state_event_for_empty_key_route(
    body: Ruma<send_state_event::v3::Request>,
) -> Result<RumaResponse<send_state_event::v3::Response>> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    // Forbid m.room.encryption if encryption is disabled
    if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() {
        return Err(Error::BadRequest(
            ErrorKind::Forbidden,
            "Encryption has been disabled",
        ));
    }

    let event_id = send_state_event_for_key_helper(
        sender_user,
        &body.room_id,
        &body.event_type.to_string().into(),
        &body.body.body,
        body.state_key.to_owned(),
    )
    .await?;

    let event_id = (*event_id).to_owned();
    Ok(send_state_event::v3::Response { event_id }.into())
}

/// # `GET /_matrix/client/r0/rooms/{roomid}/state`
///
/// Get all state events for a room.
///
/// - If not joined: Only works if current room history visibility is world readable
pub async fn get_state_events_route(
    body: Ruma<get_state_events::v3::Request>,
) -> Result<get_state_events::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    if !services()
        .rooms
        .state_accessor
        .user_can_see_state_events(&sender_user, &body.room_id)?
    {
        return Err(Error::BadRequest(
            ErrorKind::Forbidden,
            "You don't have permission to view the room state.",
        ));
    }

    Ok(get_state_events::v3::Response {
        room_state: services()
            .rooms
            .state_accessor
            .room_state_full(&body.room_id)
            .await?
            .values()
            .map(|pdu| pdu.to_state_event())
            .collect(),
    })
}

/// # `GET /_matrix/client/r0/rooms/{roomid}/state/{eventType}/{stateKey}`
///
/// Get single state event of a room.
///
/// - If not joined: Only works if current room history visibility is world readable
pub async fn get_state_events_for_key_route(
    body: Ruma<get_state_events_for_key::v3::Request>,
) -> Result<get_state_events_for_key::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    if !services()
        .rooms
        .state_accessor
        .user_can_see_state_events(&sender_user, &body.room_id)?
    {
        return Err(Error::BadRequest(
            ErrorKind::Forbidden,
            "You don't have permission to view the room state.",
        ));
    }

    let event = services()
        .rooms
        .state_accessor
        .room_state_get(&body.room_id, &body.event_type, &body.state_key)?
        .ok_or(Error::BadRequest(
            ErrorKind::NotFound,
            "State event not found.",
        ))?;

    Ok(get_state_events_for_key::v3::Response {
        content: serde_json::from_str(event.content.get())
            .map_err(|_| Error::bad_database("Invalid event content in database"))?,
    })
}

/// # `GET /_matrix/client/r0/rooms/{roomid}/state/{eventType}`
///
/// Get single state event of a room.
///
/// - If not joined: Only works if current room history visibility is world readable
pub async fn get_state_events_for_empty_key_route(
    body: Ruma<get_state_events_for_key::v3::Request>,
) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    if !services()
        .rooms
        .state_accessor
        .user_can_see_state_events(&sender_user, &body.room_id)?
    {
        return Err(Error::BadRequest(
            ErrorKind::Forbidden,
            "You don't have permission to view the room state.",
        ));
    }

    let event = services()
        .rooms
        .state_accessor
        .room_state_get(&body.room_id, &body.event_type, "")?
        .ok_or(Error::BadRequest(
            ErrorKind::NotFound,
            "State event not found.",
        ))?;

    Ok(get_state_events_for_key::v3::Response {
        content: serde_json::from_str(event.content.get())
            .map_err(|_| Error::bad_database("Invalid event content in database"))?,
    }
    .into())
}

async fn send_state_event_for_key_helper(
    sender: &UserId,
    room_id: &RoomId,
    event_type: &StateEventType,
    json: &Raw<AnyStateEventContent>,
    state_key: String,
) -> Result<Arc<EventId>> {
    let sender_user = sender;

    // TODO: Review this check, error if event is unparsable, use event type, allow alias if it
    // previously existed
    if let Ok(canonical_alias) =
        serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get())
    {
        let mut aliases = canonical_alias.alt_aliases.clone();

        if let Some(alias) = canonical_alias.alias {
            aliases.push(alias);
        }

        for alias in aliases {
            if alias.server_name() != services().globals.server_name()
                || services()
                    .rooms
                    .alias
                    .resolve_local_alias(&alias)?
                    .filter(|room| room == room_id) // Make sure it's the right room
                    .is_none()
            {
                return Err(Error::BadRequest(
                    ErrorKind::Forbidden,
                    "You are only allowed to send canonical_alias \
                    events when it's aliases already exists",
                ));
            }
        }
    }

    let mutex_state = Arc::clone(
        services()
            .globals
            .roomid_mutex_state
            .write()
            .unwrap()
            .entry(room_id.to_owned())
            .or_default(),
    );
    let state_lock = mutex_state.lock().await;

    let event_id = services().rooms.timeline.build_and_append_pdu(
        PduBuilder {
            event_type: event_type.to_string().into(),
            content: serde_json::from_str(json.json().get()).expect("content is valid json"),
            unsigned: None,
            state_key: Some(state_key),
            redacts: None,
        },
        sender_user,
        room_id,
        &state_lock,
    )?;

    Ok(event_id)
}