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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! Collection of methods related to the Matrix specification.

use std::{fmt, str::FromStr};

use matrix_sdk::{
    config::RequestConfig,
    deserialized_responses::RawAnySyncOrStrippedTimelineEvent,
    encryption::{BackupDownloadStrategy, EncryptionSettings},
    Client, ClientBuildError,
};
use matrix_sdk_ui::timeline::TimelineItemContent;
use ruma::{
    events::{
        room::{member::MembershipState, message::MessageType},
        AnyMessageLikeEventContent, AnyStrippedStateEvent, AnySyncMessageLikeEvent,
        AnySyncTimelineEvent,
    },
    html::{
        matrix::{AnchorUri, MatrixElement},
        Children, Html, HtmlSanitizerMode, NodeRef, RemoveReplyFallback, StrTendril,
    },
    matrix_uri::MatrixId,
    serde::Raw,
    EventId, IdParseError, MatrixToUri, MatrixUri, MatrixUriError, OwnedEventId, OwnedRoomAliasId,
    OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomOrAliasId, UserId,
};
use thiserror::Error;

use crate::{
    components::Pill,
    gettext_f,
    prelude::*,
    secret::StoredSession,
    session::model::{RemoteRoom, Room},
    spawn_tokio,
};

/// The result of a password validation.
#[derive(Debug, Default, Clone, Copy)]
pub struct PasswordValidity {
    /// Whether the password includes at least one lowercase letter.
    pub has_lowercase: bool,
    /// Whether the password includes at least one uppercase letter.
    pub has_uppercase: bool,
    /// Whether the password includes at least one number.
    pub has_number: bool,
    /// Whether the password includes at least one symbol.
    pub has_symbol: bool,
    /// Whether the password is at least 8 characters long.
    pub has_length: bool,
    /// The percentage of checks passed for the password, between 0 and 100.
    ///
    /// If progress is 100, the password is valid.
    pub progress: u32,
}

impl PasswordValidity {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Validate a password according to the Matrix specification.
///
/// A password should include a lower-case letter, an upper-case letter, a
/// number and a symbol and be at a minimum 8 characters in length.
///
/// See: <https://spec.matrix.org/v1.1/client-server-api/#notes-on-password-management>
pub fn validate_password(password: &str) -> PasswordValidity {
    let mut validity = PasswordValidity::new();

    for char in password.chars() {
        if char.is_numeric() {
            validity.has_number = true;
        } else if char.is_lowercase() {
            validity.has_lowercase = true;
        } else if char.is_uppercase() {
            validity.has_uppercase = true;
        } else {
            validity.has_symbol = true;
        }
    }

    validity.has_length = password.len() >= 8;

    let mut passed = 0;
    if validity.has_number {
        passed += 1;
    }
    if validity.has_lowercase {
        passed += 1;
    }
    if validity.has_uppercase {
        passed += 1;
    }
    if validity.has_symbol {
        passed += 1;
    }
    if validity.has_length {
        passed += 1;
    }
    validity.progress = passed * 100 / 5;

    validity
}

/// An deserialized event received in a sync response.
#[derive(Debug, Clone)]
pub enum AnySyncOrStrippedTimelineEvent {
    /// An event from a joined or left room.
    Sync(AnySyncTimelineEvent),
    /// An event from an invited room.
    Stripped(AnyStrippedStateEvent),
}

impl AnySyncOrStrippedTimelineEvent {
    /// Deserialize the given raw event.
    pub fn from_raw(raw: &RawAnySyncOrStrippedTimelineEvent) -> Result<Self, serde_json::Error> {
        let ev = match raw {
            RawAnySyncOrStrippedTimelineEvent::Sync(ev) => Self::Sync(ev.deserialize()?),
            RawAnySyncOrStrippedTimelineEvent::Stripped(ev) => Self::Stripped(ev.deserialize()?),
        };

        Ok(ev)
    }

