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
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
//! Types for the *m.room.message* event.

use js_int::UInt;
use ruma_identifiers::{EventId, RoomId, UserId};
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{from_value, Map, Value};

use super::{EncryptedFile, ImageInfo, ThumbnailInfo};
use crate::{Event, EventType, FromRaw};

pub mod feedback;

/// A message sent to a room.
#[derive(Clone, Debug, PartialEq)]
pub struct MessageEvent {
    /// The event's content.
    pub content: MessageEventContent,

    /// The unique identifier for the event.
    pub event_id: EventId,

    /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
    /// event was sent.
    pub origin_server_ts: UInt,

    /// The unique identifier for the room associated with this event.
    pub room_id: Option<RoomId>,

    /// The unique identifier for the user who sent this event.
    pub sender: UserId,

    /// Additional key-value pairs not signed by the homeserver.
    pub unsigned: Map<String, Value>,
}

/// The payload for `MessageEvent`.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum MessageEventContent {
    /// An audio message.
    Audio(AudioMessageEventContent),

    /// An emote message.
    Emote(EmoteMessageEventContent),

    /// A file message.
    File(FileMessageEventContent),

    /// An image message.
    Image(ImageMessageEventContent),

    /// A location message.
    Location(LocationMessageEventContent),

    /// A notice message.
    Notice(NoticeMessageEventContent),

    /// A server notice message.
    ServerNotice(ServerNoticeMessageEventContent),

    /// A text message.
    Text(TextMessageEventContent),

    /// A video message.
    Video(VideoMessageEventContent),

    /// Additional variants may be added in the future and will not be considered breaking changes
    /// to ruma-events.
    #[doc(hidden)]
    __Nonexhaustive,
}

impl FromRaw for MessageEvent {
    type Raw = raw::MessageEvent;

    fn from_raw(raw: raw::MessageEvent) -> Self {
        Self {
            content: FromRaw::from_raw(raw.content),
            event_id: raw.event_id,
            origin_server_ts: raw.origin_server_ts,
            room_id: raw.room_id,
            sender: raw.sender,
            unsigned: raw.unsigned,
        }
    }
}

impl FromRaw for MessageEventContent {
    type Raw = raw::MessageEventContent;

    fn from_raw(raw: raw::MessageEventContent) -> Self {
        use raw::MessageEventContent::*;

        match raw {
            Audio(content) => MessageEventContent::Audio(content),
            Emote(content) => MessageEventContent::Emote(content),
            File(content) => MessageEventContent::File(content),
            Image(content) => MessageEventContent::Image(content),
            Location(content) => MessageEventContent::Location(content),
            Notice(content) => MessageEventContent::Notice(content),
            ServerNotice(content) => MessageEventContent::ServerNotice(content),
            Text(content) => MessageEventContent::Text(content),
            Video(content) => MessageEventContent::Video(content),
            __Nonexhaustive => {
                unreachable!("It should be impossible to obtain a __Nonexhaustive variant.")
            }
        }
    }
}

impl Serialize for MessageEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 5;

        if self.room_id.is_some() {
            len += 1;
        }

        if !self.unsigned.is_empty() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("MessageEvent", len)?;

        state.serialize_field("content", &self.content)?;
        state.serialize_field("event_id", &self.event_id)?;
        state.serialize_field("origin_server_ts", &self.origin_server_ts)?;

        if self.room_id.is_some() {
            state.serialize_field("room_id", &self.room_id)?;
        }

        state.serialize_field("sender", &self.sender)?;
        state.serialize_field("type", &self.event_type())?;

        if !self.unsigned.is_empty() {
            state.serialize_field("unsigned", &self.unsigned)?;
        }

        state.end()
    }
}

impl_room_event!(MessageEvent, MessageEventContent, EventType::RoomMessage);

