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
use std::ops::Deref;

use futures_util::StreamExt;
use gtk::{
    gdk, glib,
    glib::{clone, closure_local},
    prelude::*,
    subclass::prelude::*,
};
use matrix_sdk::encryption::verification::{
    CancelInfo, Emoji, QrVerification, QrVerificationData, QrVerificationState, SasState,
    SasVerification, Verification, VerificationRequest, VerificationRequestState,
};
use qrcode::QrCode;
use ruma::{
    events::key::verification::{cancel::CancelCode, VerificationMethod, REQUEST_RECEIVED_TIMEOUT},
    OwnedDeviceId,
};
use tracing::{debug, error};

use super::{load_supported_verification_methods, VerificationKey};
use crate::{
    contrib::Camera,
    prelude::*,
    session::model::{Member, Membership, Room, Session, User},
    spawn, spawn_tokio,
    utils::BoundConstructOnlyObject,
};

/// A boxed [`VerificationRequest`].
#[derive(Clone, Debug, glib::Boxed)]
#[boxed_type(name = "BoxedVerificationRequest")]
pub struct BoxedVerificationRequest(pub VerificationRequest);

impl Deref for BoxedVerificationRequest {
    type Target = VerificationRequest;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[glib::flags(name = "VerificationSupportedMethods")]
pub enum VerificationSupportedMethods {
    SAS = 0b00000001,
    QR_SHOW = 0b00000010,
    QR_SCAN = 0b00000100,
}

impl<'a> From<&'a [VerificationMethod]> for VerificationSupportedMethods {
    fn from(methods: &'a [VerificationMethod]) -> Self {
        let mut result = Self::empty();

        for method in methods {
            match method {
                VerificationMethod::SasV1 => result.insert(Self::SAS),
                VerificationMethod::QrCodeScanV1 => result.insert(Self::QR_SCAN),
                VerificationMethod::QrCodeShowV1 => result.insert(Self::QR_SHOW),
                _ => {}
            }
        }

        result
    }
}

impl Default for VerificationSupportedMethods {
    fn default() -> Self {
        Self::empty()
    }
}

#[derive(Debug, Default, Eq, PartialEq, Clone, Copy, glib::Enum)]
#[repr(u32)]
#[enum_type(name = "VerificationState")]
pub enum VerificationState {
    /// We created and sent the request.
    ///
    /// We must wait for the other user/device to accept it.
    #[default]
    Created,
    /// The other user/device sent us a request.
    ///
    /// We should ask the user if they want to accept it.
    Requested,
    /// We support none of the other user's verification methods.
    NoSupportedMethods,
    /// The request was accepted.
    ///
    /// We should ask the user to choose a method.
    Ready,
    /// An SAS verification was started.
    ///
    /// We should show the emojis and ask the user to confirm that they match.
    SasConfirm,
    /// The user wants to scan a QR Code.
    QrScan,
    /// The user scanned a QR Code.
    QrScanned,
    /// Our QR Code was scanned.
    ///
    /// We should ask the user to confirm that the QR Code was scanned
    /// successfully.
    QrConfirm,
    /// The verification was successful.
    Done,
    /// The verification was cancelled.
    Cancelled,
    /// The verification was automatically dismissed.
    ///
    /// Happens when a received request is not accepted by us after 2 minutes.
    Dismissed,
    /// The verification was happening in-room but the room was left.
    RoomLeft,
    /// An unexpected error happened.
    Error,
}

mod imp {
    use std::{
        cell::{Cell, OnceCell, RefCell},
        marker::PhantomData,
    };

    use glib::subclass::Signal;
    use once_cell::sync::Lazy;

    use super::*;

