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