impl Serialize for MessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::Error as _;

        match *self {
            MessageEventContent::Audio(ref content) => content.serialize(serializer),
            MessageEventContent::Emote(ref content) => content.serialize(serializer),
            MessageEventContent::File(ref content) => content.serialize(serializer),
            MessageEventContent::Image(ref content) => content.serialize(serializer),
            MessageEventContent::Location(ref content) => content.serialize(serializer),
            MessageEventContent::Notice(ref content) => content.serialize(serializer),
            MessageEventContent::ServerNotice(ref content) => content.serialize(serializer),
            MessageEventContent::Text(ref content) => content.serialize(serializer),
            MessageEventContent::Video(ref content) => content.serialize(serializer),
            MessageEventContent::__Nonexhaustive => Err(S::Error::custom(
                "Attempted to deserialize __Nonexhaustive variant.",
            )),
        }
    }
}

pub(crate) mod raw {
    use super::*;

    /// A message sent to a room.
    #[derive(Clone, Debug, Deserialize, PartialEq)]
    pub struct MessageEvent {
        /// The event's content.
        pub content: MessageEventContent,

        /// The unique identifier for the event.
        pub event_id: EventId,

        /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
        /// event was sent.
        pub origin_server_ts: UInt,

        /// The unique identifier for the room associated with this event.
        pub room_id: Option<RoomId>,

        /// The unique identifier for the user who sent this event.
        pub sender: UserId,

        /// Additional key-value pairs not signed by the homeserver.
        #[serde(default)]
        pub unsigned: Map<String, Value>,
    }

    /// The payload for `MessageEvent`.
    #[allow(clippy::large_enum_variant)]
    #[derive(Clone, Debug, PartialEq)]
    pub enum MessageEventContent {
        /// An audio message.
        Audio(AudioMessageEventContent),

        /// An emote message.
        Emote(EmoteMessageEventContent),

        /// A file message.
        File(FileMessageEventContent),

        /// An image message.
        Image(ImageMessageEventContent),

        /// A location message.
        Location(LocationMessageEventContent),

        /// A notice message.
        Notice(NoticeMessageEventContent),

        /// A server notice message.
        ServerNotice(ServerNoticeMessageEventContent),

        /// An text message.
        Text(TextMessageEventContent),

        /// A video message.
        Video(VideoMessageEventContent),

        /// Additional variants may be added in the future and will not be considered breaking changes
        /// to ruma-events.
        #[doc(hidden)]
        __Nonexhaustive,
    }

    impl<'de> Deserialize<'de> for MessageEventContent {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            use serde::de::Error as _;

            let value: Value = Deserialize::deserialize(deserializer)?;

            let message_type_value = match value.get("msgtype") {
                Some(value) => value.clone(),
                None => return Err(D::Error::missing_field("msgtype")),
            };

            let message_type = match from_value::<MessageType>(message_type_value) {
                Ok(message_type) => message_type,
                Err(error) => return Err(D::Error::custom(error.to_string())),
            };

            match message_type {
                MessageType::Audio => {
                    let content = match from_value::<AudioMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Audio(content))
                }
                MessageType::Emote => {
                    let content = match from_value::<EmoteMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Emote(content))
                }
                MessageType::File => {
                    let content = match from_value::<FileMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::File(content))
                }
                MessageType::Image => {
                    let content = match from_value::<ImageMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Image(content))
                }
                MessageType::Location => {
                    let content = match from_value::<LocationMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Location(content))
                }
                MessageType::Notice => {
                    let content = match from_value::<NoticeMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Notice(content))
                }
                MessageType::ServerNotice => {
                    let content = match from_value::<ServerNoticeMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::ServerNotice(content))
                }
                MessageType::Text => {
                    let content = match from_value::<TextMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Text(content))
                }
                MessageType::Video => {
                    let content = match from_value::<VideoMessageEventContent>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(MessageEventContent::Video(content))
                }
                MessageType::__Nonexhaustive => Err(D::Error::custom(
                    "Attempted to deserialize __Nonexhaustive variant.",
                )),
            }
        }
    }
}

