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
use std::collections::HashSet;

use indexmap::{IndexMap, IndexSet};
use iso8601_timestamp::Timestamp;
use revolt_config::config;
use revolt_models::v0::{
    self, BulkMessageResponse, DataMessageSend, Embed, MessageAuthor, MessageSort, MessageWebhook,
    PushNotification, ReplyIntent, SendableEmbed, Text, RE_MENTION,
};
use revolt_permissions::{ChannelPermission, PermissionValue};
use revolt_result::Result;
use ulid::Ulid;
use validator::Validate;

use crate::{
    events::client::EventV1,
    tasks::{self, ack::AckEvent},
    util::idempotency::IdempotencyKey,
    Channel, Database, Emoji, File, User,
};

auto_derived_partial!(
    /// Message
    pub struct Message {
        /// Unique Id
        #[serde(rename = "_id")]
        pub id: String,
        /// Unique value generated by client sending this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub nonce: Option<String>,
        /// Id of the channel this message was sent in
        pub channel: String,
        /// Id of the user or webhook that sent this message
        pub author: String,
        /// The webhook that sent this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub webhook: Option<MessageWebhook>,
        /// Message content
        #[serde(skip_serializing_if = "Option::is_none")]
        pub content: Option<String>,
        /// System message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub system: Option<SystemMessage>,
        /// Array of attachments
        #[serde(skip_serializing_if = "Option::is_none")]
        pub attachments: Option<Vec<File>>,
        /// Time at which this message was last edited
        #[serde(skip_serializing_if = "Option::is_none")]
        pub edited: Option<Timestamp>,
        /// Attached embeds to this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub embeds: Option<Vec<Embed>>,
        /// Array of user ids mentioned in this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub mentions: Option<Vec<String>>,
        /// Array of message ids this message is replying to
        #[serde(skip_serializing_if = "Option::is_none")]
        pub replies: Option<Vec<String>>,
        /// Hashmap of emoji IDs to array of user IDs
        #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
        pub reactions: IndexMap<String, IndexSet<String>>,
        /// Information about how this message should be interacted with
        #[serde(skip_serializing_if = "Interactions::is_default", default)]
        pub interactions: Interactions,
        /// Name and / or avatar overrides for this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub masquerade: Option<Masquerade>,
    },
    "PartialMessage"
);

auto_derived!(
    /// System Event
    #[serde(tag = "type")]
    pub enum SystemMessage {
        #[serde(rename = "text")]
        Text { content: String },
        #[serde(rename = "user_added")]
        UserAdded { id: String, by: String },
        #[serde(rename = "user_remove")]
        UserRemove { id: String, by: String },
        #[serde(rename = "user_joined")]
        UserJoined { id: String },
        #[serde(rename = "user_left")]
        UserLeft { id: String },
        #[serde(rename = "user_kicked")]
        UserKicked { id: String },
        #[serde(rename = "user_banned")]
        UserBanned { id: String },
        #[serde(rename = "channel_renamed")]
        ChannelRenamed { name: String, by: String },
        #[serde(rename = "channel_description_changed")]
        ChannelDescriptionChanged { by: String },
        #[serde(rename = "channel_icon_changed")]
        ChannelIconChanged { by: String },
        #[serde(rename = "channel_ownership_changed")]
        ChannelOwnershipChanged { from: String, to: String },
    }

    /// Name and / or avatar override information
    pub struct Masquerade {
        /// Replace the display name shown on this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub name: Option<String>,
        /// Replace the avatar shown on this message (URL to image file)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub avatar: Option<String>,
        /// Replace the display role colour shown on this message
        ///
        /// Must have `ManageRole` permission to use
        #[serde(skip_serializing_if = "Option::is_none")]
        pub colour: Option<String>,
    }

    /// Information to guide interactions on this message
    #[derive(Default)]
    pub struct Interactions {
        /// Reactions which should always appear and be distinct
        #[serde(skip_serializing_if = "Option::is_none", default)]
        pub reactions: Option<IndexSet<String>>,
        /// Whether reactions should be restricted to the given list
        ///
        /// Can only be set to true if reactions list is of at least length 1
        #[serde(skip_serializing_if = "crate::if_false", default)]
        pub restrict_reactions: bool,
    }

    /// Appended Information
    pub struct AppendMessage {
        /// Additional embeds to include in this message
        #[serde(skip_serializing_if = "Option::is_none")]
        pub embeds: Option<Vec<Embed>>,
    }

    /// Message Time Period
    ///
    /// Filter and sort messages by time
    #[serde(untagged)]
    pub enum MessageTimePeriod {
        Relative {
            /// Message id to search around
            ///
            /// Specifying 'nearby' ignores 'before', 'after' and 'sort'.
            /// It will also take half of limit rounded as the limits to each side.
            /// It also fetches the message ID specified.
            nearby: String,
        },
        Absolute {
            /// Message id before which messages should be fetched
            before: Option<String>,
            /// Message id after which messages should be fetched
            after: Option<String>,
            /// Message sort direction
            sort: Option<MessageSort>,
        },
    }

    /// Message Filter
    #[derive(Default)]
    pub struct MessageFilter {
        /// Parent channel ID
        pub channel: Option<String>,
        /// Message author ID
        pub author: Option<String>,
        /// Search query
        pub query: Option<String>,
    }

    /// Message Query
    pub struct MessageQuery {
        /// Maximum number of messages to fetch
        ///
        /// For fetching nearby messages, this is \`(limit + 1)\`.
        pub limit: Option<i64>,
        /// Filter to apply
        #[serde(flatten)]
        pub filter: MessageFilter,
        /// Time period to fetch
        #[serde(flatten)]
        pub time_period: MessageTimePeriod,
    }
);