    #[derive(Default, glib::Properties)]
    #[properties(wrapper_type = super::IdentityVerification)]
    pub struct IdentityVerification {
        /// The SDK's verification request.
        #[property(set = Self::set_request, construct_only)]
        pub request: OnceCell<BoxedVerificationRequest>,
        pub request_changes_abort_handle: RefCell<Option<tokio::task::AbortHandle>>,
        /// The SDK's verification, if one was started.
        pub verification: RefCell<Option<Verification>>,
        pub verification_changes_abort_handle: RefCell<Option<tokio::task::AbortHandle>>,
        /// The user to verify.
        #[property(get, set = Self::set_user, construct_only)]
        pub user: BoundConstructOnlyObject<User>,
        /// The room of this verification, if any.
        #[property(get, set = Self::set_room, construct_only)]
        pub room: glib::WeakRef<Room>,
        membership_handler: RefCell<Option<glib::SignalHandlerId>>,
        /// The state of this verification
        #[property(get, set = Self::set_state, construct_only, builder(VerificationState::default()))]
        pub state: Cell<VerificationState>,
        /// Whether the verification request was accepted.
        ///
        /// It means that the verification reached at least the `Ready` state.
        #[property(get)]
        pub was_accepted: Cell<bool>,
        /// Whether this verification is finished.
        #[property(get = Self::is_finished)]
        is_finished: PhantomData<bool>,
        /// The supported methods of the verification request.
        #[property(get = Self::supported_methods, type = VerificationSupportedMethods)]
        pub supported_methods: RefCell<Vec<VerificationMethod>>,
        /// The flow ID of this verification.
        #[property(get = Self::flow_id)]
        flow_id: PhantomData<String>,
        /// The time and date when the verification request was received.
        #[property(get)]
        pub received_time: OnceCell<glib::DateTime>,
        pub received_timeout_source: RefCell<Option<glib::SourceId>>,
        /// The display name of this verification.
        #[property(get = Self::display_name)]
        display_name: PhantomData<String>,
        /// The QR Code, if the `QrCodeShowV1` method is supported.
        pub qr_code: RefCell<Option<QrCode>>,
        /// The camera paintable, if the user wants to scan a QR Code and we
        /// have access to the camera.
        #[property(get)]
        pub camera_paintable: RefCell<Option<gdk::Paintable>>,
        /// Whether we started the SAS verification.
        #[property(get)]
        pub we_started_sas: Cell<bool>,
        /// Whether this verification was viewed by the user.
        #[property(get, set = Self::set_was_viewed, explicit_notify)]
        pub was_viewed: Cell<bool>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for IdentityVerification {
        const NAME: &'static str = "IdentityVerification";
        type Type = super::IdentityVerification;
    }

    #[glib::derived_properties]
    impl ObjectImpl for IdentityVerification {
        fn signals() -> &'static [Signal] {
            static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
                vec![
                    // The SAS data changed.
                    Signal::builder("sas-data-changed").build(),
                    // The cancel info changed.
                    Signal::builder("cancel-info-changed").build(),
                    // The verification has been replaced by a new one.
                    Signal::builder("replaced")
                        .param_types([super::IdentityVerification::static_type()])
                        .build(),
                    // The verification is done, but has not changed its state yes.
                    //
                    // Return `glib::Propagation::Stop` in a signal handler to prevent the state
                    // from changing to `VerificationState::Done`. Can be used to replace the last
                    // screen of `IdentityVerificationView`.
                    Signal::builder("done").return_type::<bool>().build(),
                    // The verification can be dismissed.
                    Signal::builder("dismiss").build(),
                    // The verification should be removed from the verification list.
                    Signal::builder("remove-from-list").build(),
                ]
            });
            SIGNALS.as_ref()
        }