    /// The sender of the event.
    pub fn sender(&self) -> &UserId {
        match self {
            AnySyncOrStrippedTimelineEvent::Sync(ev) => ev.sender(),
            AnySyncOrStrippedTimelineEvent::Stripped(ev) => ev.sender(),
        }
    }

    /// The ID of the event, if it's not a stripped state event.
    pub fn event_id(&self) -> Option<&EventId> {
        match self {
            AnySyncOrStrippedTimelineEvent::Sync(ev) => Some(ev.event_id()),
            AnySyncOrStrippedTimelineEvent::Stripped(_) => None,
        }
    }
}

/// Extract the body from the given event.
///
/// If the event does not have a body but is supported, this will return a
/// localized string.
///
/// Returns `None` if the event type is not supported.
pub fn get_event_body(
    event: &AnySyncOrStrippedTimelineEvent,
    sender_name: &str,
    own_user: &UserId,
    show_sender: bool,
) -> Option<String> {
    match event {
        AnySyncOrStrippedTimelineEvent::Sync(AnySyncTimelineEvent::MessageLike(message)) => {
            get_message_event_body(message, sender_name, show_sender)
        }
        AnySyncOrStrippedTimelineEvent::Stripped(state) => {
            get_stripped_state_event_body(state, sender_name, own_user)
        }
        _ => None,
    }
}

/// Extract the body from the given message event.
///
/// If it's a media message, this will return a localized body.
///
/// Returns `None` if the message type is not supported.
pub fn get_message_event_body(
    event: &AnySyncMessageLikeEvent,
    sender_name: &str,
    show_sender: bool,
) -> Option<String> {
    match event.original_content()? {
        AnyMessageLikeEventContent::RoomMessage(mut message) => {
            message.sanitize(HtmlSanitizerMode::Compat, RemoveReplyFallback::Yes);

            let body = match message.msgtype {
                MessageType::Audio(_) => {
                    gettext_f("{user} sent an audio file.", &[("user", sender_name)])
                }
                MessageType::Emote(content) => format!("{sender_name} {}", content.body),
                MessageType::File(_) => gettext_f("{user} sent a file.", &[("user", sender_name)]),
                MessageType::Image(_) => {
                    gettext_f("{user} sent an image.", &[("user", sender_name)])
                }
                MessageType::Location(_) => {
                    gettext_f("{user} sent their location.", &[("user", sender_name)])
                }
                MessageType::Notice(content) => {
                    text_event_body(content.body, sender_name, show_sender)
                }
                MessageType::ServerNotice(content) => {
                    text_event_body(content.body, sender_name, show_sender)
                }
                MessageType::Text(content) => {
                    text_event_body(content.body, sender_name, show_sender)
                }
                MessageType::Video(_) => {
                    gettext_f("{user} sent a video.", &[("user", sender_name)])
                }
                _ => return None,
            };
            Some(body)
        }
        AnyMessageLikeEventContent::Sticker(_) => Some(gettext_f(
            "{user} sent a sticker.",
            &[("user", sender_name)],
        )),
        _ => None,
    }
}

fn text_event_body(message: String, sender_name: &str, show_sender: bool) -> String {
    if show_sender {
        gettext_f(
            "{user}: {message}",
            &[("user", sender_name), ("message", &message)],
        )
    } else {
        message
    }
}

/// Extract the body from the given state event.
///
/// This will return a localized body.
///
/// Returns `None` if the state event type is not supported.
pub fn get_stripped_state_event_body(
    event: &AnyStrippedStateEvent,
    sender_name: &str,
    own_user: &UserId,
) -> Option<String> {
    if let AnyStrippedStateEvent::RoomMember(member_event) = event {
        if member_event.content.membership == MembershipState::Invite
            && member_event.state_key == own_user
        {
            // Translators: Do NOT translate the content between '{' and '}', this is a
            // variable name.
            return Some(gettext_f("{user} invited you", &[("user", sender_name)]));
        }
    }

    None
}

/// All errors that can occur when setting up the Matrix client.
#[derive(Error, Debug)]
pub enum ClientSetupError {
    #[error(transparent)]
    Client(#[from] ClientBuildError),
    #[error(transparent)]
    Sdk(#[from] matrix_sdk::Error),
}

impl UserFacingError for ClientSetupError {
    fn to_user_facing(&self) -> String {
        match self {
            ClientSetupError::Client(err) => err.to_user_facing(),
            ClientSetupError::Sdk(err) => err.to_user_facing(),
        }
    }
}

/// Create a [`Client`] with the given stored session.
pub async fn client_with_stored_session(
    session: StoredSession,
) -> Result<Client, ClientSetupError> {
    let (homeserver, path, passphrase, data) = session.into_parts();

    let encryption_settings = EncryptionSettings {
        auto_enable_cross_signing: true,
        backup_download_strategy: BackupDownloadStrategy::AfterDecryptionFailure,
        auto_enable_backups: true,
    };

    let client = Client::builder()
        .homeserver_url(homeserver)
        .sqlite_store(path, Some(&passphrase))
        // force_auth option to solve an issue with some servers configuration to require
        // auth for profiles:
        // https://gitlab.gnome.org/World/fractal/-/issues/934
        .request_config(RequestConfig::new().retry_limit(2).force_auth())
        .with_encryption_settings(encryption_settings)
        .build()
        .await?;

    client.restore_session(data).await?;

    Ok(client)
}

/// Fetch the content of the media message in the given message.
///
/// Compatible messages:
///
/// - File.
/// - Image.
/// - Video.
/// - Audio.
///
/// Returns `Ok((filename, binary_content))` on success.
///
/// Returns `Err` if an error occurred while fetching the content. Panics on
/// an incompatible event.
pub async fn get_media_content(
    client: Client,
    message: MessageType,
) -> Result<(String, Vec<u8>), matrix_sdk::Error> {
    let media = client.media();

    match message {
        MessageType::File(content) => {
            let filename = crate::matrix_filename!(content, None);
            let handle = spawn_tokio!(async move { media.get_file(&content, true).await });
            let data = handle.await.unwrap()?.unwrap();
            Ok((filename, data))
        }
        MessageType::Image(content) => {
            let filename = crate::matrix_filename!(content, Some(mime::IMAGE));
            let handle = spawn_tokio!(async move { media.get_file(&content, true).await });
            let data = handle.await.unwrap()?.unwrap();
            Ok((filename, data))
        }
        MessageType::Video(content) => {
            let filename = crate::matrix_filename!(content, Some(mime::VIDEO));
            let handle = spawn_tokio!(async move { media.get_file(&content, true).await });
            let data = handle.await.unwrap()?.unwrap();
            Ok((filename, data))
        }
        MessageType::Audio(content) => {
            let filename = crate::matrix_filename!(content, Some(mime::AUDIO));
            let handle = spawn_tokio!(async move { media.get_file(&content, true).await });
            let data = handle.await.unwrap()?.unwrap();
            Ok((filename, data))
        }
        _ => {
            panic!("Trying to get the media content of a message of incompatible type");
        }
    }
}

/// The filename of the given media message.
///
/// Uses the given mimetype to generate a fallback filename if none exists.
#[macro_export]
macro_rules! matrix_filename {
    ($message:ident, $mime_fallback:expr) => {{
        let mut filename = match &$message.filename {
            Some(filename) if *filename != $message.body => filename.clone(),
            _ => $message.body.clone(),
        };

        if filename.is_empty() {
            let mimetype = $message
                .info
                .as_ref()
                .and_then(|info| info.mimetype.as_deref());

            filename = $crate::utils::media::filename_for_mime(mimetype, $mime_fallback);
        }

        filename
    }};
}

/// The caption of the given media message, if any.
#[macro_export]
macro_rules! matrix_caption {
    ($message:ident) => {{
        $message
            .filename
            .as_deref()
            .filter(|filename| *filename != $message.body)
            .map(|_| ($message.body.clone(), $message.formatted.clone()))
    }};
}

/// Find mentions in the given HTML string.
///
/// Returns a list of `(pill, mention_content)` tuples.
pub fn find_html_mentions(html: &str, room: &Room) -> Vec<(Pill, StrTendril)> {
    let mut mentions = Vec::new();
    let html = Html::parse(html);

    append_children_mentions(&mut mentions, html.children(), room);

    mentions
}

/// Find mentions in the given child nodes and append them to the given list.
fn append_children_mentions(
    mentions: &mut Vec<(Pill, StrTendril)>,
    children: Children<'_>,
    room: &Room,
) {
    for node in children {
        if let Some(mention) = node_as_mention(node, room) {
            mentions.push(mention);
            continue;
        }

        append_children_mentions(mentions, node.children(), room);
    }
}

/// Try to convert the given node to a mention.
///
/// This does not recurse into children.
fn node_as_mention(node: NodeRef<'_>, room: &Room) -> Option<(Pill, StrTendril)> {
    // Mentions are links.
    let MatrixElement::A(anchor) = node.as_element()?.to_matrix().element else {
        return None;
    };

    // Mentions contain Matrix URIs.
    let id = MatrixIdUri::try_from(anchor.href?).ok()?;

    // Mentions contain one text child node.
    let child = node.children().next()?;

    if child.next_sibling().is_some() {
        return None;
    }

    let content = child.as_text()?.clone();
    let pill = id.into_pill(room)?;

    Some((pill, content))
}

/// The textual representation of a room mention.
pub const AT_ROOM: &str = "@room";

/// Find `@room` in the given string.
///
/// This uses the same algorithm as the pushrules from the Matrix spec to detect
/// it in the `body`.
///
/// Returns the position of the first match.
pub fn find_at_room(s: &str) -> Option<usize> {
    for (pos, _) in s.match_indices(AT_ROOM) {
        let is_at_word_start = pos == 0 || s[..pos].ends_with(char_is_ascii_word_boundary);
        if !is_at_word_start {
            continue;
        }

        let pos_after_match = pos + 5;
        let is_at_word_end = pos_after_match == s.len()
            || s[pos_after_match..].starts_with(char_is_ascii_word_boundary);
        if is_at_word_end {
            return Some(pos);
        }
    }

    None
}

/// Whether the given `char` is a word boundary, according to the Matrix spec.
///
/// A word boundary is any character not in the sets `[A-Z]`, `[a-z]`, `[0-9]`
/// or `_`.
fn char_is_ascii_word_boundary(c: char) -> bool {
    !c.is_ascii_alphanumeric() && c != '_'
}

/// Compare two raw JSON sources.
pub fn raw_eq<T, U>(lhs: Option<&Raw<T>>, rhs: Option<&Raw<U>>) -> bool {
    let Some(lhs) = lhs else {
        // They are equal only if both are `None`.
        return rhs.is_none();
    };
    let Some(rhs) = rhs else {
        // They cannot be equal.
        return false;
    };

    lhs.json().get() == rhs.json().get()
}

/// A unique identifier for a room.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MatrixRoomId {
    /// A room ID.
    Id(OwnedRoomId),
    /// A room alias.
    Alias(OwnedRoomAliasId),
}

impl MatrixRoomId {
    /// The room ID, if this is an ID.
    pub fn as_id(&self) -> Option<&OwnedRoomId> {
        match self {
            Self::Id(room_id) => Some(room_id),
            Self::Alias(_) => None,
        }
    }

