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#[allow(deprecated)] // for the derives on the deprecated `LegacyLiveKit` variant
16#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
17#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
18#[serde(tag = "type")]
19pub enum RtcTransport {
20    /// A LiveKit RTC transport, as defined in the merged state of [MSC4195].
21    ///
22    /// [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195
23    #[cfg(feature = "unstable-msc4195")]
24    #[serde(rename = "m.livekit")]
25    LiveKit(LiveKitRtcTransport),
26
27    /// A LiveKit RTC transport with the `livekit` type used by implementations of earlier
28    /// versions of [MSC4195].
29    ///
30    /// [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195
31    #[cfg(feature = "unstable-msc4195")]
32    #[serde(rename = "livekit")]
33    #[deprecated = "Use `RtcTransport::LiveKit` instead unless you require backwards compatibility with older versions of MSC4195."]
34    LegacyLiveKit(LegacyLiveKitRtcTransport),
35
36    /// A custom RTC transport.
37    #[doc(hidden)]
38    #[serde(untagged)]
39    _Custom(CustomRtcTransport),
40}
41
42impl<'de> Deserialize<'de> for RtcTransport {
43    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
44    where
45        D: Deserializer<'de>,
46    {
47        use serde::de::Error;
48
49        let mut obj = JsonObject::deserialize(deserializer)?;
50        let transport_type = match obj.remove("type") {
51            Some(serde_json::Value::String(s)) => s,
52            Some(_) => return Err(D::Error::custom("`type` must be a string")),
53            None => return Err(D::Error::missing_field("type")),
54        };
55
56        Ok(match transport_type.as_str() {
57            #[cfg(feature = "unstable-msc4195")]
58            "m.livekit" => Self::LiveKit(
59                serde_json::from_value(serde_json::Value::Object(obj)).map_err(D::Error::custom)?,
60            ),
61            #[cfg(feature = "unstable-msc4195")]
62            #[allow(deprecated)]
63            "livekit" => Self::LegacyLiveKit(
64                serde_json::from_value(serde_json::Value::Object(obj)).map_err(D::Error::custom)?,
65            ),
66            _ => Self::_Custom(CustomRtcTransport { transport_type, data: obj }),
67        })
68    }
69}
70
71impl RtcTransport {
72    /// A constructor to create a custom RTC transport.
73    ///
74    /// Prefer to use the public variants of `RtcTransport` where possible; this constructor is
75    /// meant to be used for unsupported transport types only and does not allow setting arbitrary
76    /// data for supported ones.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if the `transport_type` is known and serialization of `data` to the
81    /// corresponding `RtcTransport` variant fails.
82    pub fn new(transport_type: &str, data: JsonObject) -> serde_json::Result<Self> {
83        Ok(match transport_type {
84            #[cfg(feature = "unstable-msc4195")]
85            "m.livekit" => Self::LiveKit(serde_json::from_value(serde_json::Value::Object(data))?),
86            #[cfg(feature = "unstable-msc4195")]
87            #[allow(deprecated)]
88            "livekit" => {
89                Self::LegacyLiveKit(serde_json::from_value(serde_json::Value::Object(data))?)
90            }
91            _ => Self::_Custom(CustomRtcTransport {
92                transport_type: transport_type.to_owned(),
93                data,
94            }),
95        })
96    }
97
98    #[cfg(feature = "unstable-msc4195")]
99    /// Creates a new `RtcTransport::LiveKit` with the given SFU URL.
100    pub fn livekit(url: String) -> Self {
101        Self::LiveKit(LiveKitRtcTransport::new(url))
102    }
103
104    /// Returns a reference to the transport type of this RTC transport.
105    pub fn transport_type(&self) -> &str {
106        match self {
107            #[cfg(feature = "unstable-msc4195")]
108            Self::LiveKit(_) => "m.livekit",
109            #[cfg(feature = "unstable-msc4195")]
110            #[allow(deprecated)]
111            Self::LegacyLiveKit(_) => "livekit",
112            Self::_Custom(custom) => &custom.transport_type,
113        }
114    }
115
116    /// Returns the associated data.
117    ///
118    /// The returned JSON object won't contain the `type` field, please use
119    /// [`.transport_type()`][Self::transport_type] to access that.
120    ///
121    /// Prefer to use the public variants of `RtcTransport` where possible; this method is meant
122    /// to be used for custom transport types only.
123    pub fn data(&self) -> Cow<'_, JsonObject> {
124        #[cfg(feature = "unstable-msc4195")]
125        fn serialize<T: Serialize>(object: &T) -> JsonObject {
126            use serde_json::Value as JsonValue;
127
128            match serde_json::to_value(object).expect("rtc transport type serialization to succeed")
129            {
130                JsonValue::Object(object) => object,
131                _ => panic!("all rtc transport types must serialize to objects"),
132            }
133        }
134
135        match self {
136            #[cfg(feature = "unstable-msc4195")]
137            Self::LiveKit(info) => Cow::Owned(serialize(info)),
138            #[cfg(feature = "unstable-msc4195")]
139            #[allow(deprecated)]
140            Self::LegacyLiveKit(info) => Cow::Owned(serialize(info)),
141            Self::_Custom(info) => Cow::Borrowed(&info.data),
142        }
143    }
144}
145
146/// Information about an `m.livekit` RTC transport.
147#[cfg(feature = "unstable-msc4195")]
148#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
149#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
150pub struct LiveKitRtcTransport {
151    /// The WebSocket URL of the LiveKit SFU.
152    pub url: String,
153
154    /// The URL for the LiveKit JWT service.
155    #[serde(rename = "livekit_service_url", skip_serializing_if = "Option::is_none")]
156    #[deprecated = "Use `url` instead unless you require backwards compatibility with older versions of MSC4195."]
157    pub service_url: Option<String>,
158}
159
160#[cfg(feature = "unstable-msc4195")]
161impl LiveKitRtcTransport {
162    /// Creates a new `LiveKitRtcTransport` with the given SFU URL.
163    #[allow(deprecated)]
164    pub fn new(url: String) -> Self {
165        Self { url, service_url: None }
166    }
167}
168
169#[cfg(feature = "unstable-msc4195")]
170impl From<LiveKitRtcTransport> for RtcTransport {
171    fn from(value: LiveKitRtcTransport) -> Self {
172        Self::LiveKit(value)
173    }
174}
175
176/// Information about a legacy `livekit` RTC transport.
177#[cfg(feature = "unstable-msc4195")]
178#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
179#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
180#[deprecated = "Use `LiveKitRtcTransport` instead unless you require backwards compatibility with older versions of MSC4195."]
181pub struct LegacyLiveKitRtcTransport {
182    /// The WebSocket URL of the LiveKit SFU.
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub url: Option<String>,
185
186    /// The URL for the LiveKit JWT service.
187    #[serde(rename = "livekit_service_url", skip_serializing_if = "Option::is_none")]
188    pub service_url: Option<String>,
189}
190
191#[cfg(feature = "unstable-msc4195")]
192#[allow(deprecated)]
193impl LegacyLiveKitRtcTransport {
194    /// Creates a new `LegacyLiveKitRtcTransport` with the given SFU URL.
195    pub fn new(url: String) -> Self {
196        Self { url: Some(url), service_url: None }
197    }
198
199    /// Creates a new `LegacyLiveKitRtcTransport` with the given JWT service URL.
200    pub fn with_service_url(service_url: String) -> Self {
201        Self { url: None, service_url: Some(service_url) }
202    }
203}
204
205#[cfg(feature = "unstable-msc4195")]
206#[allow(deprecated)]
207impl From<LegacyLiveKitRtcTransport> for RtcTransport {
208    fn from(value: LegacyLiveKitRtcTransport) -> Self {
209        Self::LegacyLiveKit(value)
210    }
211}
212
213/// Information about a custom RTC transport.
214///
215/// This type does not implement `Deserialize` to prevent users from
216/// constructing the `_Custom` variant of [`RtcTransport`] for a known `type`.
217/// Deserialize through [`RtcTransport`] instead.
218#[doc(hidden)]
219#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
220pub struct CustomRtcTransport {
221    /// The type of RTC transport.
222    #[serde(rename = "type")]
223    transport_type: String,
224
225    /// Remaining RTC transport data.
226    #[serde(flatten)]
227    data: JsonObject,
228}
229
230#[cfg(test)]
231mod tests {
232    use serde_json::{
233        Value as JsonValue, from_value as from_json_value, json, to_value as to_json_value,
234    };
235    use strass::assert_let;
236
237    use super::RtcTransport;
238
239    #[test]
240    fn serialize_roundtrip_custom_rtc_transport() {
241        let transport_type = "local.custom.transport";
242        assert_let!(
243            JsonValue::Object(transport_data) = json!({
244                "foo": "bar",
245                "baz": true,
246            })
247        );
248        let transport = RtcTransport::new(transport_type, transport_data.clone()).unwrap();
249        let json = json!({
250            "type": transport_type,
251            "foo": "bar",
252            "baz": true,
253        });
254
255        assert_eq!(transport.transport_type(), transport_type);
256        assert_eq!(*transport.data().as_ref(), transport_data);
257        assert_eq!(to_json_value(&transport).unwrap(), json);
258        assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport);
259    }
260
261    #[cfg(feature = "unstable-msc4195")]
262    #[test]
263    fn livekit_transport_new_and_from_impl() {
264        use super::LiveKitRtcTransport;
265
266        let url = "wss://livekit.local/".to_owned();
267        let inner = LiveKitRtcTransport::new(url.clone());
268        let transport = RtcTransport::from(inner);
269        assert_eq!(transport.transport_type(), "m.livekit");
270        assert_eq!(transport, RtcTransport::livekit(url));
271    }
272
273    #[cfg(feature = "unstable-msc4195")]
274    #[test]
275    #[allow(deprecated)]
276    fn legacy_livekit_transport_new_and_from_impl() {
277        use super::LegacyLiveKitRtcTransport;
278
279        let url = "wss://livekit.local/".to_owned();
280        let transport = RtcTransport::from(LegacyLiveKitRtcTransport::new(url.clone()));
281        assert_eq!(transport.transport_type(), "livekit");
282        assert_let!(RtcTransport::LegacyLiveKit(livekit) = transport);
283        assert_eq!(livekit.url, Some(url));
284        assert_eq!(livekit.service_url, None);
285    }
286
287    #[cfg(feature = "unstable-msc4195")]
288    #[test]
289    fn serialize_roundtrip_livekit_sfu_transport() {
290        let transport_type = "m.livekit";
291        let url = "wss://livekit.local/";
292        let transport = RtcTransport::livekit(url.to_owned());
293        let json = json!({
294            "type": transport_type,
295            "url": url,
296        });
297
298        assert_eq!(transport.transport_type(), transport_type);
299        assert_eq!(to_json_value(&transport).unwrap(), json);
300        assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport);
301    }
302
303    #[cfg(feature = "unstable-msc4195")]
304    #[test]
305    #[allow(deprecated)]
306    fn serialize_roundtrip_legacy_livekit_sfu_transport() {
307        use super::LegacyLiveKitRtcTransport;
308
309        let transport_type = "livekit";
310        let url = "wss://livekit.local/";
311        let transport = RtcTransport::LegacyLiveKit(LegacyLiveKitRtcTransport::new(url.to_owned()));
312        let json = json!({
313            "type": transport_type,
314            "url": url,
315        });
316
317        assert_eq!(transport.transport_type(), transport_type);
318        assert_eq!(to_json_value(&transport).unwrap(), json);
319        assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport);
320    }
321
322    #[cfg(feature = "unstable-msc4195")]
323    #[test]
324    fn deserialize_livekit_sfu_transport_without_url_fails() {
325        let json = json!({
326            "type": "m.livekit",
327            "livekit_service_url": "https://livekit-jwt.local/",
328        });
329
330        from_json_value::<RtcTransport>(json).unwrap_err();
331    }
332
333    #[cfg(feature = "unstable-msc4195")]
334    #[test]
335    #[allow(deprecated)]
336    fn serialize_roundtrip_legacy_livekit_sfu_transport_with_service_url() {
337        use super::LegacyLiveKitRtcTransport;
338
339        let livekit_service_url = "https://livekit-jwt.local/";
340        let json = json!({
341            "type": "livekit",
342            "livekit_service_url": livekit_service_url,
343        });
344
345        assert_let!(Ok(RtcTransport::LegacyLiveKit(livekit)) = from_json_value(json.clone()));
346        assert_eq!(livekit.url, None);
347        assert_eq!(livekit.service_url.as_deref(), Some(livekit_service_url));
348        assert_eq!(
349            livekit,
350            LegacyLiveKitRtcTransport::with_service_url(livekit_service_url.to_owned())
351        );
352        assert_eq!(to_json_value(RtcTransport::LegacyLiveKit(livekit)).unwrap(), json);
353    }
354
355    #[cfg(feature = "unstable-msc4195")]
356    #[test]
357    #[allow(deprecated)]
358    fn serialize_roundtrip_livekit_sfu_transport_with_url_and_service_url() {
359        let url = "wss://livekit.local/";
360        let livekit_service_url = "https://livekit-jwt.local/";
361        let json = json!({
362            "type": "m.livekit",
363            "url": url,
364            "livekit_service_url": livekit_service_url,
365        });
366
367        assert_let!(Ok(RtcTransport::LiveKit(livekit)) = from_json_value(json.clone()));
368        assert_eq!(livekit.url, url);
369        assert_eq!(livekit.service_url.as_deref(), Some(livekit_service_url));
370        assert_eq!(to_json_value(RtcTransport::LiveKit(livekit)).unwrap(), json);
371    }
372
373    #[cfg(feature = "unstable-msc4195")]
374    #[test]
375    #[allow(deprecated)]
376    fn serialize_roundtrip_legacy_livekit_sfu_transport_with_url_and_service_url() {
377        let url = "wss://livekit.local/";
378        let livekit_service_url = "https://livekit-jwt.local/";
379        let json = json!({
380            "type": "livekit",
381            "url": url,
382            "livekit_service_url": livekit_service_url,
383        });
384
385        assert_let!(Ok(RtcTransport::LegacyLiveKit(livekit)) = from_json_value(json.clone()));
386        assert_eq!(livekit.url.as_deref(), Some(url));
387        assert_eq!(livekit.service_url.as_deref(), Some(livekit_service_url));
388        assert_eq!(to_json_value(RtcTransport::LegacyLiveKit(livekit)).unwrap(), json);
389    }
390
391    #[cfg(feature = "unstable-msc4195")]
392    #[test]
393    fn new_livekit_sfu_transport_without_url_fails() {
394        assert_let!(
395            JsonValue::Object(data) = json!({
396                "livekit_service_url": "https://livekit-jwt.local/",
397            })
398        );
399
400        RtcTransport::new("m.livekit", data).unwrap_err();
401    }
402
403    #[cfg(feature = "unstable-msc4195")]
404    #[test]
405    #[allow(deprecated)]
406    fn new_livekit_sfu_transport_with_url_and_service_url() {
407        assert_let!(
408            JsonValue::Object(data) = json!({
409                "url": "wss://livekit.local/",
410                "livekit_service_url": "https://livekit-jwt.local/",
411            })
412        );
413
414        let transport = RtcTransport::new("m.livekit", data.clone()).unwrap();
415        assert_eq!(transport.transport_type(), "m.livekit");
416        assert_let!(RtcTransport::LiveKit(livekit) = &transport);
417        assert_eq!(livekit.url, "wss://livekit.local/");
418        assert_eq!(livekit.service_url.as_deref(), Some("https://livekit-jwt.local/"));
419        assert_eq!(*transport.data(), data);
420    }
421
422    #[cfg(feature = "unstable-msc4195")]
423    #[test]
424    #[allow(deprecated)]
425    fn new_legacy_livekit_sfu_transport_with_service_url() {
426        assert_let!(
427            JsonValue::Object(data) = json!({
428                "livekit_service_url": "https://livekit-jwt.local/",
429            })
430        );
431
432        let transport = RtcTransport::new("livekit", data.clone()).unwrap();
433        assert_eq!(transport.transport_type(), "livekit");
434        assert_let!(RtcTransport::LegacyLiveKit(livekit) = &transport);
435        assert_eq!(livekit.url, None);
436        assert_eq!(livekit.service_url.as_deref(), Some("https://livekit-jwt.local/"));
437        assert_eq!(*transport.data(), data);
438    }
439
440    #[cfg(feature = "unstable-msc4195")]
441    #[test]
442    #[allow(deprecated)]
443    fn serialize_roundtrip_livekit_and_legacy_livekit_sfu_transports() {
444        use super::LegacyLiveKitRtcTransport;
445
446        let json = json!([
447            { "type": "livekit", "livekit_service_url": "https://livekit-jwt.local/" },
448            { "type": "livekit", "url": "wss://livekit.local/" },
449            { "type": "m.livekit", "url": "wss://livekit.local/" },
450        ]);
451
452        let transports = from_json_value::<Vec<RtcTransport>>(json.clone()).unwrap();
453        assert_eq!(
454            transports,
455            [
456                RtcTransport::LegacyLiveKit(LegacyLiveKitRtcTransport::with_service_url(
457                    "https://livekit-jwt.local/".to_owned(),
458                )),
459                RtcTransport::LegacyLiveKit(LegacyLiveKitRtcTransport::new(
460                    "wss://livekit.local/".to_owned(),
461                )),
462                RtcTransport::livekit("wss://livekit.local/".to_owned()),
463            ]
464        );
465        assert_eq!(to_json_value(&transports).unwrap(), json);
466    }
467}