/// The message type of message event, e.g. `m.image` or `m.text`.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum MessageType {
    /// An audio message.
    #[serde(rename = "m.audio")]
    Audio,

    /// An emote message.
    #[serde(rename = "m.emote")]
    Emote,

    /// A file message.
    #[serde(rename = "m.file")]
    File,

    /// An image message.
    #[serde(rename = "m.image")]
    Image,

    /// A location message.
    #[serde(rename = "m.location")]
    Location,

    /// A notice message.
    #[serde(rename = "m.notice")]
    Notice,

    /// A server notice.
    #[serde(rename = "m.server_notice")]
    ServerNotice,

    /// A text message.
    #[serde(rename = "m.text")]
    Text,

    /// A video message.
    #[serde(rename = "m.video")]
    Video,

    /// Additional variants may be added in the future and will not be considered breaking changes
    /// to ruma-events.
    #[doc(hidden)]
    #[serde(skip)]
    __Nonexhaustive,
}

/// The payload for an audio message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct AudioMessageEventContent {
    /// The textual representation of this message.
    pub body: String,

    /// Metadata for the audio clip referred to in `url`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<AudioInfo>,

    /// The URL to the audio clip. Required if the file is unencrypted. The URL (typically
    /// [MXC URI](https://matrix.org/docs/spec/client_server/r0.5.0#mxc-uri)) to the audio clip.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Required if the audio clip is encrypted. Information on the encrypted audio clip.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<EncryptedFile>,
}

/// Metadata about an audio clip.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct AudioInfo {
    /// The duration of the audio in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration: Option<UInt>,

    /// The mimetype of the audio, e.g. "audio/aac."
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mimetype: Option<String>,

    /// The size of the audio clip in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<UInt>,
}

/// The payload for an emote message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct EmoteMessageEventContent {
    /// The emote action to perform.
    pub body: String,

    /// The format used in the `formatted_body`. Currently only `org.matrix.custom.html` is
    /// supported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// The formatted version of the `body`. This is required if `format` is specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub formatted_body: Option<String>,
}

/// The payload for a file message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct FileMessageEventContent {
    /// A human-readable description of the file. This is recommended to be the filename of the
    /// original upload.
    pub body: String,

    /// The original filename of the uploaded file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,

    /// Metadata about the file referred to in `url`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<FileInfo>,

    /// The URL to the file. Required if the file is unencrypted. The URL (typically
    /// [MXC URI](https://matrix.org/docs/spec/client_server/r0.5.0#mxc-uri)) to the file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Required if file is encrypted. Information on the encrypted file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<EncryptedFile>,
}

/// Metadata about a file.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct FileInfo {
    /// The mimetype of the file, e.g. "application/msword."
    pub mimetype: Option<String>,

    /// The size of the file in bytes.
    pub size: Option<UInt>,

    /// Metadata about the image referred to in `thumbnail_url`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_info: Option<ThumbnailInfo>,

    /// The URL to the thumbnail of the file. Only present if the thumbnail is unencrypted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,

    /// Information on the encrypted thumbnail file. Only present if the thumbnail is encrypted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_file: Option<EncryptedFile>,
}

/// The payload for an image message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct ImageMessageEventContent {
    /// A textual representation of the image. This could be the alt text of the image, the filename
    /// of the image, or some kind of content description for accessibility e.g. "image attachment."
    pub body: String,

    /// Metadata about the image referred to in `url`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<ImageInfo>,

    /// The URL to the image.  Required if the file is unencrypted. The URL (typically
    /// [MXC URI](https://matrix.org/docs/spec/client_server/r0.5.0#mxc-uri)) to the image.
    pub url: Option<String>,

    /// Required if image is encrypted. Information on the encrypted image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<EncryptedFile>,
}

/// The payload for a location message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct LocationMessageEventContent {
    /// A description of the location e.g. "Big Ben, London, UK,"or some kind of content description
    /// for accessibility, e.g. "location attachment."
    pub body: String,

    /// A geo URI representing the location.
    pub geo_uri: String,

    /// Info about the location being represented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<LocationInfo>,
}

/// Thumbnail info associated with a location.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct LocationInfo {
    /// Metadata about the image referred to in `thumbnail_url` or `thumbnail_file`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_info: Option<ThumbnailInfo>,

    /// The URL to a thumbnail of the location being represented. Only present if the thumbnail is
    /// unencrypted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,

    /// Information on an encrypted thumbnail of the location being represented. Only present if the
    /// thumbnail is encrypted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_file: Option<EncryptedFile>,
}