#[allow(clippy::derivable_impls)]
impl Default for Message {
    fn default() -> Self {
        Self {
            id: Default::default(),
            nonce: None,
            channel: Default::default(),
            author: Default::default(),
            webhook: None,
            content: None,
            system: None,
            attachments: None,
            edited: None,
            embeds: None,
            mentions: None,
            replies: None,
            reactions: Default::default(),
            interactions: Default::default(),
            masquerade: None,
        }
    }
}

#[allow(clippy::disallowed_methods)]
impl Message {
    /// Create message from API data
    pub async fn create_from_api(
        db: &Database,
        channel: Channel,
        data: DataMessageSend,
        author: MessageAuthor<'_>,
        mut idempotency: IdempotencyKey,
        generate_embeds: bool,
        allow_mentions: bool,
    ) -> Result<Message> {
        let config = config().await;

        Message::validate_sum(
            &data.content,
            data.embeds.as_deref().unwrap_or_default(),
            config.features.limits.default.message_length,
        )?;

        idempotency
            .consume_nonce(data.nonce)
            .await
            .map_err(|_| create_error!(InvalidOperation))?;

        // Check the message is not empty
        if (data.content.as_ref().map_or(true, |v| v.is_empty()))
            && (data.attachments.as_ref().map_or(true, |v| v.is_empty()))
            && (data.embeds.as_ref().map_or(true, |v| v.is_empty()))
        {
            return Err(create_error!(EmptyMessage));
        }

        // Ensure restrict_reactions is not specified without reactions list
        if let Some(interactions) = &data.interactions {
            if interactions.restrict_reactions {
                let disallowed = if let Some(list) = &interactions.reactions {
                    list.is_empty()
                } else {
                    true
                };

                if disallowed {
                    return Err(create_error!(InvalidProperty));
                }
            }
        }

        let (author_id, webhook) = match &author {
            MessageAuthor::User(user) => (user.id.clone(), None),
            MessageAuthor::Webhook(webhook) => (webhook.id.clone(), Some((*webhook).clone())),
            MessageAuthor::System { .. } => ("00000000000000000000000000".to_string(), None),
        };

        // Start constructing the message
        let message_id = Ulid::new().to_string();
        let mut message = Message {
            id: message_id.clone(),
            channel: channel.id(),
            masquerade: data.masquerade.map(|masquerade| masquerade.into()),
            interactions: data
                .interactions
                .map(|interactions| interactions.into())
                .unwrap_or_default(),
            author: author_id,
            webhook: webhook.map(|w| w.into()),
            ..Default::default()
        };

        // Parse mentions in message.
        let mut mentions = HashSet::new();
        if allow_mentions {
            if let Some(content) = &data.content {
                for capture in RE_MENTION.captures_iter(content) {
                    if let Some(mention) = capture.get(1) {
                        mentions.insert(mention.as_str().to_string());
                    }
                }
            }
        }

        // Verify replies are valid.
        let mut replies = HashSet::new();
        if let Some(entries) = data.replies {
            if entries.len() > config.features.limits.default.message_replies {
                return Err(create_error!(TooManyReplies {
                    max: config.features.limits.default.message_replies,
                }));
            }

            for ReplyIntent { id, mention } in entries {
                let message = db.fetch_message(&id).await?;

                if mention && allow_mentions {
                    mentions.insert(message.author.to_owned());
                }

                replies.insert(message.id);
            }
        }

        if !mentions.is_empty() {
            message.mentions.replace(mentions.into_iter().collect());
        }

        if !replies.is_empty() {
            message
                .replies
                .replace(replies.into_iter().collect::<Vec<String>>());
        }

        // Add attachments to message.
        let mut attachments = vec![];
        if data
            .attachments
            .as_ref()
            .is_some_and(|v| v.len() > config.features.limits.default.message_attachments)
        {
            return Err(create_error!(TooManyAttachments {
                max: config.features.limits.default.message_attachments,
            }));
        }

        if data
            .embeds
            .as_ref()
            .is_some_and(|v| v.len() > config.features.limits.default.message_embeds)
        {
            return Err(create_error!(TooManyEmbeds {
                max: config.features.limits.default.message_embeds,
            }));
        }

        for attachment_id in data.attachments.as_deref().unwrap_or_default() {
            attachments.push(
                db.find_and_use_attachment(attachment_id, "attachments", "message", &message_id)
                    .await?,
            );
        }

        if !attachments.is_empty() {
            message.attachments.replace(attachments);
        }

        // Process included embeds.
        for sendable_embed in data.embeds.unwrap_or_default() {
            message.attach_sendable_embed(db, sendable_embed).await?;
        }

        // Set content
        message.content = data.content;

        // Pass-through nonce value for clients
        message.nonce = Some(idempotency.into_key());

        // Send the message
        message.send(db, author, &channel, generate_embeds).await?;

        Ok(message)
    }

