summaryrefslogtreecommitdiff
path: root/src/api/client_server/alias.rs
blob: 7660ca2f5928c41af571c7813c0240ffebf75ee1 (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
use crate::{services, Error, Result, Ruma};
use rand::seq::SliceRandom;
use regex::Regex;
use ruma::{
    api::{
        appservice,
        client::{
            alias::{create_alias, delete_alias, get_alias},
            error::ErrorKind,
        },
        federation,
    },
    OwnedRoomAliasId,
};

/// # `PUT /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Creates a new room alias on this server.
pub async fn create_alias_route(
    body: Ruma<create_alias::v3::Request>,
) -> Result<create_alias::v3::Response> {
    if body.room_alias.server_name() != services().globals.server_name() {
        return Err(Error::BadRequest(
            ErrorKind::InvalidParam,
            "Alias is from another server.",
        ));
    }

    if services()
        .rooms
        .alias
        .resolve_local_alias(&body.room_alias)?
        .is_some()
    {
        return Err(Error::Conflict("Alias already exists."));
    }

    services()
        .rooms
        .alias
        .set_alias(&body.room_alias, &body.room_id)?;

    Ok(create_alias::v3::Response::new())
}

/// # `DELETE /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Deletes a room alias from this server.
///
/// - TODO: additional access control checks
/// - TODO: Update canonical alias event
pub async fn delete_alias_route(
    body: Ruma<delete_alias::v3::Request>,
) -> Result<delete_alias::v3::Response> {
    if body.room_alias.server_name() != services().globals.server_name() {
        return Err(Error::BadRequest(
            ErrorKind::InvalidParam,
            "Alias is from another server.",
        ));
    }

    services().rooms.alias.remove_alias(&body.room_alias)?;

    // TODO: update alt_aliases?

    Ok(delete_alias::v3::Response::new())
}

/// # `GET /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Resolve an alias locally or over federation.
///
/// - TODO: Suggest more servers to join via
pub async fn get_alias_route(
    body: Ruma<get_alias::v3::Request>,
) -> Result<get_alias::v3::Response> {
    get_alias_helper(body.body.room_alias).await
}

pub(crate) async fn get_alias_helper(
    room_alias: OwnedRoomAliasId,
) -> Result<get_alias::v3::Response> {
    if room_alias.server_name() != services().globals.server_name() {
        let response = services()
            .sending
            .send_federation_request(
                room_alias.server_name(),
                federation::query::get_room_information::v1::Request {
                    room_alias: room_alias.to_owned(),
                },
            )
            .await?;

        let mut servers = response.servers;
        servers.shuffle(&mut rand::thread_rng());

        return Ok(get_alias::v3::Response::new(response.room_id, servers));
    }

    let mut room_id = None;
    match services().rooms.alias.resolve_local_alias(&room_alias)? {
        Some(r) => room_id = Some(r),
        None => {
            for (_id, registration) in services().appservice.all()? {
                let aliases = registration
                    .get("namespaces")
                    .and_then(|ns| ns.get("aliases"))
                    .and_then(|aliases| aliases.as_sequence())
                    .map_or_else(Vec::new, |aliases| {
                        aliases
                            .iter()
                            .filter_map(|aliases| Regex::new(aliases.get("regex")?.as_str()?).ok())
                            .collect::<Vec<_>>()
                    });

                if aliases
                    .iter()
                    .any(|aliases| aliases.is_match(room_alias.as_str()))
                    && services()
                        .sending
                        .send_appservice_request(
                            registration,
                            appservice::query::query_room_alias::v1::Request {
                                room_alias: room_alias.clone(),
                            },
                        )
                        .await
                        .is_ok()
                {
                    room_id = Some(
                        services()
                            .rooms
                            .alias
                            .resolve_local_alias(&room_alias)?
                            .ok_or_else(|| {
                                Error::bad_config("Appservice lied to us. Room does not exist.")
                            })?,
                    );
                    break;
                }
            }
        }
    };

    let room_id = match room_id {
        Some(room_id) => room_id,
        None => {
            return Err(Error::BadRequest(
                ErrorKind::NotFound,
                "Room with alias not found.",
            ))
        }
    };

    Ok(get_alias::v3::Response::new(
        room_id,
        vec![services().globals.server_name().to_owned()],
    ))
}