rust-tg-bot-ext 1.0.0-rc.1

Application framework for Telegram bots -- handlers, filters, persistence, job queue
Documentation
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
1134
1135
1136
//! Core [`Filter`] trait and the [`F`] wrapper for bitwise composition.
//!
//! Every filter in the crate implements [`Filter`].  The [`F`] new-type wraps an
//! `Arc`-backed trait object and provides `&`, `|`, `^`, `!` operators so filters
//! can be combined with zero boilerplate:
//!
//! ```ignore
//! let f = F::from(Text::any()) & !F::from(Command::starts());
//! ```

use std::collections::HashMap;
use std::fmt;
use std::ops::{BitAnd, BitOr, BitXor, Not};
use std::sync::Arc;

use serde_json::Value;

// ---------------------------------------------------------------------------
// Update alias
// ---------------------------------------------------------------------------

/// The canonical typed `Update` from the raw Telegram types.
pub type Update = rust_tg_bot_raw::types::update::Update;

// ---------------------------------------------------------------------------
// Value bridge for filters (legacy — kept for compatibility)
// ---------------------------------------------------------------------------

/// Convert a typed [`Update`] reference to a [`serde_json::Value`].
///
/// Retained for callers that still need raw JSON inspection.  All filter
/// `check_update` implementations use typed field access instead.
pub fn to_value(update: &Update) -> Value {
    serde_json::to_value(update).unwrap_or_default()
}

// ---------------------------------------------------------------------------
// FilterResult
// ---------------------------------------------------------------------------

/// Result of a filter check, supporting data filters (like Python's `data_filter`).
///
/// Simple filters return [`Match`](FilterResult::Match) or [`NoMatch`](FilterResult::NoMatch).
/// Data filters (e.g. regex) return [`MatchWithData`](FilterResult::MatchWithData) carrying
/// named capture groups or other extracted data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterResult {
    /// The filter did not match.
    NoMatch,
    /// The filter matched but produced no additional data.
    Match,
    /// The filter matched and produced named capture data (e.g. regex groups).
    MatchWithData(HashMap<String, Vec<String>>),
}

impl FilterResult {
    /// Returns `true` when the filter matched (either `Match` or `MatchWithData`).
    #[must_use]
    pub fn is_match(&self) -> bool {
        !matches!(self, FilterResult::NoMatch)
    }

    /// Merge data from two `FilterResult` values. Used by [`AndFilter`].
    ///
    /// - If either side is `NoMatch`, the result is `NoMatch`.
    /// - If both carry data, their maps are merged (values appended).
    /// - If only one carries data, that data is preserved.
    #[must_use]
    pub fn merge(self, other: FilterResult) -> FilterResult {
        match (self, other) {
            (FilterResult::NoMatch, _) | (_, FilterResult::NoMatch) => FilterResult::NoMatch,
            (FilterResult::MatchWithData(mut a), FilterResult::MatchWithData(b)) => {
                for (k, mut v) in b {
                    a.entry(k).or_default().append(&mut v);
                }
                FilterResult::MatchWithData(a)
            }
            (FilterResult::MatchWithData(d), FilterResult::Match)
            | (FilterResult::Match, FilterResult::MatchWithData(d)) => {
                FilterResult::MatchWithData(d)
            }
            (FilterResult::Match, FilterResult::Match) => FilterResult::Match,
        }
    }
}

// ---------------------------------------------------------------------------
// Message / user / chat extraction helpers (Value-based, retained for tests)
// ---------------------------------------------------------------------------

/// Extract the effective message from a raw [`Value`] (reference-based).
pub fn effective_message_val(v: &Value) -> Option<&Value> {
    v.get("message")
        .or_else(|| v.get("edited_message"))
        .or_else(|| v.get("channel_post"))
        .or_else(|| v.get("edited_channel_post"))
        .or_else(|| v.get("business_message"))
        .or_else(|| v.get("edited_business_message"))
}

