~nicohman/signal-rs

ref: ad7bba6ed316afe281e38a8327baf7c1bbf824da signal-rs/src/registration.rs -rw-r--r-- 6.1 KiB
ad7bba6e — nicohman Basic attachments 4 months ago
                                                                                
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
use std::str::FromStr;

use crate::*;
use futures::channel::mpsc::{unbounded, UnboundedSender};
use futures::sink::SinkExt;
use futures::stream::StreamExt;
pub enum RegReq {
    Register(String, bool, Option<String>),
    Secondary(String),
    Code(String),
}
#[derive(QObject, Default)]
pub struct RegistrationController {
    base: qt_base_class!(trait QObject),
    register_main: qt_method!(fn(&mut self, number: String, voice: bool)),
    register_main_captcha: qt_method!(fn(&mut self, number: String, voice: bool, captcha: String)),
    register_secondary: qt_method!(fn(&mut self, name: String)),
    confirm_code: qt_method!(fn(&mut self, code: String)),
    registration_result: qt_signal!(reg_type: String, result: i32, error: String),
    init_state: qt_method!(fn(&mut self)),
    req_sender: Option<UnboundedSender<RegReq>>,
}

impl RegistrationController {
    pub fn init_state(&mut self) {
        let (req_sender, mut req_receiver) = unbounded::<RegReq>();
        self.req_sender.replace(req_sender);
        let ptr = QPointer::from(&*self);
        let cb = queued_callback(move |args: (String, i32, String)| {
            ptr.as_pinned()
                .unwrap()
                .borrow()
                .registration_result(args.0, args.1, args.2);
        });
        qmetaobject::future::execute_async(async move {
            let conf: Config = confy::load("signal-rs").unwrap();
            let data_dir = conf
                .data_dir
                .replace("~", home::home_dir().unwrap().to_str().unwrap());
            let config_store = presage::config::SledConfigStore::new(
                PathBuf::from(data_dir).join(PathBuf::from("cstore")),
            )
            .unwrap();
            let mut manager =
                Manager::with_config_store(config_store, ProtocolContext::default()).unwrap();
            loop {
                let next = req_receiver.next().await;
                match next.unwrap() {
                    RegReq::Register(number, voice, captcha) => {
                        if let Ok(phone) =
                            libsignal_service::prelude::phonenumber::PhoneNumber::from_str(
                                number.as_str(),
                            )
                        {
                            let res = manager
                                .register(
                                    libsignal_service::configuration::SignalServers::Production,
                                    phone,
                                    voice,
                                    captcha.as_ref().map(|x| x.as_str()),
                                )
                                .await;
                            if res.is_ok() {
                                cb(("main".into(), 0, "".into()));
                            } else {
                                let err = res.err().unwrap();
                                match err {
                                    presage::Error::CaptchaRequired => {
                                        cb(("main".into(), 1, "".into()));
                                    }
                                    _ => {
                                        cb(("main".into(), 3, err.to_string()));
                                    }
                                }
                            }
                        } else {
                            cb((
                                "main".to_string(),
                                2,
                                "Phone number could not be parsed".to_string(),
                            ));
                        }
                    }

                    RegReq::Secondary(name) => {
                        let res = manager
                            .link_secondary_device(
                                libsignal_service::configuration::SignalServers::Production,
                                name,
                            )
                            .await;
                        if res.is_ok() {
                            cb(("secondary".into(), 0, "".into()));
                        } else {
                            cb(("secondary".into(), 1, res.err().unwrap().to_string()));
                        }
                    }
                    RegReq::Code(code) => {
                        if let Ok(code) = code.as_str().parse::<u32>() {
                            let res = manager.confirm_verification_code(code).await;
                            if res.is_ok() {
                                cb(("verify".into(), 0, "".into()));
                            } else {
                                cb(("verify".into(), 2, res.err().unwrap().to_string()));
                            }
                        } else {
                            cb(("verify".into(), 1, "Code could not be parsed".to_string()))
                        }
                    }
                };
            }
        });
    }

    pub fn register_main(&mut self, number: String, voice: bool) {
        self.register(number, voice, None);
    }

    pub fn register_main_captcha(&mut self, number: String, voice: bool, captcha: String) {
        self.register(number, voice, Some(captcha));
    }

    pub fn register(&mut self, number: String, voice: bool, captcha: Option<String>) {
        let mut sender = self.req_sender.as_ref().unwrap().clone();
        qmetaobject::execute_async(async move {
            sender
                .send(RegReq::Register(number, voice, captcha))
                .await
                .expect("Couldn't send RegReq");
        });
    }

    pub fn register_secondary(&mut self, name: String) {
        let mut sender = self.req_sender.as_ref().unwrap().clone();
        qmetaobject::execute_async(async move {
            sender
                .send(RegReq::Secondary(name))
                .await
                .expect("Couldn't send RegReq");
        });
    }

    pub fn confirm_code(&mut self, code: String) {
        let mut sender = self.req_sender.as_ref().unwrap().clone();
        qmetaobject::execute_async(async move {
            sender
                .send(RegReq::Code(code))
                .await
                .expect("Couldn't send RegReq");
        });
    }
}