/// The payload for a notice message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct NoticeMessageEventContent {
    /// The notice text to send.
    pub body: String,

    /// Information about related messages for
    /// [rich replies](https://matrix.org/docs/spec/client_server/r0.5.0#rich-replies).
    #[serde(rename = "m.relates_to")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relates_to: Option<RelatesTo>,
}

/// The payload for a server notice message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct ServerNoticeMessageEventContent {
    /// A human-readable description of the notice.
    pub body: String,

    /// The type of notice being represented.
    pub server_notice_type: ServerNoticeType,

    /// A URI giving a contact method for the server administrator.
    ///
    /// Required if the notice type is `m.server_notice.usage_limit_reached`.
    pub admin_contact: Option<String>,

    /// The kind of usage limit the server has exceeded.
    ///
    /// Required if the notice type is `m.server_notice.usage_limit_reached`.
    pub limit_type: Option<LimitType>,
}

/// Types of server notices.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum ServerNoticeType {
    /// The server has exceeded some limit which requires the server administrator to intervene.
    #[serde(rename = "m.server_notice.usage_limit_reached")]
    UsageLimitReached,

    /// Additional variants may be added in the future and will not be considered breaking changes
    /// to ruma-events.
    #[doc(hidden)]
    #[serde(skip)]
    __Nonexhaustive,
}

/// Types of usage limits.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum LimitType {
    /// The server's number of active users in the last 30 days has exceeded the maximum.
    ///
    /// New connections are being refused by the server. What defines "active" is left as an
    /// implementation detail, however servers are encouraged to treat syncing users as "active".
    #[serde(rename = "monthly_active_user")]
    MonthlyActiveUser,

    /// Additional variants may be added in the future and will not be considered breaking changes
    /// to ruma-events.
    #[doc(hidden)]
    #[serde(skip)]
    __Nonexhaustive,
}

/// The payload for a text message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct TextMessageEventContent {
    /// The body of the message.
    pub body: String,

    /// The format used in the `formatted_body`. Currently only `org.matrix.custom.html` is
    /// supported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// The formatted version of the `body`. This is required if `format` is specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub formatted_body: Option<String>,

    /// Information about related messages for
    /// [rich replies](https://matrix.org/docs/spec/client_server/r0.5.0#rich-replies).
    #[serde(rename = "m.relates_to")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relates_to: Option<RelatesTo>,
}

/// The payload for a video message.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct VideoMessageEventContent {
    /// A description of the video, e.g. "Gangnam Style," or some kind of content description for
    /// accessibility, e.g. "video attachment."
    pub body: String,

    /// Metadata about the video clip referred to in `url`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<VideoInfo>,

    /// The URL to the video clip.  Required if the file is unencrypted. The URL (typically
    /// [MXC URI](https://matrix.org/docs/spec/client_server/r0.5.0#mxc-uri)) to the video clip.
    pub url: Option<String>,

    /// Required if video clip is encrypted. Information on the encrypted video clip.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<EncryptedFile>,
}

/// Metadata about a video.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct VideoInfo {
    /// The duration of the video in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration: Option<UInt>,

    /// The height of the video in pixels.
    #[serde(rename = "h")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub height: Option<UInt>,

    /// The width of the video in pixels.
    #[serde(rename = "w")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<UInt>,

    /// The mimetype of the video, e.g. "video/mp4."
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mimetype: Option<String>,

    /// The size of the video in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<UInt>,

    /// Metadata about an image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_info: Option<ThumbnailInfo>,

    /// The URL (typically [MXC URI](https://matrix.org/docs/spec/client_server/r0.5.0#mxc-uri)) to
    /// an image thumbnail of the video clip. Only present if the thumbnail is unencrypted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,

    /// Information on the encrypted thumbnail file.  Only present if the thumbnail is encrypted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_file: Option<EncryptedFile>,
}