/// Extract the effective user from a raw [`Value`] (reference-based).
pub fn effective_user_val(v: &Value) -> Option<&Value> {
    if let Some(msg) = effective_message_val(v) {
        if let Some(u) = msg.get("from") {
            return Some(u);
        }
    }
    for key in &[
        "callback_query",
        "inline_query",
        "chosen_inline_result",
        "shipping_query",
        "pre_checkout_query",
        "poll_answer",
        "my_chat_member",
        "chat_member",
        "chat_join_request",
    ] {
        if let Some(obj) = v.get(key) {
            if let Some(u) = obj.get("from") {
                return Some(u);
            }
        }
    }
    None
}

/// Extract the effective chat from a raw [`Value`] (reference-based).
pub fn effective_chat_val(v: &Value) -> Option<&Value> {
    if let Some(msg) = effective_message_val(v) {
        if let Some(c) = msg.get("chat") {
            return Some(c);
        }
    }
    for key in &[
        "callback_query",
        "my_chat_member",
        "chat_member",
        "chat_join_request",
    ] {
        if let Some(obj) = v.get(key) {
            if let Some(c) = obj.get("chat") {
                return Some(c);
            }
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Message / user / chat extraction helpers (Value-based, owned)
// ---------------------------------------------------------------------------

/// Best-effort extraction of the *effective message* from an [`Update`] as a
/// [`Value`] for callers that still operate on JSON field access.
pub fn effective_message(update: &Update) -> Option<Value> {
    update
        .effective_message()
        .and_then(|m| serde_json::to_value(m).ok())
}

/// Extract the effective user from an [`Update`] as a [`Value`].
pub fn effective_user(update: &Update) -> Option<Value> {
    update
        .effective_user()
        .and_then(|u| serde_json::to_value(u).ok())
}

/// Extract the effective chat from an [`Update`] as a [`Value`].
pub fn effective_chat(update: &Update) -> Option<Value> {
    update
        .effective_chat()
        .and_then(|c| serde_json::to_value(c).ok())
}

/// Returns `true` when the update carries a message-like field.
pub fn has_effective_message(update: &Update) -> bool {
    update.effective_message().is_some()
}

// ---------------------------------------------------------------------------
// Filter trait
// ---------------------------------------------------------------------------

/// The single trait every filter must implement.
///
/// Returns a [`FilterResult`] which can be `NoMatch`, `Match`, or
/// `MatchWithData` (for data filters like regex).
pub trait Filter: Send + Sync + 'static {
    /// Check whether the update should be handled, optionally returning
    /// extracted data.
    fn check_update(&self, update: &Update) -> FilterResult;

    /// Human-readable name for debugging / display.
    fn name(&self) -> &str {
        std::any::type_name::<Self>()
    }
}

// ---------------------------------------------------------------------------
// F wrapper
// ---------------------------------------------------------------------------

/// Ergonomic wrapper around `Arc<dyn Filter>` with operator overloads.
///
/// `F` is `Clone`-able: cloning shares the underlying filter via `Arc`.
/// This allows filter constants (like `TEXT`, `COMMAND`) to be used with
/// the bitwise composition operators (`&`, `|`, `!`) without consuming them.
#[derive(Clone)]
pub struct F(pub Arc<dyn Filter>);

impl F {
    /// Wrap any concrete filter into [`F`].
    pub fn new(filter: impl Filter) -> Self {
        Self(Arc::new(filter))
    }
}

impl fmt::Debug for F {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "F({})", self.0.name())
    }
}

impl fmt::Display for F {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.name())
    }
}

impl Filter for F {
    fn check_update(&self, update: &Update) -> FilterResult {
        self.0.check_update(update)
    }

    fn name(&self) -> &str {
        self.0.name()
    }
}

// ---------------------------------------------------------------------------
// Combinators (private structs)
// ---------------------------------------------------------------------------

struct AndFilter {
    left: F,
    right: F,
    display: String,
}

impl Filter for AndFilter {
    fn check_update(&self, update: &Update) -> FilterResult {
        let left = self.left.check_update(update);
        if !left.is_match() {
            return FilterResult::NoMatch;
        }
        let right = self.right.check_update(update);
        left.merge(right)
    }