        fn dispose(&self) {
            let obj = self.obj();

            if let Some(handler) = self.membership_handler.take() {
                if let Some(room) = self.room.upgrade() {
                    room.own_member().disconnect(handler);
                }
            }
            if let Some(handle) = self.request_changes_abort_handle.take() {
                handle.abort();
            }
            if let Some(handle) = self.verification_changes_abort_handle.take() {
                handle.abort();
            }
            if let Some(source) = self.received_timeout_source.take() {
                source.remove();
            }

            let request = obj.request().clone();
            if !request.is_done() && !request.is_passive() && !request.is_cancelled() {
                spawn_tokio!(async move {
                    if let Err(error) = request.cancel().await {
                        error!("Could not cancel verification request on dispose: {error}");
                    }
                });
            }
        }
    }

    impl IdentityVerification {
        /// Set the SDK's verification request.
        fn set_request(&self, request: BoxedVerificationRequest) {
            self.request.set(request.clone()).unwrap();

            let Ok(datetime) = glib::DateTime::now_local() else {
                error!("Could not get current GDateTime");
                return;
            };

            // Set up the timeout if we received the request and it is not accepted yet.
            if matches!(request.state(), VerificationRequestState::Requested { .. }) {
                let source_id = glib::timeout_add_local_once(
                    REQUEST_RECEIVED_TIMEOUT,
                    clone!(@weak self as imp => move || {
                        imp.received_timeout_source.take();

                        imp.set_state(VerificationState::Dismissed);
                        imp.obj().dismiss();
                    }),
                );
                self.received_timeout_source.replace(Some(source_id));
            }

            self.received_time.set(datetime).unwrap();
        }

        /// Set the user to verify.
        fn set_user(&self, user: User) {
            let mut handlers = Vec::new();

            // If the user is a room member, it means it's an in-room verification, we need
            // to keep track of their name since it's used as the display name.
            if user.is::<Member>() {
                let obj = self.obj();
                let display_name_handler =
                    user.connect_display_name_notify(clone!(@weak obj => move |_| {
                        obj.notify_display_name();
                    }));
                handlers.push(display_name_handler);
            }

            self.user.set(user, handlers);
        }

        /// Set the room of the verification, if any.
        fn set_room(&self, room: Option<&Room>) {
            let Some(room) = room else {
                // Nothing to do if there is no room.
                return;
            };

            let handler = room.own_member().connect_membership_notify(
                clone!(@weak self as imp => move |own_member| {
                    if matches!(own_member.membership(), Membership::Leave | Membership::Ban) {
                        // If the user is not in the room anymore, nothing can be done with this verification.
                        imp.set_state(VerificationState::RoomLeft);

                        if let Some(handler) = imp.membership_handler.take() {
                            own_member.disconnect(handler);
                        }
                    }
                }),
            );
            self.membership_handler.replace(Some(handler));

            self.room.set(Some(room));
        }

        /// Set the state of this verification.
        pub fn set_state(&self, state: VerificationState) {
            if self.state.get() == state {
                return;
            }
            let obj = self.obj();

            if state == VerificationState::Done {
                let ret = obj.emit_by_name::<bool>("done", &[]);
                if glib::Propagation::from(ret).is_stop() {
                    return;
                }
            }

            self.state.set(state);

            obj.notify_state();

            if self.is_finished() {
                obj.notify_is_finished();
            }
        }

        /// Whether this verification is finished.
        fn is_finished(&self) -> bool {
            matches!(
                self.state.get(),
                VerificationState::Cancelled
                    | VerificationState::Dismissed
                    | VerificationState::Done
                    | VerificationState::Error
                    | VerificationState::RoomLeft
            )
        }

        /// The supported methods of this verifications.
        fn supported_methods(&self) -> VerificationSupportedMethods {
            self.supported_methods.borrow().as_slice().into()
        }

        /// The display name of this verification request.
        fn display_name(&self) -> String {
            let user = self.user.obj();

            if !user.is_own_user() {
                user.display_name()
            } else {
                // TODO: give this request a name based on the device
                "Login Request".to_string()
            }
        }

        /// The flow ID of this verification request.
        fn flow_id(&self) -> String {
            self.request.get().unwrap().flow_id().to_owned()
        }

        /// Set whether this verification was viewed by the user.
        fn set_was_viewed(&self, was_viewed: bool) {
            if !was_viewed {
                // The user cannot unview the verification.
                return;
            }

            self.was_viewed.set(was_viewed);
            self.obj().notify_was_viewed();
        }
    }
}

glib::wrapper! {
    /// An identity verification request.
    pub struct IdentityVerification(ObjectSubclass<imp::IdentityVerification>);
}

impl IdentityVerification {
    /// Construct a verification for the given request.
    pub async fn new(request: VerificationRequest, user: &User, room: Option<&Room>) -> Self {
        let obj = glib::Object::builder::<Self>()
            .property("request", BoxedVerificationRequest(request))
            .property("user", user)
            .property("room", room)
            .build();

        obj.init().await;
        obj
    }

    /// The current session.
    pub fn session(&self) -> Session {
        self.user().session()
    }

    /// The SDK's verification request.
    fn request(&self) -> &VerificationRequest {
        self.imp().request.get().unwrap()
    }