/// Information about related messages for
/// [rich replies](https://matrix.org/docs/spec/client_server/r0.5.0#rich-replies).
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct RelatesTo {
    /// Information about another message being replied to.
    #[serde(rename = "m.in_reply_to")]
    pub in_reply_to: InReplyTo,
}

/// Information about the event a "rich reply" is replying to.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct InReplyTo {
    /// The event being replied to.
    pub event_id: EventId,
}

impl_enum! {
    MessageType {
        Audio => "m.audio",
        Emote => "m.emote",
        File => "m.file",
        Image => "m.image",
        Location => "m.location",
        Notice => "m.notice",
        ServerNotice => "m.server_notice",
        Text => "m.text",
        Video => "m.video",
    }
}

impl TextMessageEventContent {
    /// A convenience constructor to create a plain text message
    pub fn new_plain(body: impl Into<String>) -> TextMessageEventContent {
        TextMessageEventContent {
            body: body.into(),
            format: None,
            formatted_body: None,
            relates_to: None,
        }
    }
}

impl Serialize for AudioMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.info.is_some() {
            len += 1;
        }

        if self.url.is_some() {
            len += 1;
        }

        if self.file.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("AudioMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;

        if self.info.is_some() {
            state.serialize_field("info", &self.info)?;
        }

        state.serialize_field("msgtype", "m.audio")?;

        if self.url.is_some() {
            state.serialize_field("url", &self.url)?;
        }

        if self.file.is_some() {
            state.serialize_field("file", &self.file)?;
        }

        state.end()
    }
}

impl Serialize for EmoteMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.format.is_some() {
            len += 1;
        }

        if self.formatted_body.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("EmoteMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;

        if self.format.is_some() {
            state.serialize_field("format", &self.format)?;
        }

        if self.formatted_body.is_some() {
            state.serialize_field("formatted_body", &self.formatted_body)?;
        }

        state.serialize_field("msgtype", "m.emote")?;

        state.end()
    }
}

impl Serialize for FileMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.filename.is_some() {
            len += 1;
        }

        if self.info.is_some() {
            len += 1;
        }

        if self.url.is_some() {
            len += 1;
        }

        if self.file.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("FileMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;

        if self.filename.is_some() {
            state.serialize_field("filename", &self.filename)?;
        }

        state.serialize_field("msgtype", "m.file")?;

        if self.info.is_some() {
            state.serialize_field("info", &self.info)?;
        }

        if self.url.is_some() {
            state.serialize_field("url", &self.url)?;
        }

        if self.file.is_some() {
            state.serialize_field("file", &self.file)?;
        }

        state.end()
    }
}

impl Serialize for ImageMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.info.is_some() {
            len += 1;
        }

        if self.url.is_some() {
            len += 1;
        }

        if self.file.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("ImageMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;
        state.serialize_field("msgtype", "m.image")?;

        if self.info.is_some() {
            state.serialize_field("info", &self.info)?;
        }

        if self.url.is_some() {
            state.serialize_field("url", &self.url)?;
        }

        if self.file.is_some() {
            state.serialize_field("file", &self.file)?;
        }

        state.end()
    }
}

impl Serialize for LocationMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 3;

        if self.info.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("LocationMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;
        state.serialize_field("geo_uri", &self.geo_uri)?;
        state.serialize_field("msgtype", "m.location")?;

        if self.info.is_some() {
            state.serialize_field("info", &self.info)?;
        }

        state.end()
    }
}

impl Serialize for NoticeMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.relates_to.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("NoticeMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;
        state.serialize_field("msgtype", "m.notice")?;

        if self.relates_to.is_some() {
            state.serialize_field("m.relates_to", &self.relates_to)?;
        }

        state.end()
    }
}

impl Serialize for ServerNoticeMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 3;

        if self.admin_contact.is_some() {
            len += 1;
        }

        if self.limit_type.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("ServerNoticeMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;
        state.serialize_field("msgtype", "m.server_notice")?;
        state.serialize_field("server_notice_type", &self.server_notice_type)?;

        if self.admin_contact.is_some() {
            state.serialize_field("admin_contact", &self.admin_contact)?;
        }

        if self.limit_type.is_some() {
            state.serialize_field("limit_type", &self.limit_type)?;
        }

        state.end()
    }
}

