1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Utility types and traits.

#[cfg(feature = "e2e-encryption")]
use std::sync::{Arc, RwLock};

#[cfg(feature = "e2e-encryption")]
use futures_core::Stream;
#[cfg(feature = "e2e-encryption")]
use futures_util::StreamExt;
#[cfg(feature = "markdown")]
use ruma::events::room::message::FormattedBody;
use ruma::{
    events::{AnyMessageLikeEventContent, AnyStateEventContent},
    serde::Raw,
    RoomAliasId,
};
use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue};
#[cfg(feature = "e2e-encryption")]
use tokio::sync::broadcast;
#[cfg(feature = "e2e-encryption")]
use tokio_stream::wrappers::{errors::BroadcastStreamRecvError, BroadcastStream};

#[cfg(doc)]
use crate::Room;

/// An observable with channel semantics.
///
/// Channel semantics means that each update to the shared mutable value will be
/// sent out to subscribers. That is, intermediate updates to the value will not
/// be skipped like they would be in an observable without channel semantics.
#[cfg(feature = "e2e-encryption")]
#[derive(Clone, Debug)]
pub(crate) struct ChannelObservable<T: Clone + Send> {
    value: Arc<RwLock<T>>,
    channel: broadcast::Sender<T>,
}

#[cfg(feature = "e2e-encryption")]
impl<T: Default + Clone + Send + 'static> Default for ChannelObservable<T> {
    fn default() -> Self {
        let value = Default::default();
        Self::new(value)
    }
}

#[cfg(feature = "e2e-encryption")]
impl<T: 'static + Send + Clone> ChannelObservable<T> {
    /// Create a new [`ChannelObservable`] with the given value for the
    /// underlying data.
    pub(crate) fn new(value: T) -> Self {
        let channel = broadcast::Sender::new(100);
        Self { value: RwLock::new(value).into(), channel }
    }

    /// Subscribe to updates to the observable value.
    ///
    /// The current value will always be emitted as the first item in the
    /// stream.
    pub(crate) fn subscribe(&self) -> impl Stream<Item = Result<T, BroadcastStreamRecvError>> {
        let current_value = self.value.read().unwrap().to_owned();
        let initial_stream = tokio_stream::once(Ok(current_value));
        let broadcast_stream = BroadcastStream::new(self.channel.subscribe());

        initial_stream.chain(broadcast_stream)
    }

    /// Set the underlying data to the new value.
    pub(crate) fn set(&self, new_value: T) -> T {
        let old_value = {
            let mut guard = self.value.write().unwrap();
            std::mem::replace(&mut (*guard), new_value.clone())
        };

        // We're ignoring the error case where no receivers exist.
        let _ = self.channel.send(new_value);

        old_value
    }

    /// Get the current value of the underlying data.
    pub(crate) fn get(&self) -> T {
        self.value.read().unwrap().to_owned()
    }
}

/// The set of types that can be used with [`Room::send_raw`].
pub trait IntoRawMessageLikeEventContent {
    #[doc(hidden)]
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent>;
}

impl IntoRawMessageLikeEventContent for Raw<AnyMessageLikeEventContent> {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        self
    }
}

impl IntoRawMessageLikeEventContent for &Raw<AnyMessageLikeEventContent> {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        self.clone()
    }
}

impl IntoRawMessageLikeEventContent for JsonValue {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        (&self).into_raw_message_like_event_content()
    }
}

impl IntoRawMessageLikeEventContent for &JsonValue {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        Raw::new(self).expect("serde_json::Value never fails to serialize").cast()
    }
}

impl IntoRawMessageLikeEventContent for Box<RawJsonValue> {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        Raw::from_json(self)
    }
}

impl IntoRawMessageLikeEventContent for &RawJsonValue {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        self.to_owned().into_raw_message_like_event_content()
    }
}

impl IntoRawMessageLikeEventContent for &Box<RawJsonValue> {
    fn into_raw_message_like_event_content(self) -> Raw<AnyMessageLikeEventContent> {
        self.clone().into_raw_message_like_event_content()
    }
}

/// The set of types that can be used with [`Room::send_state_event_raw`].
pub trait IntoRawStateEventContent {
    #[doc(hidden)]
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent>;
}

impl IntoRawStateEventContent for Raw<AnyStateEventContent> {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        self
    }
}

impl IntoRawStateEventContent for &Raw<AnyStateEventContent> {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        self.clone()
    }
}

impl IntoRawStateEventContent for JsonValue {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        (&self).into_raw_state_event_content()
    }
}

impl IntoRawStateEventContent for &JsonValue {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        Raw::new(self).expect("serde_json::Value never fails to serialize").cast()
    }
}

impl IntoRawStateEventContent for Box<RawJsonValue> {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        Raw::from_json(self)
    }
}

impl IntoRawStateEventContent for &RawJsonValue {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        self.to_owned().into_raw_state_event_content()
    }
}

impl IntoRawStateEventContent for &Box<RawJsonValue> {
    fn into_raw_state_event_content(self) -> Raw<AnyStateEventContent> {
        self.clone().into_raw_state_event_content()
    }
}

const INVALID_ROOM_ALIAS_NAME_CHARS: &str = "#,:{}\\";