    /// The unique identifying key of this verification.
    pub fn key(&self) -> VerificationKey {
        VerificationKey::from_request(self.request())
    }

    /// Whether this is a self-verification.
    pub fn is_self_verification(&self) -> bool {
        self.request().is_self_verification()
    }

    /// The ID of the other device that is being verified.
    pub fn other_device_id(&self) -> Option<OwnedDeviceId> {
        let verification = match self.request().state() {
            VerificationRequestState::Requested {
                other_device_id, ..
            }
            | VerificationRequestState::Ready {
                other_device_id, ..
            } => return Some(other_device_id),
            VerificationRequestState::Transitioned { verification } => verification,
            VerificationRequestState::Created { .. }
            | VerificationRequestState::Done
            | VerificationRequestState::Cancelled(_) => return None,
        };

        match verification {
            Verification::SasV1(sas) => Some(sas.other_device().device_id().to_owned()),
            Verification::QrV1(qr) => Some(qr.other_device().device_id().to_owned()),
            _ => None,
        }
    }

    /// Set whether this request was accepted.
    fn set_was_accepted(&self, was_accepted: bool) {
        if !was_accepted || self.was_accepted() {
            // The state cannot go backwards.
            return;
        }

        self.imp().was_accepted.set(true);
        self.notify_was_accepted();
    }

    /// Information about the verification cancellation, if any.
    pub fn cancel_info(&self) -> Option<CancelInfo> {
        self.request().cancel_info()
    }

    /// Initialize this verification to listen to changes in the request's
    /// state.
    async fn init(&self) {
        let request = self.request();

        let obj_weak = glib::SendWeakRef::from(self.downgrade());
        let fut = request.changes().for_each(move |state| {
            let obj_weak = obj_weak.clone();
            async move {
                let ctx = glib::MainContext::default();
                ctx.spawn(async move {
                    spawn!(async move {
                        if let Some(obj) = obj_weak.upgrade() {
                            obj.handle_request_state(state).await;
                        }
                    });
                });
            }
        });
        let handle = spawn_tokio!(fut).abort_handle();

        self.imp()
            .request_changes_abort_handle
            .replace(Some(handle));

        let state = request.state();
        self.handle_request_state(state).await;
    }

    /// Handle a change in the request's state.
    async fn handle_request_state(&self, state: VerificationRequestState) {
        let imp = self.imp();
        let request = self.request();

        if !matches!(state, VerificationRequestState::Requested { .. }) {
            if let Some(source) = imp.received_timeout_source.take() {
                source.remove();
            }
        }
        if !matches!(
            state,
            VerificationRequestState::Created { .. } | VerificationRequestState::Requested { .. }
        ) {
            self.set_was_accepted(true);
        }

        match state {
            VerificationRequestState::Created { .. } => {}
            VerificationRequestState::Requested { their_methods, .. } => {
                let our_methods = load_supported_verification_methods().await;
                let supported_methods = intersect_methods(our_methods, their_methods);

                if supported_methods.is_empty() {
                    imp.set_state(VerificationState::NoSupportedMethods);
                } else {
                    imp.set_state(VerificationState::Requested);
                }
            }
            VerificationRequestState::Ready {
                their_methods,
                our_methods,
                ..
            } => {
                let mut supported_methods = intersect_methods(our_methods, their_methods);

                // Remove the reciprocate method, it's not a flow in itself.
                let reciprocate_idx = supported_methods
                    .iter()
                    .enumerate()
                    .find_map(|(idx, m)| (*m == VerificationMethod::ReciprocateV1).then_some(idx));
                if let Some(idx) = reciprocate_idx {
                    supported_methods.remove(idx);
                }

                // Check that we can get the QR Code, to avoid exposing the method if it doesn't
                // work.
                let show_qr_idx = supported_methods
                    .iter()
                    .enumerate()
                    .find_map(|(idx, m)| (*m == VerificationMethod::QrCodeShowV1).then_some(idx));
                if let Some(idx) = show_qr_idx {
                    if !self.load_qr_code().await {
                        supported_methods.remove(idx);
                    }
                }

                if supported_methods.is_empty() {
                    // This should not happen.
                    error!("Invalid verification: no methods are supported by both sessions, cancelling…");
                    if self.cancel().await.is_err() {
                        imp.set_state(VerificationState::NoSupportedMethods);
                    }
                } else {
                    self.set_supported_methods(supported_methods.clone());

                    if supported_methods.len() == 1
                        && !request.we_started()
                        && supported_methods[0] == VerificationMethod::SasV1
                    {
                        // We only go forward for SAS, because QrCodeShow is the
                        // same screen as the one to choose a method and we need
                        // to tell the user we are going to need to access the
                        // camera for QrCodeScan.
                        if self.start_sas().await.is_ok() {
                            return;
                        }
                    }

                    imp.set_state(VerificationState::Ready);
                }
            }
            VerificationRequestState::Transitioned { verification } => {
                self.set_verification(verification).await;
            }
            VerificationRequestState::Done => {
                imp.set_state(VerificationState::Done);
            }
            VerificationRequestState::Cancelled(info) => self.handle_cancelled_state(info),
        }
    }