    /// Send a message without any notifications
    pub async fn send_without_notifications(
        &mut self,
        db: &Database,
        is_dm: bool,
        generate_embeds: bool,
    ) -> Result<()> {
        db.insert_message(self).await?;

        // Fan out events
        EventV1::Message(self.clone().into())
            .p(self.channel.to_string())
            .await;

        // Update last_message_id
        tasks::last_message_id::queue(self.channel.to_string(), self.id.to_string(), is_dm).await;

        // Add mentions for affected users
        if let Some(mentions) = &self.mentions {
            for user in mentions {
                tasks::ack::queue(
                    self.channel.to_string(),
                    user.to_string(),
                    AckEvent::AddMention {
                        ids: vec![self.id.to_string()],
                    },
                )
                .await;
            }
        }

        // Generate embeds
        if generate_embeds {
            if let Some(content) = &self.content {
                tasks::process_embeds::queue(
                    self.channel.to_string(),
                    self.id.to_string(),
                    content.clone(),
                )
                .await;
            }
        }

        Ok(())
    }

    /// Send a message
    pub async fn send(
        &mut self,
        db: &Database,
        author: MessageAuthor<'_>,
        channel: &Channel,
        generate_embeds: bool,
    ) -> Result<()> {
        self.send_without_notifications(
            db,
            matches!(channel, Channel::DirectMessage { .. }),
            generate_embeds,
        )
        .await?;

        // Push out Web Push notifications
        crate::tasks::web_push::queue(
            {
                match channel {
                    Channel::DirectMessage { recipients, .. }
                    | Channel::Group { recipients, .. } => recipients.clone(),
                    Channel::TextChannel { .. } => self.mentions.clone().unwrap_or_default(),
                    _ => vec![],
                }
            },
            PushNotification::from(self.clone().into(), Some(author), &channel.id()).await,
        )
        .await;

        Ok(())
    }

