matrix_appservice_rs/
matrix.rs

1use ruma::api::exports::http::uri;
2use ruma::identifiers::{EventId, MxcUri, RoomId, UserId};
3
4/// An item that can be represented using a matrix.to URL.
5#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6pub enum MatrixToItem<'a> {
7    /// An event, since event IDs are room local a RoomId is required.
8    Event(&'a RoomId, &'a EventId),
9    /// An ID of an user.
10    User(&'a UserId),
11    /// A ID to a group, the first character must be an +.
12    Group(&'a String),
13}
14
15impl<'a> MatrixToItem<'a> {
16    /// Convert the current `MatrixToItem` into a `String`.
17    pub fn to_url_string(&self) -> String {
18        let slug = match self {
19            MatrixToItem::Event(room_id, event_id) => format!("{}/{}", room_id, event_id),
20            MatrixToItem::User(user_id) => user_id.to_string(),
21            MatrixToItem::Group(group_id) => group_id.to_string(),
22        };
23
24        format!("https://matrix.to/#/{}", slug)
25    }
26}
27
28/// An error from converting an MXC URI to a HTTP URL.
29#[derive(Debug)]
30pub enum MxcConversionError {
31    /// The given MXC URI is malformed.
32    InvalidMxc,
33    /// There was an error parsing the resulting URL into an URI object.
34    UriParseError(uri::InvalidUri),
35}
36
37impl From<uri::InvalidUri> for MxcConversionError {
38    fn from(err: uri::InvalidUri) -> Self {
39        MxcConversionError::UriParseError(err)
40    }
41}
42
43/// Convert the given MXC URI into a HTTP URL, using the given `homeserver_url` as the host to the
44/// MXC content.
45pub fn mxc_to_url(
46    homeserver_url: &uri::Uri,
47    mxc_uri: &MxcUri,
48) -> Result<uri::Uri, MxcConversionError> {
49    let (server_name, id) = mxc_uri.parts().ok_or(MxcConversionError::InvalidMxc)?;
50
51    let res = format!(
52        "{}_matrix/media/r0/download/{}/{}",
53        homeserver_url, server_name, id
54    );
55    Ok(res.parse()?)
56}