    /// Handle when the request was cancelled.
    fn handle_cancelled_state(&self, cancel_info: CancelInfo) {
        debug!("Verification was cancelled: {cancel_info:?}");
        let cancel_code = cancel_info.cancel_code();

        if cancel_info.cancelled_by_us() && *cancel_code == CancelCode::User {
            // We should handle this already.
            return;
        }

        if *cancel_code == CancelCode::Accepted && !self.was_viewed() {
            // We can safely remove it.
            self.dismiss();
            return;
        }

        self.emit_by_name::<()>("cancel-info-changed", &[]);
        self.imp().set_state(VerificationState::Cancelled);
    }

    /// Cancel the verification request.
    ///
    /// This can be used to decline the request or cancel it at any time.
    pub async fn cancel(&self) -> Result<(), matrix_sdk::Error> {
        let request = self.request().clone();

        if request.is_done() || request.is_passive() || request.is_cancelled() {
            return Err(matrix_sdk::Error::UnknownError(
                "Cannot cancel request that is already finished".into(),
            ));
        }

        let handle = spawn_tokio!(async move { request.cancel().await });

        match handle.await.unwrap() {
            Ok(()) => {
                self.dismiss();
                Ok(())
            }
            Err(error) => {
                error!("Could not cancel verification request: {error}");
                Err(error)
            }
        }
    }

    /// Accept the verification request.
    pub async fn accept(&self) -> Result<(), ()> {
        let request = self.request().clone();

        let VerificationRequestState::Requested { their_methods, .. } = request.state() else {
            error!("Cannot accept verification that is not in the requested state");
            return Err(());
        };
        let our_methods = load_supported_verification_methods().await;
        let methods = intersect_methods(our_methods, their_methods);

        let handle = spawn_tokio!(async move { request.accept_with_methods(methods).await });

        match handle.await.unwrap() {
            Ok(()) => Ok(()),
            Err(error) => {
                error!("Could not accept verification request: {error}");
                Err(())
            }
        }
    }

    /// Set the supported methods of this verification.
    fn set_supported_methods(&self, supported_methods: Vec<VerificationMethod>) {
        let imp = self.imp();
        if *imp.supported_methods.borrow() == supported_methods {
            return;
        }

        imp.supported_methods.replace(supported_methods);
        self.notify_supported_methods();
    }

    /// Go back to the state to choose a verification method.
    pub fn choose_method(&self) {
        self.imp().set_state(VerificationState::Ready);
    }

