Skip to main content

ruma_events/call/member/
focus.rs

1//! Types for MatrixRTC Focus/SFU configurations.
2
3use std::borrow::Cow;
4
5use ruma_common::{OwnedServerName, serde::JsonObject};
6use ruma_macros::StringEnum;
7use serde::{Deserialize, Deserializer, Serialize};
8
9use crate::PrivOwnedStr;
10
11/// Description of the SFU/Focus a membership can be connected to.
12///
13/// A focus can be any server powering the MatrixRTC session (SFU,
14/// MCU). It serves as a node to redistribute RTC streams.
15#[allow(deprecated)]
16#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
17#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
18#[serde(tag = "type")]
19pub enum Focus {
20    /// A LiveKit focus, as defined in the merged state of [MSC4195].
21    ///
22    /// [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195
23    #[serde(rename = "m.livekit")]
24    Livekit(LivekitFocus),
25
26    /// A LiveKit focus with the `livekit` type used by implementations of earlier versions of
27    /// [MSC4195].
28    ///
29    /// [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195
30    #[serde(rename = "livekit")]
31    #[deprecated = "Use `Focus::Livekit` instead unless you require backwards compatibility with older versions of MSC4195."]
32    LegacyLivekit(LivekitFocus),
33
34    /// A custom focus.
35    #[doc(hidden)]
36    #[serde(untagged)]
37    _Custom(CustomFocus),
38}
39
40impl<'de> Deserialize<'de> for Focus {
41    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
42    where
43        D: Deserializer<'de>,
44    {
45        use serde::de::Error;
46
47        let mut obj = JsonObject::deserialize(deserializer)?;
48        let focus_type = match obj.remove("type") {
49            Some(serde_json::Value::String(s)) => s,
50            Some(_) => return Err(D::Error::custom("`type` must be a string")),
51            None => return Err(D::Error::missing_field("type")),
52        };
53
54        Self::new(&focus_type, obj).map_err(D::Error::custom)
55    }
56}
57
58impl Focus {
59    /// A constructor to create a custom focus.
60    ///
61    /// Prefer to use the public variants of `Focus` where possible; this constructor is meant to
62    /// be used for unsupported focus types only and does not allow setting arbitrary data for
63    /// supported ones.
64    ///
65    /// # Errors
66    ///
67    /// Returns an error if the `focus_type` is known and deserialization of `data` to the
68    /// corresponding `Focus` variant fails.
69    pub fn new(focus_type: &str, data: JsonObject) -> serde_json::Result<Self> {
70        Ok(match focus_type {
71            "m.livekit" => Self::Livekit(serde_json::from_value(serde_json::Value::Object(data))?),
72            #[allow(deprecated)]
73            "livekit" => {
74                Self::LegacyLivekit(serde_json::from_value(serde_json::Value::Object(data))?)
75            }
76            _ => Self::_Custom(CustomFocus { focus_type: focus_type.to_owned(), data }),
77        })
78    }
79
80    /// Creates a new `Focus::Livekit` with the given SFU URL.
81    pub fn livekit(url: String) -> Self {
82        Self::Livekit(LivekitFocus::new(url))
83    }
84
85    /// Returns the type of this focus.
86    pub fn focus_type(&self) -> &str {
87        match self {
88            Self::Livekit(_) => "m.livekit",
89            #[allow(deprecated)]
90            Self::LegacyLivekit(_) => "livekit",
91            Self::_Custom(custom) => &custom.focus_type,
92        }
93    }
94
95    /// Returns the associated data.
96    ///
97    /// The returned JSON object won't contain the `type` field, please use
98    /// [`.focus_type()`][Self::focus_type] to access that.
99    ///
100    /// Prefer to use the public variants of `Focus` where possible; this method is meant to be
101    /// used for custom focus types only.
102    pub fn data(&self) -> Cow<'_, JsonObject> {
103        match self {
104            Self::Livekit(info) => Cow::Owned(serialize_focus_data(info)),
105            #[allow(deprecated)]
106            Self::LegacyLivekit(info) => Cow::Owned(serialize_focus_data(info)),
107            Self::_Custom(info) => Cow::Borrowed(&info.data),
108        }
109    }
110}
111
112/// Serializes the data of a known focus type to a JSON object.
113fn serialize_focus_data<T: Serialize>(object: &T) -> JsonObject {
114    use serde_json::Value as JsonValue;
115
116    match serde_json::to_value(object).expect("focus type serialization to succeed") {
117        JsonValue::Object(object) => object,
118        _ => panic!("all focus types must serialize to objects"),
119    }
120}
121
122/// The struct to describe LiveKit as a `preferred_foci`.
123///
124/// This is used for both the `m.livekit` and the legacy `livekit` focus types. Implementations of
125/// earlier versions of [MSC4195] may omit the `url` and use `livekit_service_url` instead,
126/// independently of the focus type.
127///
128/// [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195
129#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
130#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
131pub struct LivekitFocus {
132    /// The alias where the LiveKit sessions can be reached.
133    #[serde(rename = "livekit_alias", skip_serializing_if = "Option::is_none")]
134    #[deprecated = "Newer versions of Element Call won't fill this field anymore."]
135    pub alias: Option<String>,
136
137    /// The WebSocket URL of the LiveKit SFU.
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub url: Option<String>,
140
141    /// The server name of the homeserver that grants access to the LiveKit SFU.
142    ///
143    /// This must be set when publishing on an SFU of a different homeserver than the sender's. If
144    /// this is `None`, the SFU belongs to the sender's homeserver.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub server_name: Option<OwnedServerName>,
147
148    /// The URL of the JWT service for the LiveKit instance.
149    #[serde(rename = "livekit_service_url", skip_serializing_if = "Option::is_none")]
150    #[deprecated = "Use `url` instead unless you require backwards compatibility with older versions of MSC4195."]
151    pub service_url: Option<String>,
152}
153
154impl LivekitFocus {
155    /// Initialize a [`LivekitFocus`] with the given SFU URL.
156    ///
157    /// # Arguments
158    ///
159    /// * `url` - The WebSocket URL of the LiveKit SFU.
160    #[allow(deprecated)]
161    pub fn new(url: String) -> Self {
162        Self { alias: None, url: Some(url), server_name: None, service_url: None }
163    }
164
165    /// Initialize a [`LivekitFocus`] with the given JWT service URL.
166    ///
167    /// # Arguments
168    ///
169    /// * `service_url` - The URL of the JWT service for the LiveKit instance.
170    #[deprecated = "Use `LivekitFocus::new()` instead unless you require backwards compatibility with older versions of MSC4195."]
171    #[allow(deprecated)]
172    pub fn with_service_url(service_url: String) -> Self {
173        Self { alias: None, url: None, server_name: None, service_url: Some(service_url) }
174    }
175}
176
177/// Information about a custom focus.
178///
179/// This type does not implement `Deserialize` to prevent users from constructing the `_Custom`
180/// variant of [`Focus`] for a known `type`. Deserialize through [`Focus`] instead.
181#[doc(hidden)]
182#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
183pub struct CustomFocus {
184    /// The type of focus.
185    #[serde(rename = "type")]
186    focus_type: String,
187
188    /// Remaining focus data.
189    #[serde(flatten)]
190    data: JsonObject,
191}
192
193/// Data to define the actively used Focus.
194///
195/// A focus can be any server powering the MatrixRTC session (SFU,
196/// MCU). It serves as a node to redistribute RTC streams.
197#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
198#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
199#[serde(tag = "type", rename_all = "snake_case")]
200pub enum ActiveFocus {
201    /// LiveKit is one possible type of SFU/Focus that can be used for a MatrixRTC session.
202    Livekit(ActiveLivekitFocus),
203}
204
205/// The fields to describe the `active_foci`.
206#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
207#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
208pub struct ActiveLivekitFocus {
209    /// The selection method used to select the LiveKit focus for the rtc session.
210    pub focus_selection: FocusSelection,
211}
212
213impl ActiveLivekitFocus {
214    /// Initialize a [`ActiveLivekitFocus`].
215    ///
216    /// # Arguments
217    ///
218    /// * `focus_selection` - The selection method used to select the LiveKit focus for the rtc
219    ///   session.
220    pub fn new() -> Self {
221        Self { focus_selection: FocusSelection::OldestMembership }
222    }
223}
224
225/// How to select the active focus for LiveKit
226#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
227#[derive(Clone, StringEnum)]
228#[ruma_enum(rename_all = "snake_case")]
229#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
230pub enum FocusSelection {
231    /// Select the active focus by using the oldest membership and the oldest focus.
232    OldestMembership,
233
234    #[doc(hidden)]
235    _Custom(PrivOwnedStr),
236}