    /// The room alias, if this is an alias.
    pub fn as_alias(&self) -> Option<&OwnedRoomAliasId> {
        match self {
            Self::Id(_) => None,
            Self::Alias(alias) => Some(alias),
        }
    }
}

impl From<OwnedRoomId> for MatrixRoomId {
    fn from(value: OwnedRoomId) -> Self {
        Self::Id(value)
    }
}

impl From<OwnedRoomAliasId> for MatrixRoomId {
    fn from(value: OwnedRoomAliasId) -> Self {
        Self::Alias(value)
    }
}

impl From<OwnedRoomOrAliasId> for MatrixRoomId {
    fn from(value: OwnedRoomOrAliasId) -> Self {
        if value.is_room_id() {
            Self::Id(
                value
                    .try_into()
                    .expect("Conversion into known variant should not fail"),
            )
        } else {
            Self::Alias(
                value
                    .try_into()
                    .expect("Conversion into known variant should not fail"),
            )
        }
    }
}

impl From<MatrixRoomId> for OwnedRoomOrAliasId {
    fn from(value: MatrixRoomId) -> Self {
        match value {
            MatrixRoomId::Id(id) => id.into(),
            MatrixRoomId::Alias(alias) => alias.into(),
        }
    }
}

impl fmt::Display for MatrixRoomId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Id(id) => id.fmt(f),
            Self::Alias(alias) => alias.fmt(f),
        }
    }
}