    /// Set the SDK's Verification.
    async fn set_verification(&self, verification: Verification) {
        let imp = self.imp();

        if let Some(handle) = imp.verification_changes_abort_handle.take() {
            handle.abort();
        };

        let obj_weak = glib::SendWeakRef::from(self.downgrade());
        let handle = match &verification {
            Verification::SasV1(sas_verification) => {
                let fut = sas_verification.changes().for_each(move |state| {
                    let obj_weak = obj_weak.clone();
                    async move {
                        let ctx = glib::MainContext::default();
                        ctx.spawn(async move {
                            spawn!(async move {
                                if let Some(obj) = obj_weak.upgrade() {
                                    obj.handle_sas_verification_state(state).await;
                                }
                            });
                        });
                    }
                });
                spawn_tokio!(fut).abort_handle()
            }
            Verification::QrV1(qr_verification) => {
                let fut = qr_verification.changes().for_each(move |state| {
                    let obj_weak = obj_weak.clone();
                    async move {
                        let ctx = glib::MainContext::default();
                        ctx.spawn(async move {
                            spawn!(async move {
                                if let Some(obj) = obj_weak.upgrade() {
                                    obj.handle_qr_verification_state(state);
                                }
                            });
                        });
                    }
                });
                spawn_tokio!(fut).abort_handle()
            }
            _ => {
                error!("We only support SAS and QR verification");
                imp.set_state(VerificationState::Error);
                return;
            }
        };

        imp.verification.replace(Some(verification.clone()));
        imp.verification_changes_abort_handle.replace(Some(handle));

        match verification {
            Verification::SasV1(sas_verification) => {
                self.handle_sas_verification_state(sas_verification.state())
                    .await;
            }
            Verification::QrV1(qr_verification) => {
                self.handle_qr_verification_state(qr_verification.state())
            }
            _ => unreachable!(),
        }
    }

    /// Handle a change in the QR verification's state.
    fn handle_qr_verification_state(&self, state: QrVerificationState) {
        let imp = self.imp();

        match state {
            QrVerificationState::Started => {}
            QrVerificationState::Scanned => imp.set_state(VerificationState::QrConfirm),
            QrVerificationState::Confirmed => {}
            QrVerificationState::Reciprocated => {}
            QrVerificationState::Done { .. } => imp.set_state(VerificationState::Done),
            QrVerificationState::Cancelled(info) => self.handle_cancelled_state(info),
        }
    }

    /// The SDK's QR verification, if one was started.
    fn qr_verification(&self) -> Option<QrVerification> {
        match self.imp().verification.borrow().as_ref()? {
            Verification::QrV1(v) => Some(v.clone()),
            _ => None,
        }
    }

    /// Handle a change in the SAS verification's state.
    async fn handle_sas_verification_state(&self, state: SasState) {
        let Some(sas_verification) = self.sas_verification() else {
            return;
        };
        let imp = self.imp();

        match state {
            SasState::Started { .. } => {
                if !self.we_started_sas() {
                    let handle = spawn_tokio!(async move { sas_verification.accept().await });
                    if let Err(error) = handle.await.unwrap() {
                        error!("Could not accept SAS verification: {error}");
                        imp.set_state(VerificationState::Error);
                    }
                }
            }
            SasState::Accepted { .. } => {}
            SasState::KeysExchanged { .. } => {
                self.emit_by_name::<()>("sas-data-changed", &[]);
                imp.set_state(VerificationState::SasConfirm);
            }
            SasState::Confirmed => {}
            SasState::Done { .. } => imp.set_state(VerificationState::Done),
            SasState::Cancelled(info) => self.handle_cancelled_state(info),
        }
    }

    /// The SDK's SAS verification, if one was started.
    fn sas_verification(&self) -> Option<SasVerification> {
        match self.imp().verification.borrow().as_ref()? {
            Verification::SasV1(v) => Some(v.clone()),
            _ => None,
        }
    }

    /// Whether the current SAS verification supports emoji.
    pub fn sas_supports_emoji(&self) -> bool {
        match self.imp().verification.borrow().as_ref() {
            Some(Verification::SasV1(v)) => v.supports_emoji(),
            _ => false,
        }
    }

    /// The list of emojis for the current SAS verification, if any.
    pub fn sas_emoji(&self) -> Option<[Emoji; 7]> {
        match self.imp().verification.borrow().as_ref()? {
            Verification::SasV1(v) => v.emoji(),
            _ => None,
        }
    }

    /// The list of decimals for the current SAS verification, if any.
    pub fn sas_decimals(&self) -> Option<(u16, u16, u16)> {
        match self.imp().verification.borrow().as_ref()? {
            Verification::SasV1(v) => v.decimals(),
            _ => None,
        }
    }

    /// Set whether we started the SAS verification.
    fn set_we_started_sas(&self, we_started: bool) {
        self.imp().we_started_sas.set(we_started);
        self.notify_we_started_sas();
    }