    fn name(&self) -> &str {
        &self.display
    }
}

struct OrFilter {
    left: F,
    right: F,
    display: String,
}

impl Filter for OrFilter {
    fn check_update(&self, update: &Update) -> FilterResult {
        let left = self.left.check_update(update);
        if left.is_match() {
            return left;
        }
        self.right.check_update(update)
    }

    fn name(&self) -> &str {
        &self.display
    }
}

struct XorFilter {
    left: F,
    right: F,
    display: String,
}

impl Filter for XorFilter {
    fn check_update(&self, update: &Update) -> FilterResult {
        let left = self.left.check_update(update);
        let right = self.right.check_update(update);
        match (left.is_match(), right.is_match()) {
            (true, false) => self.left.check_update(update),
            (false, true) => right,
            _ => FilterResult::NoMatch,
        }
    }

    fn name(&self) -> &str {
        &self.display
    }
}

struct NotFilter {
    inner: F,
    display: String,
}

impl Filter for NotFilter {
    fn check_update(&self, update: &Update) -> FilterResult {
        if self.inner.check_update(update).is_match() {
            FilterResult::NoMatch
        } else {
            FilterResult::Match
        }
    }

    fn name(&self) -> &str {
        &self.display
    }
}

// ---------------------------------------------------------------------------
// Operator impls
// ---------------------------------------------------------------------------

impl BitAnd for F {
    type Output = F;

    fn bitand(self, rhs: F) -> F {
        let display = format!("<{} and {}>", self.0.name(), rhs.0.name());
        F(Arc::new(AndFilter {
            left: self,
            right: rhs,
            display,
        }))
    }
}

impl BitOr for F {
    type Output = F;

    fn bitor(self, rhs: F) -> F {
        let display = format!("<{} or {}>", self.0.name(), rhs.0.name());
        F(Arc::new(OrFilter {
            left: self,
            right: rhs,
            display,
        }))
    }
}

impl BitXor for F {
    type Output = F;

    fn bitxor(self, rhs: F) -> F {
        let display = format!("<{} xor {}>", self.0.name(), rhs.0.name());
        F(Arc::new(XorFilter {
            left: self,
            right: rhs,
            display,
        }))
    }
}

impl Not for F {
    type Output = F;

    fn not(self) -> F {
        let display = format!("<not {}>", self.0.name());
        F(Arc::new(NotFilter {
            inner: self,
            display,
        }))
    }
}

// ---------------------------------------------------------------------------
// Closure-backed filter
// ---------------------------------------------------------------------------

/// A filter built from a bare closure. Useful for one-off / ad-hoc filters.
pub struct FnFilter<Func> {
    func: Func,
    label: &'static str,
}

impl<Func> FnFilter<Func>
where
    Func: Fn(&Update) -> bool + Send + Sync + 'static,
{
    /// Create a new closure-backed filter.
    pub fn new(label: &'static str, func: Func) -> Self {
        Self { func, label }
    }
}