    /// Create text embed from sendable embed
    pub async fn create_embed(&self, db: &Database, embed: SendableEmbed) -> Result<Embed> {
        embed.validate().map_err(|error| {
            create_error!(FailedValidation {
                error: error.to_string()
            })
        })?;

        let media = if let Some(id) = embed.media {
            Some(
                db.find_and_use_attachment(&id, "attachments", "message", &self.id)
                    .await?,
            )
        } else {
            None
        };

        Ok(Embed::Text(Text {
            icon_url: embed.icon_url,
            url: embed.url,
            title: embed.title,
            description: embed.description,
            media: media.map(|m| m.into()),
            colour: embed.colour,
        }))
    }

    /// Update message data
    pub async fn update(&mut self, db: &Database, partial: PartialMessage) -> Result<()> {
        self.apply_options(partial.clone());
        db.update_message(&self.id, &partial).await?;

        EventV1::MessageUpdate {
            id: self.id.clone(),
            channel: self.channel.clone(),
            data: partial.into(),
        }
        .p(self.channel.clone())
        .await;

        Ok(())
    }

    /// Helper function to fetch many messages with users
    pub async fn fetch_with_users(
        db: &Database,
        query: MessageQuery,
        perspective: &User,
        include_users: Option<bool>,
        server_id: Option<String>,
    ) -> Result<BulkMessageResponse> {
        let messages: Vec<v0::Message> = db
            .fetch_messages(query)
            .await?
            .into_iter()
            .map(Into::into)
            .collect();

        if let Some(true) = include_users {
            let user_ids = messages
                .iter()
                .map(|m| m.author.clone())
                .collect::<HashSet<String>>()
                .into_iter()
                .collect::<Vec<String>>();
            let users = User::fetch_many_ids_as_mutuals(db, perspective, &user_ids).await?;

            Ok(BulkMessageResponse::MessagesAndUsers {
                messages,
                users,
                members: if let Some(server_id) = server_id {
                    Some(
                        db.fetch_members(&server_id, &user_ids)
                            .await?
                            .into_iter()
                            .map(Into::into)
                            .collect(),
                    )
                } else {
                    None
                },
            })
        } else {
            Ok(BulkMessageResponse::JustMessages(messages))
        }
    }

    /// Append content to message
    pub async fn append(
        db: &Database,
        id: String,
        channel: String,
        append: AppendMessage,
    ) -> Result<()> {
        db.append_message(&id, &append).await?;

        EventV1::MessageAppend {
            id,
            channel: channel.to_string(),
            append: append.into(),
        }
        .p(channel)
        .await;

        Ok(())
    }

    /// Convert sendable embed to text embed and attach to message
    pub async fn attach_sendable_embed(
        &mut self,
        db: &Database,
        embed: v0::SendableEmbed,
    ) -> Result<()> {
        let media: Option<v0::File> = if let Some(id) = embed.media {
            Some(
                db.find_and_use_attachment(&id, "attachments", "message", &self.id)
                    .await?
                    .into(),
            )
        } else {
            None
        };

        let embed = v0::Embed::Text(v0::Text {
            icon_url: embed.icon_url,
            url: embed.url,
            title: embed.title,
            description: embed.description,
            media,
            colour: embed.colour,
        });

        if let Some(embeds) = &mut self.embeds {
            embeds.push(embed);
        } else {
            self.embeds = Some(vec![embed]);
        }

        Ok(())
    }

    /// Add a reaction to a message
    pub async fn add_reaction(&self, db: &Database, user: &User, emoji: &str) -> Result<()> {
        // Check how many reactions are already on the message
        let config = config().await;
        if self.reactions.len() >= config.features.limits.default.message_reactions
            && !self.reactions.contains_key(emoji)
        {
            return Err(create_error!(InvalidOperation));
        }

        // Check if the emoji is whitelisted
        if !self.interactions.can_use(emoji) {
            return Err(create_error!(InvalidOperation));
        }

        // Check if the emoji is usable by us
        if !Emoji::can_use(db, emoji).await? {
            return Err(create_error!(InvalidOperation));
        }

        // Send reaction event
        EventV1::MessageReact {
            id: self.id.to_string(),
            channel_id: self.channel.to_string(),
            user_id: user.id.to_string(),
            emoji_id: emoji.to_string(),
        }
        .p(self.channel.to_string())
        .await;

        // Add emoji
        db.add_reaction(&self.id, emoji, &user.id).await
    }

