why2-chat 2.1.4

Lightweight, fast and secure chat application powered by WHY2 encryption.
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
/*
This is part of WHY2
Copyright (C) 2022-2026 Václav Šmejkal

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

use std::
{
    io::Error,
    time::Instant,
};

use crossterm::event::
{
    KeyCode,
    KeyEvent,
    KeyModifiers,
};

use zeroize::Zeroizing;

use tokio::
{
    sync::mpsc::Sender,
    net::tcp::{ OwnedReadHalf, OwnedWriteHalf },
};

use crate::
{
    config,
    options,
    network::client,
};

use super::
{
    consts,
    input::InputBuffer,
    state::App,
};

//TYPES
//ONE FINISHED DIAL ATTEMPT, NUMBERED
pub type ConnectResult = (u64, Result<(OwnedReadHalf, OwnedWriteHalf), Error>);

//ENUMS
pub enum Action //WHAT THE LOOP HAS TO DO AFTER A KEYSTROKE
{
    None,
    Connect,
    Submit, //AN ANSWERED IDENTITY STEP
    Quit,
}

#[derive(Clone, Copy, PartialEq)] //WHICH OF THE THREE THINGS THE BOX IS ASKING FOR
pub enum Stage
{
    Address,
    Username,
    Password { register: bool },
}

//STRUCTS
pub struct Login //THE CONNECT PROMPT
{
    pub input: InputBuffer,
    pub stage: Stage,
    pub busy: bool,            //A DIAL, OR AN ANSWER THE SERVER HAS NOT REPLIED TO YET
    pub connected: bool,       //THE SOCKET IS OPEN
    pub error: Option<String>, //WHY THE LAST ONE DID NOT WORK
    pub hint: Option<String>,  //THE SERVER'S RULES FOR THE STEP ON SCREEN
    attempt: u64,              //ONLY THE NEWEST ATTEMPT'S RESULT IS ACCEPTED
}

//WHAT AN AUTOMATIC RE-DIAL NEEDS AFTER A DROPPED SESSION
#[derive(Default)]
pub struct Reconnect
{
    credentials: Option<(String, Zeroizing<String>)>, //WHAT GOT US IN, ONCE IT ACTUALLY DID
    typed: (String, Zeroizing<String>),               //THE ANSWERS OF THE STEPS IN FLIGHT
    due: Option<Instant>,                             //WHEN TO DIAL AGAIN
    left: u32,                                        //ATTEMPTS BEFORE IT GIVES UP AND WAITS FOR A KEY
    answers: u32,                                     //REPLIES THIS DIAL MAY STILL REPLAY - USERNAME AND PASSWORD
    retrying: bool,                                   //THE BOX IS BUSY BECAUSE OF US, NOT BECAUSE OF A KEYPRESS
    pub submit: bool,                                 //AN ANSWER IS IN THE FIELD FOR THE TICK TO SEND
}

//IMPLEMENTATIONS
impl Reconnect
{
    //KEEP WHAT WAS TYPED AT EACH STEP
    pub fn remember(&mut self, stage: Stage, text: &str)
    {
        match stage
        {
            Stage::Username => self.typed.0 = text.to_owned(),
            Stage::Password { .. } => self.typed.1 = Zeroizing::new(text.to_owned()),
            Stage::Address => {},
        }
    }

    //THE PAIR WORKED, SO IT IS WORTH REPLAYING
    pub fn accepted(&mut self)
    {
        self.credentials = Some(self.typed.clone());
        self.left = consts::RECONNECT_ATTEMPTS;
        self.retrying = false;
        self.due = None;
    }

    //THE USER ASKED TO LEAVE, OR CANCELLED THE DIAL
    pub fn forget(&mut self) { *self = Self::default(); }

    //SCHEDULE A DIAL, IF THERE IS ANYTHING TO LOG BACK IN WITH
    pub fn arm(&mut self) -> bool
    {
        if self.credentials.is_none() || self.left == 0
        {
            self.retrying = false; //OUT OF TRIES - THE NEXT DIAL IS THE USER'S OWN

            return false;
        }

        self.left -= 1;
        self.retrying = true;
        self.answers = 2; //A SERVER THAT KEEPS ASKING IS NOT ANSWERED FOREVER
        self.due = Some(Instant::now() + consts::RECONNECT_DELAY);

        true
    }

    //WHAT THE BOX SAYS WHILE IT IS DIALLING ITSELF BACK
    pub fn status(&self) -> Option<String>
    {
        self.retrying.then(|| format!("Connection lost, reconnecting… ({}/{})",
            consts::RECONNECT_ATTEMPTS - self.left, consts::RECONNECT_ATTEMPTS))
    }

    //WHETHER THE WAIT IS UP
    pub fn take_due(&mut self) -> bool
    {
        if self.due.is_none_or(|due| Instant::now() < due) { return false; }

        self.due = None;

        true
    }

    //THE ANSWER THE SERVER'S NEXT STEP WANTS
    pub fn answer(&mut self, stage: Stage) -> Option<String>
    {
        //ONLY A DIAL WE STARTED REPLAYS ANYTHING - A DIAL THE USER TYPED IS THEIRS TO ANSWER
        if !self.retrying || self.answers == 0 { return None; }

        let (username, password) = self.credentials.as_ref()?;

        let answer = match stage
        {
            Stage::Username => username.clone(),
            Stage::Password { register: false } => password.to_string(),

            //A REGISTRATION MEANS THE ACCOUNT IS GONE - ASK
            _ => return None,
        };

        self.answers -= 1;

        Some(answer)
    }
}

impl Default for Login
{
    fn default() -> Self { Self::new() }
}

impl Login
{
    pub fn new() -> Self
    {
        let mut input = InputBuffer::new();

        //auto_connect IS THE ONE CASE THAT PREFILLS
        let auto = config::read_config::<bool>("auto_connect");
        if auto { input.insert_str(config::read_config::<String>("auto_connect_addr").trim()); }

        Self { input, stage: Stage::Address, busy: auto, connected: false, error: None, hint: None, attempt: 0 }
    }

    //COME BACK AT THE ADDRESS STEP AFTER A DROP
    pub fn again(address: &str, attempt: u64, error: String) -> Self
    {
        let mut input = InputBuffer::new();
        input.insert_str(address);

        Self { input, stage: Stage::Address, busy: false, connected: false, error: Some(error), hint: None, attempt }
    }

    pub fn address(&self) -> String { self.input.text().trim().to_owned() }

    pub fn attempt(&self) -> u64 { self.attempt }

    //THE ATTEMPT A RESULT HAS TO BELONG TO
    pub fn accepts(&self, attempt: u64) -> bool { self.busy && attempt == self.attempt }

    pub fn failed(&mut self, error: &Error)
    {
        self.busy = false;
        self.error = Some(error.to_string());
    }

    //ASK THE NEXT STEP, KEEPING THE ERROR
    pub fn ask(&mut self, stage: Stage, hint: Option<String>)
    {
        self.stage = stage;
        self.hint = hint;
        self.busy = false;
        self.input = InputBuffer::new();
    }

    pub fn masked(&self) -> bool { matches!(self.stage, Stage::Password { .. }) }

    pub fn title(&self) -> &'static str
    {
        match self.stage
        {
            Stage::Address => " Connect ",
            Stage::Username => " Identify ",
            Stage::Password { register: true } => " Register ",
            Stage::Password { register: false } => " Log in ",
        }
    }

    pub fn label(&self) -> &'static str
    {
        match self.stage
        {
            Stage::Address => "Server address",
            Stage::Username => "Username",
            Stage::Password { .. } => "Password",
        }
    }

    //THE STATUS ROW WHILE SOMETHING IS IN FLIGHT
    pub fn waiting(&self) -> &'static str
    {
        match (self.stage, self.connected)
        {
            (Stage::Address, false) => "Connecting…",
            (Stage::Address, true) => "Exchanging keys…", //THE SOCKET IS UP, THE HANDSHAKE IS NOT DONE
            _ => "Waiting for the server…",
        }
    }

    //ESC ABANDONS A DIAL, THEN LEAVES THE CLIENT
    pub fn cancellable(&self) -> bool { self.busy && !self.connected && self.stage == Stage::Address }
}

//FUNCTIONS
//PUBLIC
pub fn handle_key(app: &mut App, key: KeyEvent) -> Action
{
    let Some(login) = app.login.as_mut() else { return Action::None };

    //ESC BACKS OUT OF A DIAL FIRST
    if key.code == KeyCode::Esc
    {
        if login.connected || login.stage != Stage::Address || !login.busy { return Action::Quit; }

        //LEAVE THE TASK - ITS RESULT NO LONGER COUNTS
        login.busy = false;
        login.error = None;

        //A CANCELLED DIAL IS NOT ONE TO REPEAT
        app.reconnect.forget();

        return Action::None;
    }

    if login.busy { return Action::None; } //NOTHING IS EDITABLE WHILE AN ANSWER IS IN FLIGHT

    if key.modifiers.contains(KeyModifiers::CONTROL)
    {
        match key.code
        {
            KeyCode::Char('a') => login.input.home(),
            KeyCode::Char('e') => login.input.end(),
            KeyCode::Char('u') => login.input.kill_to_start(),
            KeyCode::Char('k') => login.input.kill_to_end(),
            KeyCode::Char('w') => login.input.delete_word(),
            _ => {},
        }

        return Action::None;
    }

    match key.code
    {
        //ONE FIELD, ONE LINE
        KeyCode::Char(character) => login.input.insert(character),

        KeyCode::Backspace => login.input.backspace(),
        KeyCode::Delete => login.input.delete(),

        KeyCode::Left => login.input.left(),
        KeyCode::Right => login.input.right(),
        KeyCode::Home => login.input.home(),
        KeyCode::End => login.input.end(),

        KeyCode::Enter => match login.stage
        {
            Stage::Address =>
            {
                if login.address().is_empty()
                {
                    login.error = Some(String::from("Enter the address of a server."));
                } else { return Action::Connect; }
            },

            //A PASSWORD IS TAKEN AS TYPED
            _ =>
            {
                if login.input.text().is_empty()
                {
                    login.error = Some(format!("Enter a {}.", login.label().to_lowercase()));
                } else { return Action::Submit; }
            },
        },

        _ => {},
    }

    Action::None
}

pub fn insert_str(app: &mut App, text: &str) //A PASTE INTO WHICHEVER FIELD IS UP
{
    if let Some(login) = app.login.as_mut() && !login.busy
    {
        login.input.insert_str(&text.replace(['\r', '\n'], ""));
    }
}

//TAKE THE ANSWERED STEP OFF THE FIELD, GO BUSY
pub fn take_input(app: &mut App) -> String
{
    let Some(login) = app.login.as_mut() else { return String::new() };

    //ONLY THE ADDRESS IS TRIMMED HERE
    let text = login.input.text();
    let stage = login.stage;

    login.input = InputBuffer::new();
    login.error = None;
    login.hint = None;
    login.busy = true;

    //A RECONNECT REPLAYS THIS
    app.reconnect.remember(stage, &text);

    text
}

//DIAL IN A TASK, SO THE FRAME KEEPS DRAWING
pub fn connect(app: &mut App, results: &Sender<ConnectResult>)
{
    let Some(login) = app.login.as_mut() else { return };

    let display = login.address();
    if display.is_empty() { return; }

    login.busy = true;
    login.error = None;
    login.attempt += 1;

    let attempt = login.attempt;

    //KEEP THE ADDRESS AS TYPED FOR THE TITLE
    let mut address = display.clone();
    if !address.contains(':') { address.push_str(&format!(":{}", config::read_config::<u16>("default_port"))); }

    app.address = display;

    //THE RECONNECT AFTER PINNING DIALS THIS
    options::set_server_address(&address);

    //A NEW CONNECTION COUNTS FROM ZERO
    options::set_seq(0);
    options::set_server_seq(0);

    let results = results.clone();

    tokio::spawn(async move
    {
        let _ = results.send((attempt, client::connect(address).await)).await;
    });
}