impl<Func> Filter for FnFilter<Func>
where
    Func: Fn(&Update) -> bool + Send + Sync + 'static,
{
    fn check_update(&self, update: &Update) -> FilterResult {
        if (self.func)(update) {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        self.label
    }
}

// ---------------------------------------------------------------------------
// ALL filter
// ---------------------------------------------------------------------------

/// Matches every update that carries an effective message.
pub struct All;

impl Filter for All {
    fn check_update(&self, update: &Update) -> FilterResult {
        if has_effective_message(update) {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.ALL"
    }
}

/// Constant instance -- `filters::ALL`.
pub const ALL: All = All;

// ---------------------------------------------------------------------------
// Macro for simple presence filters
// ---------------------------------------------------------------------------

macro_rules! message_presence_filter {
    (
        $(#[$meta:meta])*
        $struct_name:ident, $field:ident, $display:expr
    ) => {
        $(#[$meta])*
        pub struct $struct_name;

        impl Filter for $struct_name {
            fn check_update(&self, update: &Update) -> FilterResult {
                if update
                    .effective_message()
                    .and_then(|m| m.$field.as_ref())
                    .is_some()
                {
                    FilterResult::Match
                } else {
                    FilterResult::NoMatch
                }
            }

            fn name(&self) -> &str {
                $display
            }
        }
    };
    // Variant for bool fields (non-Option, true = present)
    (
        $(#[$meta:meta])*
        bool: $struct_name:ident, $field:ident, $display:expr
    ) => {
        $(#[$meta])*
        pub struct $struct_name;

        impl Filter for $struct_name {
            fn check_update(&self, update: &Update) -> FilterResult {
                if update
                    .effective_message()
                    .map(|m| m.$field)
                    .unwrap_or(false)
                {
                    FilterResult::Match
                } else {
                    FilterResult::NoMatch
                }
            }

            fn name(&self) -> &str {
                $display
            }
        }
    };
}

// ---------------------------------------------------------------------------
// Presence filter instances
// ---------------------------------------------------------------------------

message_presence_filter!(
    /// Messages containing an animation (GIF).
    AnimationFilter, animation, "filters.ANIMATION"
);
/// Constant instance of [`AnimationFilter`] -- matches messages containing an animation (GIF).
pub const ANIMATION: AnimationFilter = AnimationFilter;

message_presence_filter!(
    /// Messages containing audio.
    AudioFilter, audio, "filters.AUDIO"
);
/// Constant instance of [`AudioFilter`] -- matches messages containing audio.
pub const AUDIO: AudioFilter = AudioFilter;

message_presence_filter!(
    /// Messages containing a boost_added notification.
    BoostAdded, boost_added, "filters.BOOST_ADDED"
);
/// Constant instance of [`BoostAdded`] -- matches messages containing a boost-added notification.
pub const BOOST_ADDED: BoostAdded = BoostAdded;

message_presence_filter!(
    /// Messages containing a checklist.
    ChecklistFilter, checklist, "filters.CHECKLIST"
);
/// Constant instance of [`ChecklistFilter`] -- matches messages containing a checklist.
pub const CHECKLIST: ChecklistFilter = ChecklistFilter;

message_presence_filter!(
    /// Messages containing a contact.
    ContactFilter, contact, "filters.CONTACT"
);
/// Constant instance of [`ContactFilter`] -- matches messages containing a contact.
pub const CONTACT: ContactFilter = ContactFilter;

message_presence_filter!(
    /// Messages containing an effect_id.
    EffectId, effect_id, "filters.EFFECT_ID"
);
/// Constant instance of [`EffectId`] -- matches messages containing an effect ID.
pub const EFFECT_ID: EffectId = EffectId;

message_presence_filter!(
    /// Messages that have a forward_origin.
    ForwardedPresence, forward_origin, "filters.FORWARDED"
);
/// Constant instance of [`ForwardedPresence`] -- matches messages that have a forward origin.
pub const FORWARDED: ForwardedPresence = ForwardedPresence;

message_presence_filter!(
    /// Messages containing a game.
    GameFilter, game, "filters.GAME"
);
/// Constant instance of [`GameFilter`] -- matches messages containing a game.
pub const GAME: GameFilter = GameFilter;

message_presence_filter!(
    /// Messages containing a giveaway.
    GiveawayFilter, giveaway, "filters.GIVEAWAY"
);
/// Constant instance of [`GiveawayFilter`] -- matches messages containing a giveaway.
pub const GIVEAWAY: GiveawayFilter = GiveawayFilter;

message_presence_filter!(
    /// Messages containing giveaway_winners.
    GiveawayWinners, giveaway_winners, "filters.GIVEAWAY_WINNERS"
);
/// Constant instance of [`GiveawayWinners`] -- matches messages containing giveaway winners.
pub const GIVEAWAY_WINNERS: GiveawayWinners = GiveawayWinners;

message_presence_filter!(
    /// Messages containing an invoice.
    InvoiceFilter, invoice, "filters.INVOICE"
);
/// Constant instance of [`InvoiceFilter`] -- matches messages containing an invoice.
pub const INVOICE: InvoiceFilter = InvoiceFilter;

message_presence_filter!(
    /// Messages containing a location.
    LocationFilter, location, "filters.LOCATION"
);
/// Constant instance of [`LocationFilter`] -- matches messages containing a location.
pub const LOCATION: LocationFilter = LocationFilter;

message_presence_filter!(
    /// Messages containing paid media.
    PaidMediaFilter, paid_media, "filters.PAID_MEDIA"
);
/// Constant instance of [`PaidMediaFilter`] -- matches messages containing paid media.
pub const PAID_MEDIA: PaidMediaFilter = PaidMediaFilter;

message_presence_filter!(
    /// Messages containing passport data.
    PassportDataFilter, passport_data, "filters.PASSPORT_DATA"
);
/// Constant instance of [`PassportDataFilter`] -- matches messages containing passport data.
pub const PASSPORT_DATA: PassportDataFilter = PassportDataFilter;

message_presence_filter!(
    /// Messages containing a poll.
    PollFilter, poll, "filters.POLL"
);
/// Constant instance of [`PollFilter`] -- matches messages containing a poll.
pub const POLL: PollFilter = PollFilter;

message_presence_filter!(
    /// Messages that are replies.
    ReplyFilter, reply_to_message, "filters.REPLY"
);
/// Constant instance of [`ReplyFilter`] -- matches messages that are replies.
pub const REPLY: ReplyFilter = ReplyFilter;

message_presence_filter!(
    /// Messages that are replies to a story.
    ReplyToStory, reply_to_story, "filters.REPLY_TO_STORY"
);
/// Constant instance of [`ReplyToStory`] -- matches messages that are replies to a story.
pub const REPLY_TO_STORY: ReplyToStory = ReplyToStory;

message_presence_filter!(
    /// Messages containing a story.
    StoryFilter, story, "filters.STORY"
);
/// Constant instance of [`StoryFilter`] -- matches messages containing a story.
pub const STORY: StoryFilter = StoryFilter;

message_presence_filter!(
    /// Messages containing a venue.
    VenueFilter, venue, "filters.VENUE"
);
/// Constant instance of [`VenueFilter`] -- matches messages containing a venue.
pub const VENUE: VenueFilter = VenueFilter;

message_presence_filter!(
    /// Messages containing a video.
    VideoFilter, video, "filters.VIDEO"
);
/// Constant instance of [`VideoFilter`] -- matches messages containing a video.
pub const VIDEO: VideoFilter = VideoFilter;

message_presence_filter!(
    /// Messages containing a video note.
    VideoNoteFilter, video_note, "filters.VIDEO_NOTE"
);
/// Constant instance of [`VideoNoteFilter`] -- matches messages containing a video note.
pub const VIDEO_NOTE: VideoNoteFilter = VideoNoteFilter;

message_presence_filter!(
    /// Messages containing voice audio.
    VoiceFilter, voice, "filters.VOICE"
);
/// Constant instance of [`VoiceFilter`] -- matches messages containing voice audio.
pub const VOICE: VoiceFilter = VoiceFilter;

message_presence_filter!(
    /// Messages containing suggested_post_info.
    SuggestedPostInfo, suggested_post_info, "filters.SUGGESTED_POST_INFO"
);
/// Constant instance of [`SuggestedPostInfo`] -- matches messages containing suggested post info.
pub const SUGGESTED_POST_INFO: SuggestedPostInfo = SuggestedPostInfo;

// Bool-field presence filters

message_presence_filter!(
    /// Messages with has_media_spoiler set.
    bool: HasMediaSpoiler, has_media_spoiler, "filters.HAS_MEDIA_SPOILER"
);
/// Constant instance of [`HasMediaSpoiler`] -- matches messages with the media spoiler flag set.
pub const HAS_MEDIA_SPOILER: HasMediaSpoiler = HasMediaSpoiler;

message_presence_filter!(
    /// Messages with has_protected_content set.
    bool: HasProtectedContent, has_protected_content, "filters.HAS_PROTECTED_CONTENT"
);
/// Constant instance of [`HasProtectedContent`] -- matches messages with protected content.
pub const HAS_PROTECTED_CONTENT: HasProtectedContent = HasProtectedContent;

message_presence_filter!(
    /// Messages that are automatic forwards.
    bool: IsAutomaticForward, is_automatic_forward, "filters.IS_AUTOMATIC_FORWARD"
);
/// Constant instance of [`IsAutomaticForward`] -- matches automatically forwarded messages.
pub const IS_AUTOMATIC_FORWARD: IsAutomaticForward = IsAutomaticForward;

message_presence_filter!(
    /// Messages that are topic messages.
    bool: IsTopicMessage, is_topic_message, "filters.IS_TOPIC_MESSAGE"
);
/// Constant instance of [`IsTopicMessage`] -- matches messages that are topic messages.
pub const IS_TOPIC_MESSAGE: IsTopicMessage = IsTopicMessage;

message_presence_filter!(
    /// Messages sent from offline.
    bool: IsFromOffline, is_from_offline, "filters.IS_FROM_OFFLINE"
);
/// Constant instance of [`IsFromOffline`] -- matches messages sent from an offline client.
pub const IS_FROM_OFFLINE: IsFromOffline = IsFromOffline;

// sender_boost_count is Option<i32> — present when Some(_)
/// Messages with a non-`None` `sender_boost_count` field.
pub struct SenderBoostCount;

impl Filter for SenderBoostCount {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_message()
            .and_then(|m| m.sender_boost_count)
            .is_some()
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.SENDER_BOOST_COUNT"
    }
}

/// Constant instance of [`SenderBoostCount`] -- matches messages where the sender has a boost count.
pub const SENDER_BOOST_COUNT: SenderBoostCount = SenderBoostCount;

// ---------------------------------------------------------------------------
// Attachment (computed)
// ---------------------------------------------------------------------------

/// Messages containing an effective attachment. Mirrors the computed property
/// from python-telegram-bot.
pub struct AttachmentFilter;

impl Filter for AttachmentFilter {
    fn check_update(&self, update: &Update) -> FilterResult {
        let msg = match update.effective_message() {
            Some(m) => m,
            None => return FilterResult::NoMatch,
        };
        let matched = msg.animation.is_some()
            || msg.audio.is_some()
            || msg.contact.is_some()
            || msg.dice.is_some()
            || msg.document.is_some()
            || msg.game.is_some()
            || msg.invoice.is_some()
            || msg.location.is_some()
            || msg.paid_media.is_some()
            || msg.passport_data.is_some()
            || msg.photo.as_ref().map(|a| !a.is_empty()).unwrap_or(false)
            || msg.poll.is_some()
            || msg.sticker.is_some()
            || msg.story.is_some()
            || msg.venue.is_some()
            || msg.video.is_some()
            || msg.video_note.is_some()
            || msg.voice.is_some();
        if matched {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.ATTACHMENT"
    }
}

/// Constant instance of [`AttachmentFilter`] -- matches messages containing any attachment.
pub const ATTACHMENT: AttachmentFilter = AttachmentFilter;

// ---------------------------------------------------------------------------
// Update-level presence filters
// ---------------------------------------------------------------------------

/// Messages from a forum (topics enabled) chat.
pub struct ForumFilter;

impl Filter for ForumFilter {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_message()
            .and_then(|m| m.chat.is_forum)
            .unwrap_or(false)
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.FORUM"
    }
}

/// Constant instance of [`ForumFilter`] -- matches messages from a forum chat.
pub const FORUM: ForumFilter = ForumFilter;

/// Messages from a direct-messages chat of a channel.
pub struct DirectMessages;

impl Filter for DirectMessages {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_message()
            .and_then(|m| m.chat.is_direct_messages)
            .unwrap_or(false)
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.DIRECT_MESSAGES"
    }
}

/// Constant instance of [`DirectMessages`] -- matches messages from a channel's direct-messages chat.
pub const DIRECT_MESSAGES: DirectMessages = DirectMessages;

/// Messages that have a `from` (from_user) field.
pub struct UserPresence;

impl Filter for UserPresence {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_message()
            .and_then(|m| m.from_user.as_ref())
            .is_some()
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.USER"
    }
}

/// Constant instance of [`UserPresence`] -- matches messages that have a `from_user` field.
pub const USER: UserPresence = UserPresence;

/// Messages from a user who added the bot to the attachment menu.
pub struct UserAttachmentMenu;

impl Filter for UserAttachmentMenu {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_user()
            .and_then(|u| u.added_to_attachment_menu)
            .unwrap_or(false)
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.USER_ATTACHMENT"
    }
}

/// Constant instance of [`UserAttachmentMenu`] -- matches messages from users with the bot in their attachment menu.
pub const USER_ATTACHMENT: UserAttachmentMenu = UserAttachmentMenu;

/// Messages from a Telegram Premium user.
pub struct PremiumUser;

impl Filter for PremiumUser {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_user()
            .and_then(|u| u.is_premium)
            .unwrap_or(false)
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.PREMIUM_USER"
    }
}

/// Constant instance of [`PremiumUser`] -- matches messages from Telegram Premium users.
pub const PREMIUM_USER: PremiumUser = PremiumUser;

/// Messages with a `sender_chat` field present.
pub struct SenderChatPresence;

impl Filter for SenderChatPresence {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_message()
            .and_then(|m| m.sender_chat.as_ref())
            .is_some()
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.SenderChat.ALL"
    }
}

