Skip to main content

ruma_client_api/
rtc.rs

1//! [MatrixRTC] endpoints.
2//!
3//! [MatrixRTC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143
4
5use std::borrow::Cow;
6
7use ruma_common::serde::JsonObject;
8use serde::{Deserialize, Deserializer, Serialize};
9
10#[cfg(feature = "unstable-msc4195")]
11pub mod livekit;
12pub mod transports;
13
14/// Information about a specific MatrixRTC transport.
15#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
16#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
17#[serde(tag = "type")]
18pub enum RtcTransport {
19    /// A LiveKit RTC transport.
20    #[cfg(feature = "unstable-msc4195")]
21    #[serde(rename = "livekit")]
22    LiveKit(LiveKitRtcTransport),
23
24    /// A custom RTC transport.
25    #[doc(hidden)]
26    #[serde(untagged)]
27    _Custom(CustomRtcTransport),
28}
29
30impl<'de> Deserialize<'de> for RtcTransport {
31    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
32    where
33        D: Deserializer<'de>,
34    {
35        use serde::de::Error;
36
37        let mut obj = JsonObject::deserialize(deserializer)?;
38        let transport_type = match obj.remove("type") {
39            Some(serde_json::Value::String(s)) => s,
40            Some(_) => return Err(D::Error::custom("`type` must be a string")),
41            None => return Err(D::Error::missing_field("type")),
42        };
43
44        Ok(match transport_type.as_str() {
45            #[cfg(feature = "unstable-msc4195")]
46            "livekit" => Self::LiveKit(
47                serde_json::from_value(serde_json::Value::Object(obj)).map_err(D::Error::custom)?,
48            ),
49            _ => Self::_Custom(CustomRtcTransport { transport_type, data: obj }),
50        })
51    }
52}
53
54impl RtcTransport {
55    /// A constructor to create a custom RTC transport.
56    ///
57    /// Prefer to use the public variants of `RtcTransport` where possible; this constructor is
58    /// meant to be used for unsupported transport types only and does not allow setting arbitrary
59    /// data for supported ones.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error if the `transport_type` is known and serialization of `data` to the
64    /// corresponding `RtcTransport` variant fails.
65    pub fn new(transport_type: &str, data: JsonObject) -> serde_json::Result<Self> {
66        Ok(match transport_type {
67            #[cfg(feature = "unstable-msc4195")]
68            "livekit" => Self::LiveKit(serde_json::from_value(serde_json::Value::Object(data))?),
69            _ => Self::_Custom(CustomRtcTransport {
70                transport_type: transport_type.to_owned(),
71                data,
72            }),
73        })
74    }
75
76    #[cfg(feature = "unstable-msc4195")]
77    /// Creates a new `RtcTransport::LiveKit`.
78    pub fn livekit(service_url: String) -> Self {
79        Self::LiveKit(LiveKitRtcTransport { service_url })
80    }
81
82    /// Returns a reference to the transport type of this RTC transport.
83    pub fn transport_type(&self) -> &str {
84        match self {
85            #[cfg(feature = "unstable-msc4195")]
86            Self::LiveKit(_) => "livekit",
87            Self::_Custom(custom) => &custom.transport_type,
88        }
89    }
90
91    /// Returns the associated data.
92    ///
93    /// The returned JSON object won't contain the `type` field, please use
94    /// [`.transport_type()`][Self::transport_type] to access that.
95    ///
96    /// Prefer to use the public variants of `RtcTransport` where possible; this method is meant
97    /// to be used for custom transport types only.
98    pub fn data(&self) -> Cow<'_, JsonObject> {
99        #[cfg(feature = "unstable-msc4195")]
100        fn serialize<T: Serialize>(object: &T) -> JsonObject {
101            use serde_json::Value as JsonValue;
102
103            match serde_json::to_value(object).expect("rtc transport type serialization to succeed")
104            {
105                JsonValue::Object(object) => object,
106                _ => panic!("all rtc transport types must serialize to objects"),
107            }
108        }
109
110        match self {
111            #[cfg(feature = "unstable-msc4195")]
112            Self::LiveKit(info) => Cow::Owned(serialize(info)),
113            Self::_Custom(info) => Cow::Borrowed(&info.data),
114        }
115    }
116}
117
118/// Information about a LiveKit RTC transport.
119#[cfg(feature = "unstable-msc4195")]
120#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
121#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
122pub struct LiveKitRtcTransport {
123    /// The URL for the LiveKit service.
124    #[serde(rename = "livekit_service_url")]
125    pub service_url: String,
126}
127
128#[cfg(feature = "unstable-msc4195")]
129impl LiveKitRtcTransport {
130    /// Creates a new `LiveKitRtcTransport` with the given service URL.
131    pub fn new(service_url: String) -> Self {
132        Self { service_url }
133    }
134}
135
136#[cfg(feature = "unstable-msc4195")]
137impl From<LiveKitRtcTransport> for RtcTransport {
138    fn from(value: LiveKitRtcTransport) -> Self {
139        Self::LiveKit(value)
140    }
141}
142
143/// Information about a custom RTC transport.
144///
145/// This type does not implement `Deserialize` to prevent users from
146/// constructing the `_Custom` variant of [`RtcTransport`] for a known `type`.
147/// Deserialize through [`RtcTransport`] instead.
148#[doc(hidden)]
149#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
150pub struct CustomRtcTransport {
151    /// The type of RTC transport.
152    #[serde(rename = "type")]
153    transport_type: String,
154
155    /// Remaining RTC transport data.
156    #[serde(flatten)]
157    data: JsonObject,
158}
159
160#[cfg(test)]
161mod tests {
162    use serde_json::{
163        Value as JsonValue, from_value as from_json_value, json, to_value as to_json_value,
164    };
165    use strass::assert_let;
166
167    use super::RtcTransport;
168
169    #[test]
170    fn serialize_roundtrip_custom_rtc_transport() {
171        let transport_type = "local.custom.transport";
172        assert_let!(
173            JsonValue::Object(transport_data) = json!({
174                "foo": "bar",
175                "baz": true,
176            })
177        );
178        let transport = RtcTransport::new(transport_type, transport_data.clone()).unwrap();
179        let json = json!({
180            "type": transport_type,
181            "foo": "bar",
182            "baz": true,
183        });
184
185        assert_eq!(transport.transport_type(), transport_type);
186        assert_eq!(*transport.data().as_ref(), transport_data);
187        assert_eq!(to_json_value(&transport).unwrap(), json);
188        assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport);
189    }
190
191    #[cfg(feature = "unstable-msc4195")]
192    #[test]
193    fn livekit_transport_new_and_from_impl() {
194        use super::LiveKitRtcTransport;
195
196        let url = "http://livekit.local/".to_owned();
197        let inner = LiveKitRtcTransport::new(url.clone());
198        let transport = RtcTransport::from(inner);
199        assert_eq!(transport.transport_type(), "livekit");
200        assert_eq!(transport, RtcTransport::livekit(url));
201    }
202
203    #[cfg(feature = "unstable-msc4195")]
204    #[test]
205    fn serialize_roundtrip_livekit_sfu_transport() {
206        let transport_type = "livekit";
207        let livekit_service_url = "http://livekit.local/";
208        let transport = RtcTransport::livekit(livekit_service_url.to_owned());
209        let json = json!({
210            "type": transport_type,
211            "livekit_service_url": livekit_service_url,
212        });
213
214        assert_eq!(transport.transport_type(), transport_type);
215        assert_eq!(to_json_value(&transport).unwrap(), json);
216        assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport);
217    }
218}