/// A URI for a Matrix ID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MatrixIdUri {
    /// A room.
    Room(MatrixRoomIdUri),
    /// A user.
    User(OwnedUserId),
    /// An event.
    Event(MatrixEventIdUri),
}

impl MatrixIdUri {
    /// Constructs a `MatrixIdUri` from the given ID and servers list.
    fn try_from_parts(id: MatrixId, via: &[OwnedServerName]) -> Result<Self, ()> {
        let uri = match id {
            MatrixId::Room(room_id) => Self::Room(MatrixRoomIdUri {
                id: room_id.into(),
                via: via.to_owned(),
            }),
            MatrixId::RoomAlias(room_alias) => Self::Room(MatrixRoomIdUri {
                id: room_alias.into(),
                via: via.to_owned(),
            }),
            MatrixId::User(user_id) => Self::User(user_id),
            MatrixId::Event(room_id, event_id) => Self::Event(MatrixEventIdUri {
                event_id,
                room_uri: MatrixRoomIdUri {
                    id: room_id.into(),
                    via: via.to_owned(),
                },
            }),
            _ => return Err(()),
        };

        Ok(uri)
    }

    /// Try parsing a `&str` into a `MatrixIdUri`.
    pub fn parse(s: &str) -> Result<Self, MatrixIdUriParseError> {
        if let Ok(uri) = MatrixToUri::parse(s) {
            return uri.try_into();
        }

        MatrixUri::parse(s)?.try_into()
    }