/// Messages with a `via_bot` field present.
pub struct ViaBotPresence;

impl Filter for ViaBotPresence {
    fn check_update(&self, update: &Update) -> FilterResult {
        if update
            .effective_message()
            .and_then(|m| m.via_bot.as_ref())
            .is_some()
        {
            FilterResult::Match
        } else {
            FilterResult::NoMatch
        }
    }

    fn name(&self) -> &str {
        "filters.VIA_BOT"
    }
}

/// Constant instance of [`ViaBotPresence`] -- matches messages sent via an inline bot.
pub const VIA_BOT: ViaBotPresence = ViaBotPresence;

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn text_update(text: &str) -> Update {
        serde_json::from_value(json!({
            "update_id": 1,
            "message": {
                "message_id": 1,
                "date": 0,
                "chat": {"id": 1, "type": "private"},
                "text": text
            }
        }))
        .unwrap()
    }

    fn empty_update() -> Update {
        serde_json::from_value(json!({"update_id": 1})).unwrap()
    }

    #[test]
    fn all_matches_message() {
        assert!(ALL.check_update(&text_update("hello")).is_match());
    }

    #[test]
    fn all_rejects_empty() {
        assert!(!ALL.check_update(&empty_update()).is_match());
    }

    #[test]
    fn and_combinator() {
        let f = F::new(All) & F::new(All);
        assert!(f.check_update(&text_update("hello")).is_match());
    }

    #[test]
    fn or_combinator() {
        let f = F::new(All) | F::new(All);
        assert!(!f.check_update(&empty_update()).is_match());
    }

    #[test]
    fn not_combinator() {
        let f = !F::new(All);
        assert!(!f.check_update(&text_update("hi")).is_match());
    }

    #[test]
    fn xor_both_true_is_false() {
        let f = F::new(All) ^ F::new(All);
        assert!(!f.check_update(&text_update("hi")).is_match());
    }

    #[test]
    fn fn_filter_works() {
        let f = FnFilter::new("always_true", |_| true);
        assert!(f.check_update(&empty_update()).is_match());
    }

    #[test]
    fn presence_animation() {
        let update: Update = serde_json::from_value(json!({
            "update_id": 1,
            "message": {
                "message_id": 1, "date": 0,
                "chat": {"id": 1, "type": "private"},
                "animation": {"file_id": "a", "file_unique_id": "b", "width": 1, "height": 1, "duration": 1}
            }
        })).unwrap();
        assert!(ANIMATION.check_update(&update).is_match());
        assert!(!VIDEO.check_update(&update).is_match());
    }

    #[test]
    fn attachment_computed() {
        let update: Update = serde_json::from_value(json!({
            "update_id": 1,
            "message": {
                "message_id": 1, "date": 0,
                "chat": {"id": 1, "type": "private"},
                "document": {"file_id": "d", "file_unique_id": "e"}
            }
        }))
        .unwrap();
        assert!(ATTACHMENT.check_update(&update).is_match());
    }

    #[test]
    fn effective_message_from_edited() {
        let update: Update = serde_json::from_value(json!({
            "update_id": 1,
            "edited_message": {"message_id": 2, "chat": {"id": 1, "type": "private"}, "date": 0}
        }))
        .unwrap();
        assert!(effective_message(&update).is_some());
    }

    #[test]
    fn effective_user_from_callback() {
        let update: Update = serde_json::from_value(json!({
            "update_id": 1,
            "callback_query": {
                "id": "1",
                "from": {"id": 42, "is_bot": false, "first_name": "Test"},
                "chat_instance": "ci"
            }
        }))
        .unwrap();
        let user = effective_user(&update).unwrap();
        assert_eq!(user.get("id").unwrap().as_i64().unwrap(), 42);
    }

    #[test]
    fn forum_filter() {
        let update: Update = serde_json::from_value(json!({
            "update_id": 1,
            "message": {
                "message_id": 1, "date": 0,
                "chat": {"id": 1, "type": "supergroup", "is_forum": true},
                "text": "hello"
            }
        }))
        .unwrap();
        assert!(FORUM.check_update(&update).is_match());
    }

    #[test]
    fn premium_user_filter() {
        let update: Update = serde_json::from_value(json!({
            "update_id": 1,
            "message": {
                "message_id": 1, "date": 0,
                "chat": {"id": 1, "type": "private"},
                "from": {"id": 1, "is_bot": false, "first_name": "A", "is_premium": true},
                "text": "hi"
            }
        }))
        .unwrap();
        assert!(PREMIUM_USER.check_update(&update).is_match());
    }

    #[test]
    fn filter_result_merge() {
        let a = FilterResult::MatchWithData(HashMap::from([("x".into(), vec!["1".into()])]));
        let b = FilterResult::MatchWithData(HashMap::from([("x".into(), vec!["2".into()])]));
        let merged = a.merge(b);
        if let FilterResult::MatchWithData(m) = merged {
            assert_eq!(m.get("x").unwrap(), &vec!["1".to_owned(), "2".to_owned()]);
        } else {
            panic!("expected MatchWithData");
        }
    }

    #[test]
    fn filter_result_merge_nomatch() {
        let a = FilterResult::Match;
        let b = FilterResult::NoMatch;
        assert_eq!(a.merge(b), FilterResult::NoMatch);
    }

    #[test]
    fn and_combinator_merges_data() {
        // Create two data filters
        let f1 = FnFilter::new("f1", |_| true);
        let f2 = FnFilter::new("f2", |_| true);
        let combined = F::new(f1) & F::new(f2);
        assert!(combined.check_update(&text_update("hi")).is_match());
    }

    #[test]
    fn or_returns_first_match() {
        let f1 = FnFilter::new("f1", |_| true);
        let f2 = FnFilter::new("f2", |_| false);
        let combined = F::new(f1) | F::new(f2);
        assert!(combined.check_update(&text_update("hi")).is_match());
    }

    #[test]
    fn xor_one_true() {
        let f1 = FnFilter::new("f1", |_| true);
        let f2 = FnFilter::new("f2", |_| false);
        let combined = F::new(f1) ^ F::new(f2);
        assert!(combined.check_update(&text_update("hi")).is_match());
    }
}