    /// Validate the sum of content of a message is under threshold
    pub fn validate_sum(
        content: &Option<String>,
        embeds: &[SendableEmbed],
        max_length: usize,
    ) -> Result<()> {
        let mut running_total = 0;
        if let Some(content) = content {
            running_total += content.len();
        }

        for embed in embeds {
            if let Some(desc) = &embed.description {
                running_total += desc.len();
            }
        }

        if running_total <= max_length {
            Ok(())
        } else {
            Err(create_error!(PayloadTooLarge))
        }
    }

    /// Delete a message
    pub async fn delete(self, db: &Database) -> Result<()> {
        let file_ids: Vec<String> = self
            .attachments
            .map(|files| files.iter().map(|file| file.id.to_string()).collect())
            .unwrap_or_default();

        if !file_ids.is_empty() {
            db.mark_attachments_as_deleted(&file_ids).await?;
        }

        db.delete_message(&self.id).await?;

        EventV1::MessageDelete {
            id: self.id,
            channel: self.channel.clone(),
        }
        .p(self.channel)
        .await;
        Ok(())
    }

    /// Bulk delete messages
    pub async fn bulk_delete(db: &Database, channel: &str, ids: Vec<String>) -> Result<()> {
        let valid_ids = db
            .fetch_messages_by_id(&ids)
            .await?
            .into_iter()
            .filter(|msg| msg.channel == channel)
            .map(|msg| msg.id)
            .collect::<Vec<String>>();

        db.delete_messages(channel, &valid_ids).await?;
        EventV1::BulkMessageDelete {
            channel: channel.to_string(),
            ids: valid_ids,
        }
        .p(channel.to_string())
        .await;
        Ok(())
    }

    /// Remove a reaction from a message
    pub async fn remove_reaction(&self, db: &Database, user: &str, emoji: &str) -> Result<()> {
        // Check if it actually exists
        let empty = if let Some(users) = self.reactions.get(emoji) {
            if !users.contains(user) {
                return Err(create_error!(NotFound));
            }

            users.len() == 1
        } else {
            return Err(create_error!(NotFound));
        };

        // Send reaction event
        EventV1::MessageUnreact {
            id: self.id.to_string(),
            channel_id: self.channel.to_string(),
            user_id: user.to_string(),
            emoji_id: emoji.to_string(),
        }
        .p(self.channel.to_string())
        .await;

        if empty {
            // If empty, remove the reaction entirely
            db.clear_reaction(&self.id, emoji).await
        } else {
            // Otherwise only remove that one reaction
            db.remove_reaction(&self.id, emoji, user).await
        }
    }

    /// Remove a reaction from a message
    pub async fn clear_reaction(&self, db: &Database, emoji: &str) -> Result<()> {
        // Send reaction event
        EventV1::MessageRemoveReaction {
            id: self.id.to_string(),
            channel_id: self.channel.to_string(),
            emoji_id: emoji.to_string(),
        }
        .p(self.channel.to_string())
        .await;

        // Write to database
        db.clear_reaction(&self.id, emoji).await
    }
}

impl SystemMessage {
    pub fn into_message(self, channel: String) -> Message {
        Message {
            id: Ulid::new().to_string(),
            channel,
            author: "00000000000000000000000000".to_string(),
            system: Some(self),

            ..Default::default()
        }
    }
}

impl Interactions {
    /// Validate interactions info is correct
    pub async fn validate(&self, db: &Database, permissions: &PermissionValue) -> Result<()> {
        let config = config().await;

        if let Some(reactions) = &self.reactions {
            permissions.throw_if_lacking_channel_permission(ChannelPermission::React)?;

            if reactions.len() > config.features.limits.default.message_reactions {
                return Err(create_error!(InvalidOperation));
            }

            for reaction in reactions {
                if !Emoji::can_use(db, reaction).await? {
                    return Err(create_error!(InvalidOperation));
                }
            }
        }

        Ok(())
    }

    /// Check if we can use a given emoji to react
    pub fn can_use(&self, emoji: &str) -> bool {
        if self.restrict_reactions {
            if let Some(reactions) = &self.reactions {
                reactions.contains(emoji)
            } else {
                false
            }
        } else {
            true
        }
    }

    /// Check if default initialisation of fields
    pub fn is_default(&self) -> bool {
        !self.restrict_reactions && self.reactions.is_none()
    }
}