    /// Try to load the QR Code.
    ///
    /// Return `true` if it was successfully loaded, `false` otherwise.
    async fn load_qr_code(&self) -> bool {
        let request = self.request().clone();

        let handle = spawn_tokio!(async move { request.generate_qr_code().await });

        let qr_verification = match handle.await.unwrap() {
            Ok(Some(qr_verification)) => qr_verification,
            Ok(None) => {
                error!("Could not start QR verification generation: unknown reason");
                return false;
            }
            Err(error) => {
                error!("Could not start QR verification generation: {error}");
                return false;
            }
        };

        match qr_verification.to_qr_code() {
            Ok(qr_code) => {
                self.imp().qr_code.replace(Some(qr_code));
                true
            }
            Err(error) => {
                error!("Could not generate verification QR code: {error}");
                false
            }
        }
    }

    /// The QR Code, if the `QrCodeShowV1` method is supported.
    pub fn qr_code(&self) -> Option<QrCode> {
        self.imp().qr_code.borrow().clone()
    }

    /// Whether we have the QR code.
    pub fn has_qr_code(&self) -> bool {
        self.imp().qr_code.borrow().is_some()
    }

    /// Start a QR Code scan.
    pub async fn start_qr_code_scan(&self) -> Result<(), ()> {
        let imp = self.imp();

        match Camera::default().paintable().await {
            Some(paintable) => {
                imp.camera_paintable.replace(Some(paintable.upcast()));
                self.notify_camera_paintable();

                imp.set_state(VerificationState::QrScan);

                Ok(())
            }
            None => Err(()),
        }
    }

    /// The QR Code was scanned.
    pub async fn qr_code_scanned(&self, data: QrVerificationData) -> Result<(), ()> {
        self.imp().set_state(VerificationState::QrScanned);
        let request = self.request().clone();

        let handle = spawn_tokio!(async move { request.scan_qr_code(data).await });

        match handle.await.unwrap() {
            Ok(Some(_)) => Ok(()),
            Ok(None) => {
                error!("Could not validate scanned verification QR code: unknown reason");
                Err(())
            }
            Err(error) => {
                error!("Could not validate scanned verification QR code: {error}");
                Err(())
            }
        }
    }

    /// Confirm that the QR Code was scanned by the other party.
    pub async fn confirm_qr_code_scanned(&self) -> Result<(), ()> {
        let Some(qr_verification) = self.qr_verification() else {
            error!("Cannot confirm QR Code scan without an ongoing QR verification");
            return Err(());
        };

        let handle = spawn_tokio!(async move { qr_verification.confirm().await });

        match handle.await.unwrap() {
            Ok(()) => Ok(()),
            Err(error) => {
                error!("Could not confirm scanned verification QR code: {error}");
                Err(())
            }
        }
    }

    /// Start a SAS verification.
    pub async fn start_sas(&self) -> Result<(), ()> {
        let request = self.request().clone();

        // We need to set this first, to make sure we have it when we handle the state
        // change.
        self.set_we_started_sas(true);

        let handle = spawn_tokio!(async move { request.start_sas().await });

        match handle.await.unwrap() {
            Ok(Some(_)) => Ok(()),
            Ok(None) => {
                error!("Could not start SAS verification: unknown reason");
                // Unset it because it didn't work.
                self.set_we_started_sas(false);
                Err(())
            }
            Err(error) => {
                error!("Could not start SAS verification: {error}");
                // Unset it because it didn't work.
                self.set_we_started_sas(false);
                Err(())
            }
        }
    }

    /// The SAS data does not match.
    pub async fn sas_mismatch(&self) -> Result<(), ()> {
        let Some(sas_verification) = self.sas_verification() else {
            error!("Cannot send SAS mismatch without an ongoing SAS verification");
            return Err(());
        };

        let handle = spawn_tokio!(async move { sas_verification.mismatch().await });

        match handle.await.unwrap() {
            Ok(()) => Ok(()),
            Err(error) => {
                error!("Could not send SAS verification mismatch: {error}");
                Err(())
            }
        }
    }

    /// The SAS data matches.
    pub async fn sas_match(&self) -> Result<(), ()> {
        let Some(sas_verification) = self.sas_verification() else {
            error!("Cannot send SAS match without an ongoing SAS verification");
            return Err(());
        };

        let handle = spawn_tokio!(async move { sas_verification.confirm().await });

        match handle.await.unwrap() {
            Ok(()) => Ok(()),
            Err(error) => {
                error!("Could not send SAS verification match: {error}");
                Err(())
            }
        }
    }

