summaryrefslogtreecommitdiff
path: root/src/api/client_server/directory.rs
blob: 50ae9f15738b22ba050bd20f1db91c8651ffc5ed (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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use crate::{services, Error, Result, Ruma};
use ruma::{
    api::{
        client::{
            directory::{
                get_public_rooms, get_public_rooms_filtered, get_room_visibility,
                set_room_visibility,
            },
            error::ErrorKind,
            room,
        },
        federation,
    },
    directory::{Filter, PublicRoomJoinRule, PublicRoomsChunk, RoomNetwork},
    events::{
        room::{
            avatar::RoomAvatarEventContent,
            canonical_alias::RoomCanonicalAliasEventContent,
            create::RoomCreateEventContent,
            guest_access::{GuestAccess, RoomGuestAccessEventContent},
            history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
            join_rules::{JoinRule, RoomJoinRulesEventContent},
            topic::RoomTopicEventContent,
        },
        StateEventType,
    },
    ServerName, UInt,
};
use tracing::{error, info, warn};

/// # `POST /_matrix/client/r0/publicRooms`
///
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
pub async fn get_public_rooms_filtered_route(
    body: Ruma<get_public_rooms_filtered::v3::Request>,
) -> Result<get_public_rooms_filtered::v3::Response> {
    get_public_rooms_filtered_helper(
        body.server.as_deref(),
        body.limit,
        body.since.as_deref(),
        &body.filter,
        &body.room_network,
    )
    .await
}

/// # `GET /_matrix/client/r0/publicRooms`
///
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
pub async fn get_public_rooms_route(
    body: Ruma<get_public_rooms::v3::Request>,
) -> Result<get_public_rooms::v3::Response> {
    let response = get_public_rooms_filtered_helper(
        body.server.as_deref(),
        body.limit,
        body.since.as_deref(),
        &Filter::default(),
        &RoomNetwork::Matrix,
    )
    .await?;

    Ok(get_public_rooms::v3::Response {
        chunk: response.chunk,
        prev_batch: response.prev_batch,
        next_batch: response.next_batch,
        total_room_count_estimate: response.total_room_count_estimate,
    })
}

/// # `PUT /_matrix/client/r0/directory/list/room/{roomId}`
///
/// Sets the visibility of a given room in the room directory.
///
/// - TODO: Access control checks
pub async fn set_room_visibility_route(
    body: Ruma<set_room_visibility::v3::Request>,
) -> Result<set_room_visibility::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    if !services().rooms.metadata.exists(&body.room_id)? {
        // Return 404 if the room doesn't exist
        return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found"));
    }

    match &body.visibility {
        room::Visibility::Public => {
            services().rooms.directory.set_public(&body.room_id)?;
            info!("{} made {} public", sender_user, body.room_id);
        }
        room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?,
        _ => {
            return Err(Error::BadRequest(
                ErrorKind::InvalidParam,
                "Room visibility type is not supported.",
            ));
        }
    }

    Ok(set_room_visibility::v3::Response {})
}

/// # `GET /_matrix/client/r0/directory/list/room/{roomId}`
///
/// Gets the visibility of a given room in the room directory.
pub async fn get_room_visibility_route(
    body: Ruma<get_room_visibility::v3::Request>,
) -> Result<get_room_visibility::v3::Response> {
    if !services().rooms.metadata.exists(&body.room_id)? {
        // Return 404 if the room doesn't exist
        return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found"));
    }

    Ok(get_room_visibility::v3::Response {
        visibility: if services().rooms.directory.is_public_room(&body.room_id)? {
            room::Visibility::Public
        } else {
            room::Visibility::Private
        },
    })
}