    /// Try to construct a [`Pill`] from this ID in the given room.
    pub fn into_pill(self, room: &Room) -> Option<Pill> {
        match self {
            Self::Room(room_uri) => {
                let session = room.session()?;
                session
                    .room_list()
                    .get_by_identifier(&room_uri.id)
                    .as_ref()
                    .map(Pill::new)
                    .or_else(|| Some(Pill::new(&RemoteRoom::new(&session, room_uri))))
            }
            MatrixIdUri::User(user_id) => {
                // We should have a strong reference to the list wherever we show a user pill,
                // so we can use `get_or_create_members()`.
                let user = room.get_or_create_members().get_or_create(user_id);
                Some(Pill::new(&user))
            }
            _ => None,
        }
    }
}

impl TryFrom<&MatrixUri> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(uri: &MatrixUri) -> Result<Self, Self::Error> {
        // We ignore the action, because we always offer to join a room or DM a user.
        Self::try_from_parts(uri.id().clone(), uri.via())
            .map_err(|_| MatrixIdUriParseError::UnsupportedId(uri.id().clone()))
    }
}

impl TryFrom<MatrixUri> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(uri: MatrixUri) -> Result<Self, Self::Error> {
        Self::try_from(&uri)
    }
}

impl TryFrom<&MatrixToUri> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(uri: &MatrixToUri) -> Result<Self, Self::Error> {
        Self::try_from_parts(uri.id().clone(), uri.via())
            .map_err(|_| MatrixIdUriParseError::UnsupportedId(uri.id().clone()))
    }
}