    /// Restart this verification with a new one to the same user.
    pub async fn restart(&self) -> Result<Self, ()> {
        let user = self.user();
        let verification_list = user.session().verification_list();

        let new_user = (!self.is_self_verification()).then_some(user);
        let new_verification = verification_list.create(new_user).await?;

        self.emit_by_name::<()>("replaced", &[&new_verification]);

        // If we restart because an unexpected error happened, try to cancel it.
        if self.cancel().await.is_err() {
            self.dismiss();
        }

        Ok(new_verification)
    }

    /// The verification can be dismissed.
    ///
    /// Also removes it from the verification list.
    pub fn dismiss(&self) {
        self.remove_from_list();
        self.emit_by_name::<()>("dismiss", &[]);
    }

    /// The verification can be removed from the verification list.
    ///
    /// You will usually want to use [`IdentityVerification::dismiss()`] because
    /// the interface listens for the signal it emits, and it calls this method
    /// internally.
    pub fn remove_from_list(&self) {
        self.emit_by_name::<()>("remove-from-list", &[]);
    }

    /// Connect to the signal emitted when the SAS data changed.
    pub fn connect_sas_data_changed<F: Fn(&Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
        self.connect_closure(
            "sas-data-changed",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }

    /// Connect to the signal emitted when the cancel info changed.
    pub fn connect_cancel_info_changed<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> glib::SignalHandlerId {
        self.connect_closure(
            "cancel-info-changed",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }

    /// Connect to the signal emitted when the verification has been replaced.
    ///
    /// The second parameter to the function is the new verification.
    pub fn connect_replaced<F: Fn(&Self, &Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
        self.connect_closure(
            "replaced",
            true,
            closure_local!(move |obj: Self, new_verification: Self| {
                f(&obj, &new_verification);
            }),
        )
    }

    /// Connect to the signal emitted when the verification is done, but its
    /// state does not reflect that yet.
    ///
    /// Return `glib::Propagation::Stop` in the signal handler to prevent the
    /// state from changing to `VerificationState::Done`. Can be used to replace
    /// the last screen of `IdentityVerificationView`.
    pub fn connect_done<F: Fn(&Self) -> glib::Propagation + 'static>(
        &self,
        f: F,
    ) -> glib::SignalHandlerId {
        self.connect_closure(
            "done",
            true,
            closure_local!(move |obj: Self| {
                let ret = f(&obj);

                if ret.is_stop() {
                    obj.stop_signal_emission_by_name("done");
                }

                bool::from(ret)
            }),
        )
    }

    /// Connect to the signal emitted when the verification can be dismissed.
    pub fn connect_dismiss<F: Fn(&Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
        self.connect_closure(
            "dismiss",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }

    /// Connect to the signal emitted when the verification can be removed from
    /// the verification list.
    pub(super) fn connect_remove_from_list<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> glib::SignalHandlerId {
        self.connect_closure(
            "remove-from-list",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }
}

/// Get the intersection or our methods and their methods.
fn intersect_methods(
    our_methods: Vec<VerificationMethod>,
    their_methods: Vec<VerificationMethod>,
) -> Vec<VerificationMethod> {
    let mut supported_methods = our_methods;

    supported_methods.retain(|m| match m {
        VerificationMethod::SasV1 => their_methods.contains(&VerificationMethod::SasV1),
        VerificationMethod::QrCodeScanV1 => {
            their_methods.contains(&VerificationMethod::QrCodeShowV1)
                && their_methods.contains(&VerificationMethod::ReciprocateV1)
        }
        VerificationMethod::QrCodeShowV1 => {
            their_methods.contains(&VerificationMethod::QrCodeScanV1)
                && their_methods.contains(&VerificationMethod::ReciprocateV1)
        }
        VerificationMethod::ReciprocateV1 => {
            (their_methods.contains(&VerificationMethod::QrCodeShowV1)
                || their_methods.contains(&VerificationMethod::QrCodeScanV1))
                && their_methods.contains(&VerificationMethod::ReciprocateV1)
        }
        _ => false,
    });

    supported_methods
}