pub(crate) async fn get_public_rooms_filtered_helper(
    server: Option<&ServerName>,
    limit: Option<UInt>,
    since: Option<&str>,
    filter: &Filter,
    _network: &RoomNetwork,
) -> Result<get_public_rooms_filtered::v3::Response> {
    if let Some(other_server) =
        server.filter(|server| *server != services().globals.server_name().as_str())
    {
        let response = services()
            .sending
            .send_federation_request(
                other_server,
                federation::directory::get_public_rooms_filtered::v1::Request {
                    limit,
                    since: since.map(ToOwned::to_owned),
                    filter: Filter {
                        generic_search_term: filter.generic_search_term.clone(),
                        room_types: filter.room_types.clone(),
                    },
                    room_network: RoomNetwork::Matrix,
                },
            )
            .await?;

        return Ok(get_public_rooms_filtered::v3::Response {
            chunk: response.chunk,
            prev_batch: response.prev_batch,
            next_batch: response.next_batch,
            total_room_count_estimate: response.total_room_count_estimate,
        });
    }

    let limit = limit.map_or(10, u64::from);
    let mut num_since = 0_u64;

    if let Some(s) = &since {
        let mut characters = s.chars();
        let backwards = match characters.next() {
            Some('n') => false,
            Some('p') => true,
            _ => {
                return Err(Error::BadRequest(
                    ErrorKind::InvalidParam,
                    "Invalid `since` token",
                ))
            }
        };

        num_since = characters
            .collect::<String>()
            .parse()
            .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `since` token."))?;

        if backwards {
            num_since = num_since.saturating_sub(limit);
        }
    }

    let mut all_rooms: Vec<_> = services()
        .rooms
        .directory
        .public_rooms()
        .map(|room_id| {
            let room_id = room_id?;

            let chunk = PublicRoomsChunk {
                canonical_alias: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomCanonicalAlias, "")?
                    .map_or(Ok(None), |s| {
                        serde_json::from_str(s.content.get())
                            .map(|c: RoomCanonicalAliasEventContent| c.alias)
                            .map_err(|_| {
                                Error::bad_database("Invalid canonical alias event in database.")
                            })
                    })?,
                name: services().rooms.state_accessor.get_name(&room_id)?,
                num_joined_members: services()
                    .rooms
                    .state_cache
                    .room_joined_count(&room_id)?
                    .unwrap_or_else(|| {
                        warn!("Room {} has no member count", room_id);
                        0
                    })
                    .try_into()
                    .expect("user count should not be that big"),
                topic: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomTopic, "")?
                    .map_or(Ok(None), |s| {
                        serde_json::from_str(s.content.get())
                            .map(|c: RoomTopicEventContent| Some(c.topic))
                            .map_err(|_| {
                                error!("Invalid room topic event in database for room {}", room_id);
                                Error::bad_database("Invalid room topic event in database.")
                            })
                    })?,
                world_readable: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")?
                    .map_or(Ok(false), |s| {
                        serde_json::from_str(s.content.get())
                            .map(|c: RoomHistoryVisibilityEventContent| {
                                c.history_visibility == HistoryVisibility::WorldReadable
                            })
                            .map_err(|_| {
                                Error::bad_database(
                                    "Invalid room history visibility event in database.",
                                )
                            })
                    })?,
                guest_can_join: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")?
                    .map_or(Ok(false), |s| {
                        serde_json::from_str(s.content.get())
                            .map(|c: RoomGuestAccessEventContent| {
                                c.guest_access == GuestAccess::CanJoin
                            })
                            .map_err(|_| {
                                Error::bad_database("Invalid room guest access event in database.")
                            })
                    })?,
                avatar_url: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomAvatar, "")?
                    .map(|s| {
                        serde_json::from_str(s.content.get())
                            .map(|c: RoomAvatarEventContent| c.url)
                            .map_err(|_| {
                                Error::bad_database("Invalid room avatar event in database.")
                            })
                    })
                    .transpose()?
                    // url is now an Option<String> so we must flatten
                    .flatten(),
                join_rule: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomJoinRules, "")?
                    .map(|s| {
                        serde_json::from_str(s.content.get())
                            .map(|c: RoomJoinRulesEventContent| match c.join_rule {
                                JoinRule::Public => Some(PublicRoomJoinRule::Public),
                                JoinRule::Knock => Some(PublicRoomJoinRule::Knock),
                                _ => None,
                            })
                            .map_err(|e| {
                                error!("Invalid room join rule event in database: {}", e);
                                Error::BadDatabase("Invalid room join rule event in database.")
                            })
                    })
                    .transpose()?
                    .flatten()
                    .ok_or_else(|| Error::bad_database("Missing room join rule event for room."))?,
                room_type: services()
                    .rooms
                    .state_accessor
                    .room_state_get(&room_id, &StateEventType::RoomCreate, "")?
                    .map(|s| {
                        serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(
                            |e| {
                                error!("Invalid room create event in database: {}", e);
                                Error::BadDatabase("Invalid room create event in database.")
                            },
                        )
                    })
                    .transpose()?
                    .and_then(|e| e.room_type),
                room_id,
            };
            Ok(chunk)
        })
        .filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms
        .filter(|chunk| {
            if let Some(query) = filter
                .generic_search_term
                .as_ref()
                .map(|q| q.to_lowercase())
            {
                if let Some(name) = &chunk.name {
                    if name.as_str().to_lowercase().contains(&query) {
                        return true;
                    }
                }

                if let Some(topic) = &chunk.topic {
                    if topic.to_lowercase().contains(&query) {
                        return true;
                    }
                }

                if let Some(canonical_alias) = &chunk.canonical_alias {
                    if canonical_alias.as_str().to_lowercase().contains(&query) {
                        return true;
                    }
                }

                false
            } else {
                // No search term
                true
            }
        })
        // We need to collect all, so we can sort by member count
        .collect();

    all_rooms.sort_by(|l, r| r.num_joined_members.cmp(&l.num_joined_members));

    let total_room_count_estimate = (all_rooms.len() as u32).into();

    let chunk: Vec<_> = all_rooms
        .into_iter()
        .skip(num_since as usize)
        .take(limit as usize)
        .collect();

    let prev_batch = if num_since == 0 {
        None
    } else {
        Some(format!("p{num_since}"))
    };

    let next_batch = if chunk.len() < limit as usize {
        None
    } else {
        Some(format!("n{}", num_since + limit))
    };

    Ok(get_public_rooms_filtered::v3::Response {
        chunk,
        prev_batch,
        next_batch,
        total_room_count_estimate: Some(total_room_count_estimate),
    })
}