impl Serialize for TextMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.format.is_some() {
            len += 1;
        }

        if self.formatted_body.is_some() {
            len += 1;
        }

        if self.relates_to.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("TextMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;

        if self.format.is_some() {
            state.serialize_field("format", &self.format)?;
        }

        if self.formatted_body.is_some() {
            state.serialize_field("formatted_body", &self.formatted_body)?;
        }

        state.serialize_field("msgtype", "m.text")?;

        if self.relates_to.is_some() {
            state.serialize_field("m.relates_to", &self.relates_to)?;
        }

        state.end()
    }
}

impl Serialize for VideoMessageEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 2;

        if self.info.is_some() {
            len += 1;
        }

        if self.url.is_some() {
            len += 1;
        }

        if self.file.is_some() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("VideoMessageEventContent", len)?;

        state.serialize_field("body", &self.body)?;
        state.serialize_field("msgtype", "m.video")?;

        if self.info.is_some() {
            state.serialize_field("info", &self.info)?;
        }

        if self.url.is_some() {
            state.serialize_field("url", &self.url)?;
        }

        if self.file.is_some() {
            state.serialize_field("file", &self.file)?;
        }

        state.end()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::to_string;

    use super::{AudioMessageEventContent, MessageEventContent};
    use crate::room::message::{InReplyTo, RelatesTo, TextMessageEventContent};
    use crate::EventResult;
    use ruma_identifiers::EventId;
    use std::convert::TryFrom;

    #[test]
    fn serialization() {
        let message_event_content = MessageEventContent::Audio(AudioMessageEventContent {
            body: "test".to_string(),
            info: None,
            url: Some("http://example.com/audio.mp3".to_string()),
            file: None,
        });

        assert_eq!(
            to_string(&message_event_content).unwrap(),
            r#"{"body":"test","msgtype":"m.audio","url":"http://example.com/audio.mp3"}"#
        );
    }

    #[test]
    fn plain_text() {
        let message_event_content = MessageEventContent::Text(TextMessageEventContent::new_plain(
            "> <@test:example.com> test\n\ntest reply",
        ));

        assert_eq!(
            to_string(&message_event_content).unwrap(),
            r#"{"body":"> <@test:example.com> test\n\ntest reply","msgtype":"m.text"}"#
        );
    }

    #[test]
    fn relates_to_serialization() {
        let message_event_content = MessageEventContent::Text(TextMessageEventContent {
            body: "> <@test:example.com> test\n\ntest reply".to_owned(),
            format: None,
            formatted_body: None,
            relates_to: Some(RelatesTo {
                in_reply_to: InReplyTo {
                    event_id: EventId::try_from("$15827405538098VGFWH:example.com").unwrap(),
                },
            }),
        });

        assert_eq!(
            to_string(&message_event_content).unwrap(),
            r#"{"body":"> <@test:example.com> test\n\ntest reply","msgtype":"m.text","m.relates_to":{"m.in_reply_to":{"event_id":"$15827405538098VGFWH:example.com"}}}"#
        );
    }

    #[test]
    fn deserialization() {
        let message_event_content = MessageEventContent::Audio(AudioMessageEventContent {
            body: "test".to_string(),
            info: None,
            url: Some("http://example.com/audio.mp3".to_string()),
            file: None,
        });

        assert_eq!(
            serde_json::from_str::<EventResult<MessageEventContent>>(
                r#"{"body":"test","msgtype":"m.audio","url":"http://example.com/audio.mp3"}"#
            )
            .unwrap()
            .into_result()
            .unwrap(),
            message_event_content
        );
    }

    #[test]
    fn deserialization_failure() {
        assert!(serde_json::from_str::<EventResult<MessageEventContent>>(
            r#"{"body":"test","msgtype":"m.location","url":"http://example.com/audio.mp3"}"#
        )
        .unwrap()
        .into_result()
        .is_err());
    }
}