/// Verifies the passed `String` matches the expected room alias format:
///
/// This means it's lowercase, with no whitespace chars, has a single leading
/// `#` char and a single `:` separator between the local and domain parts, and
/// the local part only contains characters that can't be percent encoded.
pub fn is_room_alias_format_valid(alias: String) -> bool {
    let alias_parts: Vec<&str> = alias.split(':').collect();
    if alias_parts.len() != 2 {
        return false;
    }

    let local_part = alias_parts[0];
    let has_valid_format = local_part.chars().skip(1).all(|c| {
        c.is_ascii()
            && !c.is_whitespace()
            && !c.is_control()
            && !INVALID_ROOM_ALIAS_NAME_CHARS.contains(c)
    });

    let is_lowercase = alias.to_lowercase() == alias;

    // Checks both the local part and the domain part
    has_valid_format && is_lowercase && RoomAliasId::parse(alias).is_ok()
}

/// Given a pair of optional `body` and `formatted_body` parameters,
/// returns a formatted body.
///
/// Return the formatted body if available, or interpret the `body` parameter as
/// markdown, if provided.
#[cfg(feature = "markdown")]
pub fn formatted_body_from(
    body: Option<&str>,
    formatted_body: Option<FormattedBody>,
) -> Option<FormattedBody> {
    if formatted_body.is_some() {
        formatted_body
    } else {
        body.and_then(FormattedBody::markdown)
    }
}

#[cfg(test)]
mod test {
    #[cfg(feature = "markdown")]
    use assert_matches2::{assert_let, assert_matches};
    #[cfg(feature = "markdown")]
    use ruma::events::room::message::FormattedBody;

    #[cfg(feature = "markdown")]
    use crate::utils::formatted_body_from;
    use crate::utils::is_room_alias_format_valid;

    #[cfg(feature = "e2e-encryption")]
    #[test]
    fn test_channel_observable_get_set() {
        let observable = super::ChannelObservable::new(0);

        assert_eq!(observable.get(), 0);
        assert_eq!(observable.set(1), 0);
        assert_eq!(observable.set(10), 1);
        assert_eq!(observable.get(), 10);
    }

    #[test]
    fn test_is_room_alias_format_valid_when_it_has_no_leading_hash_char_is_not_valid() {
        assert!(!is_room_alias_format_valid("alias:domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_it_has_several_colon_chars_is_not_valid() {
        assert!(!is_room_alias_format_valid("#alias:something:domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_it_has_no_colon_chars_is_not_valid() {
        assert!(!is_room_alias_format_valid("#alias.domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_server_part_is_not_valid() {
        assert!(!is_room_alias_format_valid("#alias:".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_name_part_has_whitespace_is_not_valid() {
        assert!(!is_room_alias_format_valid("#alias with whitespace:domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_name_part_has_control_char_is_not_valid() {
        assert!(!is_room_alias_format_valid("#alias\u{0009}:domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_name_part_has_invalid_char_is_not_valid() {
        assert!(!is_room_alias_format_valid("#a#lias,{t\\est}:domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_name_part_is_not_lowercase_is_not_valid() {
        assert!(!is_room_alias_format_valid("#Alias:domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_server_part_is_not_lowercase_is_not_valid() {
        assert!(!is_room_alias_format_valid("#alias:Domain.org".to_owned()))
    }

    #[test]
    fn test_is_room_alias_format_valid_when_has_valid_format() {
        assert!(is_room_alias_format_valid("#alias.test:domain.org".to_owned()))
    }

    #[test]
    #[cfg(feature = "markdown")]
    fn test_formatted_body_from_nothing_returns_none() {
        assert_matches!(formatted_body_from(None, None), None);
    }

    #[test]
    #[cfg(feature = "markdown")]
    fn test_formatted_body_from_only_formatted_body_returns_the_formatted_body() {
        let formatted_body = FormattedBody::html(r"<h1>Hello!</h1>");

        assert_let!(
            Some(result_formatted_body) = formatted_body_from(None, Some(formatted_body.clone()))
        );

        assert_eq!(formatted_body.body, result_formatted_body.body);
        assert_eq!(result_formatted_body.format, result_formatted_body.format);
    }

    #[test]
    #[cfg(feature = "markdown")]
    fn test_formatted_body_from_markdown_body_returns_a_processed_formatted_body() {
        let markdown_body = Some(r"# Parsed");

        assert_let!(Some(result_formatted_body) = formatted_body_from(markdown_body, None));

        let expected_formatted_body = FormattedBody::html("<h1>Parsed</h1>\n".to_owned());
        assert_eq!(expected_formatted_body.body, result_formatted_body.body);
        assert_eq!(expected_formatted_body.format, result_formatted_body.format);
    }

    #[test]
    #[cfg(feature = "markdown")]
    fn test_formatted_body_from_body_and_formatted_body_returns_the_formatted_body() {
        let markdown_body = Some(r"# Markdown");
        let formatted_body = FormattedBody::html(r"<h1>HTML</h1>");

        assert_let!(
            Some(result_formatted_body) =
                formatted_body_from(markdown_body, Some(formatted_body.clone()))
        );

        assert_eq!(formatted_body.body, result_formatted_body.body);
        assert_eq!(formatted_body.format, result_formatted_body.format);
    }
}