impl TryFrom<MatrixToUri> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(uri: MatrixToUri) -> Result<Self, Self::Error> {
        Self::try_from(&uri)
    }
}

impl FromStr for MatrixIdUri {
    type Err = MatrixIdUriParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl TryFrom<&str> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::parse(s)
    }
}

impl TryFrom<&AnchorUri> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(value: &AnchorUri) -> Result<Self, Self::Error> {
        match value {
            AnchorUri::Matrix(uri) => MatrixIdUri::try_from(uri),
            AnchorUri::MatrixTo(uri) => MatrixIdUri::try_from(uri),
            // The same error that should be returned by `parse()` when parsing a non-Matrix URI.
            _ => Err(IdParseError::InvalidMatrixUri(MatrixUriError::WrongScheme).into()),
        }
    }
}

impl TryFrom<AnchorUri> for MatrixIdUri {
    type Error = MatrixIdUriParseError;

    fn try_from(value: AnchorUri) -> Result<Self, Self::Error> {
        Self::try_from(&value)
    }
}

/// A URI for a Matrix room ID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatrixRoomIdUri {
    /// The room ID.
    pub id: MatrixRoomId,
    /// Matrix servers usable to route a `RoomId`.
    pub via: Vec<OwnedServerName>,
}

impl MatrixRoomIdUri {
    /// Try parsing a `&str` into a `MatrixRoomIdUri`.
    pub fn parse(s: &str) -> Option<MatrixRoomIdUri> {
        MatrixIdUri::parse(s)
            .ok()
            .and_then(|uri| match uri {
                MatrixIdUri::Room(room_uri) => Some(room_uri),
                _ => None,
            })
            .or_else(|| {
                RoomOrAliasId::parse(s)
                    .ok()
                    .map(MatrixRoomId::from)
                    .map(Into::into)
            })
    }
}

impl From<MatrixRoomId> for MatrixRoomIdUri {
    fn from(id: MatrixRoomId) -> Self {
        Self {
            id,
            via: Vec::new(),
        }
    }
}

impl From<OwnedRoomId> for MatrixRoomIdUri {
    fn from(value: OwnedRoomId) -> Self {
        MatrixRoomId::from(value).into()
    }
}

impl From<OwnedRoomAliasId> for MatrixRoomIdUri {
    fn from(value: OwnedRoomAliasId) -> Self {
        MatrixRoomId::from(value).into()
    }
}

impl From<&MatrixRoomIdUri> for MatrixUri {
    fn from(value: &MatrixRoomIdUri) -> Self {
        match &value.id {
            MatrixRoomId::Id(room_id) => room_id.matrix_uri_via(value.via.clone(), false),
            MatrixRoomId::Alias(alias) => alias.matrix_uri(false),
        }
    }
}

/// A URI for a Matrix event ID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatrixEventIdUri {
    /// The event ID.
    pub event_id: OwnedEventId,
    /// The event's room ID URI.
    pub room_uri: MatrixRoomIdUri,
}

/// Errors encountered when parsing a Matrix ID URI.
#[derive(Debug, Clone, Error)]
pub enum MatrixIdUriParseError {
    /// Not a valid Matrix URI.
    #[error(transparent)]
    InvalidUri(#[from] IdParseError),
    /// Unsupported Matrix ID.
    #[error("unsupported Matrix ID: {0:?}")]
    UnsupportedId(MatrixId),
}

/// Helper trait for [`TimelineItemContent`].
pub trait TimelineItemContentExt {
    /// Whether this event might contain an `@room` mention.
    ///
    /// This means that either it doesn't have intentional mentions, or it has
    /// intentional mentions and `room` is set to `true`.
    fn can_contain_at_room(&self) -> bool;
}

impl TimelineItemContentExt for TimelineItemContent {
    fn can_contain_at_room(&self) -> bool {
        match self {
            TimelineItemContent::Message(msg) => {
                let Some(mentions) = msg.mentions() else {
                    return true;
                };

                mentions.room
            }
            _ => false,
        }
    }
}