matrix_sdk/widget/settings/
mod.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use language_tags::LanguageTag;
16use ruma::{
17    api::client::profile::{get_profile, AvatarUrl, DisplayName},
18    DeviceId, RoomId, UserId,
19};
20use url::Url;
21
22use crate::Room;
23
24mod element_call;
25mod url_params;
26
27pub use self::element_call::{EncryptionSystem, Intent, VirtualElementCallWidgetOptions};
28
29/// Settings of the widget.
30#[derive(Debug, Clone)]
31pub struct WidgetSettings {
32    widget_id: String,
33    init_on_content_load: bool,
34    raw_url: Url,
35}
36
37impl WidgetSettings {
38    /// Create a new WidgetSettings instance
39    pub fn new(
40        id: String,
41        init_on_content_load: bool,
42        raw_url: &str,
43    ) -> Result<Self, url::ParseError> {
44        Ok(Self { widget_id: id, init_on_content_load, raw_url: Url::parse(raw_url)? })
45    }
46
47    /// Widget's unique identifier.
48    pub fn widget_id(&self) -> &str {
49        &self.widget_id
50    }
51
52    /// Whether or not the widget should be initialized on load message
53    /// (`ContentLoad` message), or upon creation/attaching of the widget to
54    /// the SDK's state machine that drives the API.
55    pub fn init_on_content_load(&self) -> bool {
56        self.init_on_content_load
57    }
58
59    /// This contains the url from the widget state event.
60    /// In this url placeholders can be used to pass information from the client
61    /// to the widget. Possible values are: `$matrix_widget_id`,
62    /// `$matrix_display_name`, etc.
63    ///
64    /// # Examples
65    ///
66    /// `http://widget.domain?username=$userId` will become
67    /// `http://widget.domain?username=@user_matrix_id:server.domain`.
68    pub fn raw_url(&self) -> &Url {
69        &self.raw_url
70    }
71
72    /// Get the base url of the widget. Used as the target for PostMessages. In
73    /// case the widget is in a webview and not an IFrame. It contains the
74    /// schema and the authority e.g. `https://my.domain.org`. A postmessage would
75    /// be sent using: `postMessage(myMessage, widget_base_url)`.
76    pub fn base_url(&self) -> Option<Url> {
77        base_url(&self.raw_url)
78    }
79
80    /// Create the actual [`Url`] that can be used to setup the WebView or
81    /// IFrame that contains the widget.
82    ///
83    /// # Arguments
84    ///
85    /// * `room` - A Matrix room which is used to query the logged in username
86    /// * `props` - Properties from the client that can be used by a widget to
87    ///   adapt to the client. e.g. language, font-scale...
88    //
89    // TODO: add `From<WidgetStateEvent>`, so that `WidgetSettings` can be built
90    // by using the room state.
91    pub async fn generate_webview_url(
92        &self,
93        room: &Room,
94        props: ClientProperties,
95    ) -> Result<Url, url::ParseError> {
96        self._generate_webview_url(
97            room.client().account().fetch_user_profile().await.unwrap_or_default(),
98            room.own_user_id(),
99            room.room_id(),
100            room.client().device_id().unwrap_or("UNKNOWN".into()),
101            room.client().homeserver(),
102            props,
103        )
104    }
105
106    // Using a separate function (without Room as a param) for tests.
107    fn _generate_webview_url(
108        &self,
109        profile: get_profile::v3::Response,
110        user_id: &UserId,
111        room_id: &RoomId,
112        device_id: &DeviceId,
113        homeserver_url: Url,
114        client_props: ClientProperties,
115    ) -> Result<Url, url::ParseError> {
116        let avatar_url = profile
117            .get_static::<AvatarUrl>()
118            .ok()
119            .flatten()
120            .map(|url| url.to_string())
121            .unwrap_or_default();
122
123        let query_props = url_params::QueryProperties {
124            widget_id: self.widget_id.clone(),
125            avatar_url,
126            display_name: profile.get_static::<DisplayName>().ok().flatten().unwrap_or_default(),
127            user_id: user_id.into(),
128            room_id: room_id.into(),
129            language: client_props.language.to_string(),
130            client_theme: client_props.theme,
131            client_id: client_props.client_id,
132            device_id: device_id.into(),
133            homeserver_url: homeserver_url.into(),
134        };
135        let mut generated_url = self.raw_url.clone();
136        url_params::replace_properties(&mut generated_url, query_props);
137
138        Ok(generated_url)
139    }
140}
141
142/// The set of settings and properties for the widget based on the client
143/// configuration. Those values are used generate the widget url.
144#[derive(Debug)]
145pub struct ClientProperties {
146    /// The client_id provides the widget with the option to behave differently
147    /// for different clients. e.g org.example.ios.
148    client_id: String,
149    /// The language the client is set to e.g. en-us.
150    language: LanguageTag,
151    /// A string describing the theme (dark, light) or org.example.dark.
152    theme: String,
153}
154
155impl ClientProperties {
156    /// Creates client properties. If a malformatted language tag is provided,
157    /// the default one (en-US) will be used.
158    ///
159    /// # Arguments
160    /// * `client_id` - client identifier. This allows widgets to adapt to
161    ///   specific clients (e.g. `io.element.web`).
162    /// * `language` - language that is used in the client (default: `en-US`).
163    /// * `theme` - theme (dark, light) or org.example.dark (default: `light`).
164    pub fn new(client_id: &str, language: Option<LanguageTag>, theme: Option<String>) -> Self {
165        // It is safe to unwrap "en-us".
166        let default_language = LanguageTag::parse("en-us").unwrap();
167        let default_theme = "light".to_owned();
168        Self {
169            language: language.unwrap_or(default_language),
170            client_id: client_id.to_owned(),
171            theme: theme.unwrap_or(default_theme),
172        }
173    }
174}
175
176fn base_url(url: &Url) -> Option<Url> {
177    let mut url = url.clone();
178    url.path_segments_mut().ok()?.clear();
179    url.set_query(None);
180    url.set_fragment(None);
181    Some(url)
182}