1
// This file is part of hnefatafl-copenhagen.
2
//
3
// hnefatafl-copenhagen is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU Affero General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// hnefatafl-copenhagen is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU Affero General Public License for more details.
12
//
13
// You should have received a copy of the GNU Affero General Public License
14
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
//
16
// SPDX-License-Identifier: AGPL-3.0-or-later
17
// SPDX-FileCopyrightText: 2025 David Campbell <david@hnefatafl.org>
18

            
19
#![deny(clippy::indexing_slicing)]
20
#![deny(clippy::expect_used)]
21
#![deny(clippy::panic)]
22
#![deny(clippy::unwrap_used)]
23

            
24
mod command_line;
25
mod remove_connection;
26
mod smtp;
27
mod tests;
28
mod unix_timestamp;
29

            
30
use std::{
31
    collections::{HashMap, HashSet, VecDeque},
32
    fmt,
33
    fs::{self, File, OpenOptions},
34
    io::{BufRead, BufReader, ErrorKind, Read, Write},
35
    net::{IpAddr, TcpListener, TcpStream},
36
    process::exit,
37
    str::FromStr,
38
    sync::{
39
        Arc, Mutex,
40
        mpsc::{self, Receiver, Sender},
41
    },
42
    thread::{self, sleep},
43
    time::Duration,
44
};
45

            
46
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
47
use clap::Parser;
48
use hnefatafl_copenhagen::{
49
    Id, SERVER_PORT, VERSION_ID,
50
    accounts::{Account, Accounts, DateTimeUtc},
51
    board::BoardSize,
52
    draw::Draw,
53
    email::Email,
54
    game::TimeUnix,
55
    glicko::Outcome,
56
    rating::Rated,
57
    role::Role,
58
    server_game::{
59
        ArchivedGame, Challenger, Messenger, ServerGame, ServerGameLight, ServerGameSerialized,
60
        ServerGames, ServerGamesLight, ServerGamesLightVec,
61
    },
62
    status::Status,
63
    time::{Time, TimeEnum, TimeSettings},
64
    tournament::Tournament,
65
    utils::{self, create_data_folder, data_file},
66
};
67
use itertools::Itertools;
68
use jiff::{Timestamp, ToSpan, Zoned};
69
use lettre::{
70
    SmtpTransport, Transport,
71
    message::{Mailbox, header::ContentType},
72
    transport::smtp::authentication::Credentials,
73
};
74
use log::{debug, error, info, trace};
75
use rand::random;
76
use serde::{Deserialize, Serialize};
77
use std::fmt::Write as _;
78

            
79
use crate::{
80
    command_line::Args, remove_connection::RemoveConnection, smtp::Smtp,
81
    unix_timestamp::UnixTimestamp,
82
};
83

            
84
const ACTIVE_GAMES_FILE: &str = "active-games.postcard";
85
const ARCHIVED_GAMES_FILE: &str = "archived-games.ron";
86
const KEEP_TEXTS: usize = 100;
87

            
88
const HOUR_IN_SECONDS: u64 = 60 * 60;
89
const DAY_IN_SECONDS: u64 = HOUR_IN_SECONDS * 24;
90
const DAYS_FOR_INACTIVE_ACCOUNT: i64 = 14;
91

            
92
/// Seconds in two months: `60.0 * 60.0 * 24.0 * 30.417 * 2.0 = 5_256_057.6`
93
const TWO_MONTHS: i64 = 5_256_058;
94
const SEVEN_DAYS: i64 = 1_000 * 60 * 60 * 24 * 7;
95
const USERS_FILE: &str = "users.ron";
96

            
97
fn main() -> anyhow::Result<()> {
98
    // println!("{:x}", rand::random::<u32>());
99
    // return Ok(());
100

            
101
    let args = Args::parse();
102
    utils::init_logger("hnefatafl_server_full", args.debug, args.systemd);
103

            
104
    if args.man {
105
        return Args::generate_man_page();
106
    }
107

            
108
    create_data_folder()?;
109

            
110
    let (tx, rx) = mpsc::channel();
111
    let mut server = Server {
112
        tx: Some(tx.clone()),
113
        ..Server::default()
114
    };
115

            
116
    if args.skip_the_data_file {
117
        server.skip_the_data_files = true;
118
    } else {
119
        server.load_data_files(tx.clone(), args.systemd)?;
120
    }
121

            
122
    thread::spawn(move || handle_error(server.handle_messages(&rx)));
123

            
124
    if !args.skip_advertising_updates {
125
        Server::advertise_updates(tx.clone());
126
    }
127

            
128
    Server::check_once_a_day(tx.clone());
129

            
130
    if args.autostart_tournament {
131
        Server::new_tournament(tx.clone());
132
    }
133

            
134
    Server::save(tx.clone());
135

            
136
    let mut address = "[::]".to_string();
137
    address.push_str(SERVER_PORT);
138

            
139
    let listener = match TcpListener::bind(&address) {
140
        Ok(listener) => listener,
141
        Err(error) => {
142
            error!("TcpLister::bind: {error}");
143

            
144
            address = "0.0.0.0".to_string();
145
            address.push_str(SERVER_PORT);
146
            TcpListener::bind(&address)?
147
        }
148
    };
149

            
150
    info!("listening on {address} ...");
151

            
152
    for (index, stream) in (1..).zip(listener.incoming()) {
153
        let stream = match stream {
154
            Ok(stream) => stream,
155
            Err(error) => {
156
                error!("stream: {error}");
157
                continue;
158
            }
159
        };
160

            
161
        let peer_address = match stream.peer_addr() {
162
            Ok(peer_address) => peer_address.ip(),
163
            Err(error) => {
164
                error!("peer_address: {error}");
165
                continue;
166
            }
167
        };
168

            
169
        if args.secure {
170
            let (tx_close, rx_close) = mpsc::channel();
171

            
172
            tx.send((
173
                format!("0 server connection_add {peer_address}"),
174
                Some(tx_close),
175
            ))?;
176

            
177
            match rx_close.recv() {
178
                Ok(close) => match close.parse() {
179
                    Ok(close) => {
180
                        if close {
181
                            continue;
182
                        }
183
                    }
184
                    Err(error) => {
185
                        error!("close 2: {error}");
186
                        continue;
187
                    }
188
                },
189
                Err(error) => {
190
                    error!("close 1: {error}");
191
                    continue;
192
                }
193
            }
194
        }
195

            
196
        let tx = tx.clone();
197

            
198
        thread::spawn(move || {
199
            if let Err(error) = login(index, stream, peer_address, &tx) {
200
                error!("peer_address: {peer_address}, login: {error}");
201
            }
202
        });
203
    }
204

            
205
    Ok(())
206
}
207

            
208
#[allow(clippy::too_many_lines)]
209
fn login(
210
    id: Id,
211
    mut stream: TcpStream,
212
    peer_address: IpAddr,
213
    tx: &mpsc::Sender<(String, Option<mpsc::Sender<String>>)>,
214
) -> anyhow::Result<()> {
215
    info!("login attempted from {peer_address}");
216

            
217
    let args = Args::parse();
218

            
219
    let _remove_connection;
220
    if args.secure {
221
        _remove_connection = RemoveConnection {
222
            address: stream.peer_addr()?.ip(),
223
            tx: tx.clone(),
224
        };
225
    }
226

            
227
    let mut reader = BufReader::new(stream.try_clone()?);
228
    let mut buf = String::new();
229
    let (client_tx, client_rx) = mpsc::channel();
230
    let mut username_proper = "_".to_string();
231
    let mut login_successful = false;
232

            
233
    for _ in 0..100 {
234
        reader.read_line(&mut buf)?;
235

            
236
        for ch in buf.trim().chars() {
237
            if ch.is_control() || ch == '\0' {
238
                return Err(anyhow::Error::msg(
239
                    "there are control characters in the username or password",
240
                ));
241
            }
242
        }
243

            
244
        if buf.trim().is_empty() {
245
            return Err(anyhow::Error::msg(
246
                "The user sent a command without logging in, then quit.",
247
            ));
248
        }
249

            
250
        let buf_clone = buf.clone();
251
        let mut username_password_etc = buf_clone.split_ascii_whitespace();
252

            
253
        let version_id = username_password_etc.next();
254
        let create_account_login = username_password_etc.next();
255
        let username_option = username_password_etc.next();
256

            
257
        if let (Some(version_id), Some(create_account_login), Some(username)) =
258
            (version_id, create_account_login, username_option)
259
        {
260
            username_proper = username.to_string();
261
            if version_id != VERSION_ID {
262
                stream.write_all(b"? login wrong_version\n")?;
263
                buf.clear();
264
                continue;
265
            }
266

            
267
            let password: Vec<&str> = username_password_etc.collect();
268
            let password = password.join(" ");
269

            
270
            if username.len() > 16 {
271
                stream.write_all(b"? login _ username is more than 16 characters\n")?;
272
                buf.clear();
273
                continue;
274
            }
275
            if password.len() > 32 {
276
                stream.write_all(b"? login _ password is more than 32 characters\n")?;
277
                buf.clear();
278
                continue;
279
            }
280

            
281
            debug!("{peer_address} {id} {username} {create_account_login} {password}");
282

            
283
            if create_account_login == "reset_password" {
284
                tx.send((
285
                    format!("0 {username} reset_password"),
286
                    Some(client_tx.clone()),
287
                ))?;
288

            
289
                stream.write_all(b"? login reset_password\n")?;
290

            
291
                buf.clear();
292
                continue;
293
            }
294

            
295
            tx.send((
296
                format!("{id} {username} {create_account_login} {password}"),
297
                Some(client_tx.clone()),
298
            ))?;
299

            
300
            let message = client_rx.recv()?;
301
            buf.clear();
302
            if create_account_login == "login" {
303
                if "= login" == message.as_str() {
304
                    login_successful = true;
305
                    break;
306
                }
307

            
308
                stream.write_all(b"? login multiple_possible_errors\n")?;
309
                continue;
310
            } else if create_account_login == "create_account" {
311
                if "= create_account" == message.as_str() {
312
                    login_successful = true;
313
                    break;
314
                }
315

            
316
                stream.write_all(b"? create_account\n")?;
317
                continue;
318
            }
319

            
320
            stream.write_all(b"? login _\n")?;
321
        }
322

            
323
        buf.clear();
324
    }
325

            
326
    if !login_successful {
327
        return Err(anyhow::Error::msg("the user failed to login"));
328
    }
329
    stream.write_all(b"= login\n")?;
330
    info!("{peer_address} {id} {username_proper} logged in");
331

            
332
    thread::spawn(move || {
333
        if let Err(error) = receiving_and_writing(stream, &client_rx) {
334
            error!("receiving_and_writing: {error}");
335
        }
336
    });
337

            
338
    tx.send((format!("{id} {username_proper} email_get"), None))?;
339
    tx.send((format!("{id} {username_proper} texts"), None))?;
340
    tx.send((format!("{id} {username_proper} display_games"), None))?;
341
    tx.send((format!("{id} {username_proper} tournament_status_0"), None))?;
342
    tx.send((format!("{id} {username_proper} admin"), None))?;
343
    tx.send((format!("{id} {username_proper} admin_tournament"), None))?;
344

            
345
    let mut game_id = None;
346
    'outer: for _ in 0..1_000_000 {
347
        if let Err(err) = reader.read_line(&mut buf) {
348
            error!("peer_address: {peer_address}, reader.read_line(): {err}");
349
            break 'outer;
350
        }
351

            
352
        let buf_str = buf.trim();
353

            
354
        if buf_str.is_empty() {
355
            break 'outer;
356
        }
357

            
358
        for char in buf_str.chars() {
359
            if char.is_control() || char == '\0' {
360
                break 'outer;
361
            }
362
        }
363

            
364
        // Fixme: If a player creates a game less than day main time, then
365
        // leaves the game without declining, then the other players gets a
366
        // game that does not automatically quit.
367
        let words: Vec<_> = buf_str.split_whitespace().collect();
368
        if let Some(first) = words.first() {
369
            if (*first == "join_game" || *first == "resume_game")
370
                && let Some(second) = words.get(1)
371
                && let Ok(id) = u128::from_str(second)
372
            {
373
                game_id = Some(id);
374
            }
375

            
376
            if *first == "leave_game" {
377
                game_id = None;
378
            }
379
        }
380

            
381
        tx.send((format!("{id} {username_proper} {buf_str}"), None))?;
382
        buf.clear();
383
    }
384

            
385
    if let Some(game_id) = game_id {
386
        tx.send((format!("{id} {username_proper} leave_game {game_id}"), None))?;
387
    }
388

            
389
    tx.send((format!("{id} {username_proper} logout"), None))?;
390
    info!("{peer_address} {id} {username_proper} logged out");
391

            
392
    Ok(())
393
}
394

            
395
fn receiving_and_writing<T: Send + Write>(
396
    mut stream: T,
397
    client_rx: &Receiver<String>,
398
) -> anyhow::Result<()> {
399
    for mut message in client_rx {
400
        match message.as_str() {
401
            "= archived_games" => {
402
                let ron_archived_games = client_rx.recv()?;
403
                let archived_games: Vec<ArchivedGame> = ron::from_str(&ron_archived_games)?;
404
                let postcard_archived_games = &postcard::to_allocvec(&archived_games)?;
405

            
406
                writeln!(message, " {}", postcard_archived_games.len())?;
407
                stream.write_all(message.as_bytes())?;
408
                stream.write_all(postcard_archived_games)?;
409
            }
410
            "= logout" => return Ok(()),
411
            _ => {
412
                message.push('\n');
413
                if let Err(error) = stream.write_all(message.as_bytes()) {
414
                    return Err(anyhow::Error::msg(format!("{message}: {error}")));
415
                }
416
            }
417
        }
418
    }
419

            
420
    Ok(())
421
}
422

            
423
fn handle_error<T, E: fmt::Display>(result: Result<T, E>) -> T {
424
    match result {
425
        Ok(value) => value,
426
        Err(error) => {
427
            error!("{error}");
428
            exit(1)
429
        }
430
    }
431
}
432

            
433
fn hash_password(password: &str) -> Option<String> {
434
    let ctx = Argon2::default();
435
    Some(ctx.hash_password(password.as_bytes()).ok()?.to_string())
436
}
437

            
438
fn timestamp() -> String {
439
    Timestamp::now().strftime("[%F %T UTC]").to_string()
440
}
441

            
442
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
443
struct Server {
444
    #[serde(default)]
445
    game_id: Id,
446
    #[serde(default)]
447
    ran_update_rd: UnixTimestamp,
448
    #[serde(default)]
449
    admins: HashSet<String>,
450
    #[serde(default)]
451
    admins_tournament: HashSet<String>,
452
    #[serde(default)]
453
    smtp: Smtp,
454
    #[serde(default)]
455
    tournament: Option<Tournament>,
456
    #[serde(default)]
457
    accounts: Accounts,
458
    #[serde(skip)]
459
    accounts_old: Accounts,
460
    #[serde(skip)]
461
    archived_games: Vec<ArchivedGame>,
462
    #[serde(skip)]
463
    clients: HashMap<usize, mpsc::Sender<String>>,
464
    #[serde(skip)]
465
    connections: HashMap<String, u128>,
466
    #[serde(skip)]
467
    games: ServerGames,
468
    #[serde(skip)]
469
    games_light: ServerGamesLight,
470
    #[serde(skip)]
471
    games_light_vec: ServerGamesLightVec,
472
    #[serde(skip)]
473
    games_light_old: ServerGamesLight,
474
    #[serde(skip)]
475
    skip_the_data_files: bool,
476
    #[serde(default)]
477
    texts: VecDeque<String>,
478
    #[serde(skip)]
479
    tx: Option<mpsc::Sender<(String, Option<mpsc::Sender<String>>)>>,
480
}
481

            
482
impl Server {
483
    fn advertise_updates(tx: Sender<(String, Option<Sender<String>>)>) {
484
        thread::spawn(move || {
485
            loop {
486
                handle_error(tx.send(("0 server display_server".to_string(), None)));
487
                thread::sleep(Duration::from_secs(1));
488
            }
489
        });
490
    }
491

            
492
    fn append_archived_game(&mut self, game: ServerGame) -> anyhow::Result<()> {
493
        let Some(attacker) = self.accounts.0.get(&game.attacker) else {
494
            return Err(anyhow::Error::msg("failed to get rating!"));
495
        };
496
        let Some(defender) = self.accounts.0.get(&game.defender) else {
497
            return Err(anyhow::Error::msg("failed to get rating!"));
498
        };
499
        let game = ArchivedGame::new(game, attacker.rating.clone(), defender.rating.clone());
500

            
501
        let archived_games_file = data_file(ARCHIVED_GAMES_FILE);
502
        let mut game_string = ron::ser::to_string(&game)?;
503
        game_string.push('\n');
504

            
505
        let mut file = OpenOptions::new()
506
            .create(true)
507
            .append(true)
508
            .open(archived_games_file)?;
509

            
510
        file.write_all(game_string.as_bytes())?;
511

            
512
        self.archived_games.push(game);
513

            
514
        Ok(())
515
    }
516

            
517
    fn bcc_mailboxes(&self, username: &str) -> Vec<Mailbox> {
518
        let mut emails = Vec::new();
519

            
520
        if let Some(account) = self.accounts.0.get(username)
521
            && account.send_emails
522
        {
523
            for account in self.accounts.0.values() {
524
                if let Some(email) = &account.email
525
                    && email.verified
526
                    && let Some(email) = email.to_mailbox()
527
                {
528
                    emails.push(email);
529
                }
530
            }
531
        }
532

            
533
        emails
534
    }
535

            
536
    fn bcc_send(&self, username: &str) -> String {
537
        let mut emails = Vec::new();
538

            
539
        if let Some(account) = self.accounts.0.get(username)
540
            && account.send_emails
541
        {
542
            for account in self.accounts.0.values() {
543
                if let Some(email) = &account.email
544
                    && email.verified
545
                {
546
                    emails.push(email.tx());
547
                }
548
            }
549
        }
550

            
551
        emails.sort();
552
        emails.join(" ")
553
    }
554

            
555
    /// ```sh
556
    /// # PASSWORD can be the empty string.
557
    /// <- change_password PASSWORD
558
    /// -> = change_password
559
    /// ```
560
    fn change_password(
561
        &mut self,
562
        username: &str,
563
        index_supplied: usize,
564
        command: &str,
565
        the_rest: &[&str],
566
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
567
        info!("{index_supplied} {username} change_password");
568

            
569
        let account = self.accounts.0.get_mut(username)?;
570
        let password = the_rest.join(" ");
571

            
572
        if password.len() > 32 {
573
            return Some((
574
                self.clients.get(&index_supplied)?.clone(),
575
                false,
576
                format!("{command} password is greater than 32 characters"),
577
            ));
578
        }
579

            
580
        let hash = hash_password(&password)?;
581
        account.password = hash;
582

            
583
        Some((
584
            self.clients.get(&index_supplied)?.clone(),
585
            true,
586
            (*command).to_string(),
587
        ))
588
    }
589

            
590
    /// ```sh
591
    /// # server internal
592
    /// ```
593
    ///
594
    /// c = 63.2
595
    ///
596
    /// This assumes 30 2 month periods must pass before one's rating
597
    /// deviation is the same as a new player and that a typical RD is 50.
598
    #[must_use]
599
    fn check_update_rd(&mut self) -> bool {
600
        let now = Timestamp::now().as_second();
601
        if now - self.ran_update_rd.0 >= TWO_MONTHS {
602
            for account in self.accounts.0.values_mut() {
603
                account.rating.update_rd();
604
            }
605
            self.ran_update_rd = UnixTimestamp(now);
606
            true
607
        } else {
608
            false
609
        }
610
    }
611

            
612
    fn check_once_a_day(tx: Sender<(String, Option<Sender<String>>)>) {
613
        thread::spawn(move || {
614
            loop {
615
                handle_error(tx.send(("0 server delete_unused_accounts".to_string(), None)));
616
                handle_error(tx.send(("0 server check_update_rd".to_string(), None)));
617
                thread::sleep(Duration::from_secs(DAY_IN_SECONDS));
618
            }
619
        });
620
    }
621

            
622
    /// ```sh
623
    /// # PASSWORD can be the empty string.
624
    /// <- VERSION_ID create_account player-1 PASSWORD
625
    /// -> = login
626
    /// ```
627
    fn create_account(
628
        &mut self,
629
        username: &str,
630
        index_supplied: usize,
631
        command: &str,
632
        the_rest: &[&str],
633
        option_tx: Option<Sender<String>>,
634
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
635
        let password = the_rest.join(" ");
636
        let tx = option_tx?;
637

            
638
        if self.accounts.0.contains_key(username) || username == "server" {
639
            info!("{index_supplied} {username} is already in the database");
640
            Some((tx, false, (*command).to_string()))
641
        } else {
642
            info!("{index_supplied} {username} created user account");
643

            
644
            let hash = hash_password(&password)?;
645
            self.clients.insert(index_supplied, tx);
646
            self.accounts.0.insert(
647
                (*username).to_string(),
648
                Account {
649
                    password: hash,
650
                    logged_in: Some(index_supplied),
651
                    ..Default::default()
652
                },
653
            );
654

            
655
            Some((
656
                self.clients.get(&index_supplied)?.clone(),
657
                true,
658
                (*command).to_string(),
659
            ))
660
        }
661
    }
662

            
663
    fn decline_game(
664
        &mut self,
665
        username: &str,
666
        index_supplied: usize,
667
        mut command: String,
668
        the_rest: &[&str],
669
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
670
        let channel = self.clients.get(&index_supplied)?;
671

            
672
        let Some(id) = the_rest.first() else {
673
            return Some((channel.clone(), false, command));
674
        };
675
        let Ok(id) = id.parse::<Id>() else {
676
            return Some((channel.clone(), false, command));
677
        };
678

            
679
        let mut switch = false;
680
        if let Some(&"switch") = the_rest.get(1) {
681
            switch = true;
682
        }
683

            
684
        info!("{index_supplied} {username} decline_game {id} switch={switch}");
685

            
686
        if let Some(game_old) = self.games_light.0.remove(&id) {
687
            let mut attacker = None;
688
            let mut defender = None;
689

            
690
            if switch {
691
                if Some(username.to_string()) == game_old.attacker {
692
                    defender = game_old.defender;
693
                } else if Some(username.to_string()) == game_old.defender {
694
                    attacker = game_old.attacker;
695
                }
696
            } else if Some(username.to_string()) == game_old.attacker {
697
                attacker = game_old.attacker;
698
            } else if Some(username.to_string()) == game_old.defender {
699
                defender = game_old.defender;
700
            }
701

            
702
            let game = ServerGameLight {
703
                id,
704
                attacker,
705
                defender,
706
                challenger: Challenger::default(),
707
                rated: game_old.rated,
708
                timed: game_old.timed,
709
                board_size: game_old.board_size,
710
                spectators: game_old.spectators,
711
                challenge_accepted: false,
712
                game_over: false,
713
                turn: Role::Roleless,
714
            };
715

            
716
            command = format!("{command} {game:?}");
717
            self.games_light.0.insert(id, game);
718
        }
719

            
720
        Some((channel.clone(), true, command))
721
    }
722

            
723
    fn delete_account(&mut self, username: &str, index_supplied: usize) {
724
        info!("{index_supplied} {username} delete_account");
725

            
726
        self.accounts.0.remove(username);
727
    }
728

            
729
    #[allow(clippy::too_many_lines)]
730
    fn display_server(&mut self, username: &str) -> Option<(mpsc::Sender<String>, bool, String)> {
731
        if self.games_light != self.games_light_old {
732
            debug!("0 {username} display_games");
733
            self.games_light_old = self.games_light.clone();
734
            self.sort_games_light();
735

            
736
            let mut names = HashMap::new();
737
            for (name, account) in &self.accounts.0 {
738
                if let Some(id) = account.logged_in {
739
                    names.insert(id, name);
740
                }
741
            }
742

            
743
            for (id, tx) in &mut self.clients {
744
                let Ok(games) = self
745
                    .games_light_vec
746
                    .display_games(names.get(id).map(|s| s.as_str()))
747
                else {
748
                    continue;
749
                };
750

            
751
                let _ok = tx.send(format!("= display_games {games}"));
752
            }
753
        }
754

            
755
        if self.accounts != self.accounts_old {
756
            debug!("0 {username} display_users");
757
            self.accounts_old = self.accounts.clone();
758

            
759
            for (name, account) in &self.accounts.0 {
760
                if let Some(id) = account.logged_in
761
                    && let Some(tx) = self.clients.get(&id)
762
                {
763
                    if self.admins.contains(name) {
764
                        if let Ok(string) = &self.accounts.display_admin() {
765
                            let _ok = tx.send(format!("= display_users_admin {string}"));
766
                        }
767
                    } else {
768
                        let _ok = tx.send(format!("= display_users {}", &self.accounts));
769
                    }
770
                }
771
            }
772
        }
773

            
774
        for game in self.games.0.values_mut() {
775
            match game.game.turn {
776
                Role::Attacker => {
777
                    if game.game.status == Status::Ongoing
778
                        && let TimeUnix::Time(game_time) = &mut game.game.time
779
                    {
780
                        let now = Timestamp::now().as_millisecond();
781
                        let elapsed_time = now - *game_time;
782
                        game.elapsed_time += elapsed_time;
783
                        *game_time = now;
784

            
785
                        if game.elapsed_time > SEVEN_DAYS
786
                            && let Some(tx) = &mut self.tx
787
                        {
788
                            let _ok = tx.send((
789
                                format!(
790
                                    "0 {} game {} play attacker resigns _",
791
                                    game.attacker, game.id
792
                                ),
793
                                None,
794
                            ));
795
                            return None;
796
                        }
797

            
798
                        if let TimeSettings::Timed(attacker_time) = &mut game.game.attacker_time {
799
                            if attacker_time.milliseconds_left > 0 {
800
                                attacker_time.milliseconds_left -= elapsed_time;
801
                            } else if let Some(tx) = &mut self.tx {
802
                                let _ok = tx.send((
803
                                    format!(
804
                                        "0 {} game {} play attacker resigns _",
805
                                        game.attacker, game.id
806
                                    ),
807
                                    None,
808
                                ));
809
                            }
810
                        }
811
                    }
812
                }
813
                Role::Roleless => {}
814
                Role::Defender => {
815
                    if game.game.status == Status::Ongoing
816
                        && let TimeUnix::Time(game_time) = &mut game.game.time
817
                    {
818
                        let now = Timestamp::now().as_millisecond();
819
                        let elapsed_time = now - *game_time;
820
                        game.elapsed_time += elapsed_time;
821
                        *game_time = now;
822

            
823
                        if game.elapsed_time > SEVEN_DAYS
824
                            && let Some(tx) = &mut self.tx
825
                        {
826
                            let _ok = tx.send((
827
                                format!(
828
                                    "0 {} game {} play defender resigns _",
829
                                    game.defender, game.id
830
                                ),
831
                                None,
832
                            ));
833
                            return None;
834
                        }
835

            
836
                        if let TimeSettings::Timed(defender_time) = &mut game.game.defender_time {
837
                            if defender_time.milliseconds_left > 0 {
838
                                defender_time.milliseconds_left -= elapsed_time;
839
                            } else if let Some(tx) = &mut self.tx {
840
                                let _ok = tx.send((
841
                                    format!(
842
                                        "0 {} game {} play defender resigns _",
843
                                        game.defender, game.id
844
                                    ),
845
                                    None,
846
                                ));
847
                            }
848
                        }
849
                    }
850
                }
851
            }
852
        }
853

            
854
        None
855
    }
856

            
857
    fn draw(
858
        &mut self,
859
        index_supplied: usize,
860
        command: &str,
861
        the_rest: &[&str],
862
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
863
        let Some(id) = the_rest.first() else {
864
            return Some((
865
                self.clients.get(&index_supplied)?.clone(),
866
                false,
867
                (*command).to_string(),
868
            ));
869
        };
870
        let Ok(id) = id.parse::<Id>() else {
871
            return Some((
872
                self.clients.get(&index_supplied)?.clone(),
873
                false,
874
                (*command).to_string(),
875
            ));
876
        };
877

            
878
        let Some(draw) = the_rest.get(1) else {
879
            return Some((
880
                self.clients.get(&index_supplied)?.clone(),
881
                false,
882
                (*command).to_string(),
883
            ));
884
        };
885
        let Ok(draw) = Draw::from_str(draw) else {
886
            return Some((
887
                self.clients.get(&index_supplied)?.clone(),
888
                false,
889
                (*command).to_string(),
890
            ));
891
        };
892

            
893
        let Some(mut game) = self.games.0.remove(&id) else {
894
            return Some((
895
                self.clients.get(&index_supplied)?.clone(),
896
                false,
897
                (*command).to_string(),
898
            ));
899
        };
900

            
901
        let message = format!("= draw {draw}");
902
        game.attacker_tx.send(message.clone());
903
        game.defender_tx.send(message.clone());
904

            
905
        if draw == Draw::Accept {
906
            let Some(game_light) = self.games_light.0.get(&id) else {
907
                return Some((
908
                    self.clients.get(&index_supplied)?.clone(),
909
                    false,
910
                    (*command).to_string(),
911
                ));
912
            };
913

            
914
            for spectator in game_light.spectators() {
915
                if let Some(sender) = self.clients.get(&spectator) {
916
                    let _ok = sender.send(message.clone());
917
                }
918
            }
919

            
920
            game.game.status = Status::Draw;
921

            
922
            let accounts = &mut self.accounts.0;
923
            let (attacker_rating, defender_rating) = if let (Some(attacker), Some(defender)) =
924
                (accounts.get(&game.attacker), accounts.get(&game.defender))
925
            {
926
                (attacker.rating.rating, defender.rating.rating)
927
            } else {
928
                unreachable!();
929
            };
930

            
931
            if let Some(attacker) = accounts.get_mut(&game.attacker) {
932
                attacker.draws += 1;
933

            
934
                if game.rated.into() {
935
                    attacker
936
                        .rating
937
                        .update_rating(defender_rating, &Outcome::Draw);
938
                }
939
            }
940
            if let Some(defender) = accounts.get_mut(&game.defender) {
941
                defender.draws += 1;
942

            
943
                if game.rated.into() {
944
                    defender
945
                        .rating
946
                        .update_rating(attacker_rating, &Outcome::Draw);
947
                }
948
            }
949

            
950
            if let Some(game) = self.games_light.0.get_mut(&id) {
951
                game.game_over = true;
952
            }
953

            
954
            if !self.skip_the_data_files {
955
                self.append_archived_game(game)
956
                    .map_err(|err| {
957
                        error!("append_archived_games: {err}");
958
                    })
959
                    .ok()?;
960
            }
961
        }
962

            
963
        None
964
    }
965

            
966
    //
967
    #[allow(clippy::too_many_lines)]
968
    fn game(
969
        &mut self,
970
        index_supplied: usize,
971
        username: &str,
972
        command: &str,
973
        the_rest: &[&str],
974
        group_size: usize,
975
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
976
        if the_rest.len() < 5 {
977
            return Some((
978
                self.clients.get(&index_supplied)?.clone(),
979
                false,
980
                (*command).to_string(),
981
            ));
982
        }
983

            
984
        let index = the_rest.first()?;
985
        let Ok(index) = index.parse() else {
986
            return Some((
987
                self.clients.get(&index_supplied)?.clone(),
988
                false,
989
                (*command).to_string(),
990
            ));
991
        };
992
        let role = the_rest.get(2)?;
993
        let Ok(role) = Role::from_str(role) else {
994
            return Some((
995
                self.clients.get(&index_supplied)?.clone(),
996
                false,
997
                (*command).to_string(),
998
            ));
999
        };
        let from = the_rest.get(3)?;
        let to = the_rest.get(4)?;
        let mut to = (*to).to_string();
        if to == "_" {
            to = String::new();
        }
        let Some(game) = self.games.0.get_mut(&index) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Some(game_light) = self.games_light.0.get_mut(&index) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        game.elapsed_time = 0;
        game.draw_requested = Role::Roleless;
        let mut attackers_turn_next = true;
        if role == Role::Attacker {
            if *username == game.attacker {
                game.game
                    .read_line(&format!("play attacker {from} {to}"))
                    .map_err(|error| {
                        error!("play attacker {from} {to}: {error}");
                        error
                    })
                    .ok()?;
                attackers_turn_next = false;
                let message = format!("game {index} play attacker {from} {to}");
                for spectator in game_light.spectators() {
                    if let Some(client) = self.clients.get(&spectator) {
                        let _ok = client.send(message.clone());
                    }
                }
                game.defender_tx.send(message);
            } else {
                return Some((
                    self.clients.get(&index_supplied)?.clone(),
                    false,
                    (*command).to_string(),
                ));
            }
        } else if *username == game.defender {
            game.game
                .read_line(&format!("play defender {from} {to}"))
                .map_err(|error| {
                    error!("play defender {from} {to}: {error}");
                    error
                })
                .ok()?;
            let message = format!("game {index} play defender {from} {to}");
            for spectator in game_light.spectators() {
                if let Some(client) = self.clients.get(&spectator) {
                    let _ok = client.send(message.clone());
                }
            }
            game.attacker_tx.send(message);
        } else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        }
        let mut game_over = false;
        game_light.turn = Role::Roleless;
        match game.game.status {
            Status::AttackerWins => {
                let accounts = &mut self.accounts.0;
                let (attacker_rating, defender_rating) = if let (Some(attacker), Some(defender)) =
                    (accounts.get(&game.attacker), accounts.get(&game.defender))
                {
                    (attacker.rating.rating, defender.rating.rating)
                } else {
                    unreachable!();
                };
                if let Some(attacker) = accounts.get_mut(&game.attacker) {
                    attacker.wins += 1;
                    if game.rated.into() {
                        attacker
                            .rating
                            .update_rating(defender_rating, &Outcome::Win);
                    }
                }
                if let Some(defender) = accounts.get_mut(&game.defender) {
                    defender.losses += 1;
                    if game.rated.into() {
                        defender
                            .rating
                            .update_rating(attacker_rating, &Outcome::Loss);
                    }
                }
                let message = format!("= game_over {index} attacker_wins");
                game.attacker_tx.send(message.clone());
                game.defender_tx.send(message.clone());
                for spectator in game_light.spectators() {
                    if let Some(sender) = self.clients.get(&spectator) {
                        let _ok = sender.send(message.clone());
                    }
                }
                game_over = true;
            }
            Status::Draw => {
                // Handled in the draw fn.
            }
            Status::Ongoing => {
                if attackers_turn_next {
                    game_light.turn = Role::Attacker;
                    game.attacker_tx
                        .send(format!("game {index} generate_move attacker"));
                } else {
                    game_light.turn = Role::Defender;
                    game.defender_tx
                        .send(format!("game {index} generate_move defender"));
                }
            }
            Status::DefenderWins => {
                let accounts = &mut self.accounts.0;
                let (attacker_rating, defender_rating) = if let (Some(attacker), Some(defender)) =
                    (accounts.get(&game.attacker), accounts.get(&game.defender))
                {
                    (attacker.rating.rating, defender.rating.rating)
                } else {
                    unreachable!();
                };
                if let Some(attacker) = accounts.get_mut(&game.attacker) {
                    attacker.losses += 1;
                    if game.rated.into() {
                        attacker
                            .rating
                            .update_rating(defender_rating, &Outcome::Loss);
                    }
                }
                if let Some(defender) = accounts.get_mut(&game.defender) {
                    defender.wins += 1;
                    if game.rated.into() {
                        defender
                            .rating
                            .update_rating(attacker_rating, &Outcome::Win);
                    }
                }
                let message = format!("= game_over {index} defender_wins");
                game.attacker_tx.send(message.clone());
                game.defender_tx.send(message.clone());
                for id in game_light.spectators() {
                    if let Some(sender) = self.clients.get(&id) {
                        let _ok = sender.send(message.clone());
                    }
                }
                game_over = true;
            }
        }
        if game_over {
            let Some(game) = self.games.0.remove(&index) else {
                unreachable!()
            };
            if let Some(game_light) = self.games_light.0.get_mut(&index) {
                game_light.game_over = true;
            }
            if let Some(tournament) = &mut self.tournament {
                if tournament.game_over(&game) {
                    self.generate_round(group_size);
                }
                self.tournament_status_all();
            }
            if !self.skip_the_data_files {
                self.append_archived_game(game)
                    .map_err(|err| {
                        error!("append_archived_game: {err}");
                    })
                    .ok()?;
            }
            return None;
        }
        Some((
            self.clients.get(&index_supplied)?.clone(),
            true,
            (*command).to_string(),
        ))
    }
    fn generate_round(&mut self, group_size: usize) {
        let mut round = None;
        if let Some(tournament) = &mut self.tournament {
            let groups = tournament.generate_round(&self.accounts, group_size);
            round = Some(groups);
        }
        let mut ids = VecDeque::new();
        let mut groups_arc_mutex = Vec::new();
        if let Some(groups) = round {
            for (i, mut group) in groups.into_iter().enumerate() {
                for combination in group.records.iter().map(|record| record.0).combinations(2) {
                    if let (Some(first), Some(second)) = (combination.first(), combination.get(1)) {
                        ids.push_back((self.new_tournament_game(first, second), i));
                        ids.push_back((self.new_tournament_game(second, first), i));
                        group.total_games += 2;
                    }
                }
                groups_arc_mutex.push(Arc::new(Mutex::new(group)));
            }
        }
        if !groups_arc_mutex.is_empty()
            && let Some(tournament) = &mut self.tournament
        {
            for (id, i) in ids {
                if let Some(group) = groups_arc_mutex.get(i) {
                    tournament.tournament_games.insert(id, group.clone());
                    tournament.tournament_games.insert(id, group.clone());
                }
            }
            if let Some(rounds) = &mut tournament.groups {
                rounds.push(groups_arc_mutex);
            }
        }
    }
    fn set_email(
        &mut self,
        index_supplied: usize,
        username: &str,
        command: &str,
        email: Option<&str>,
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(address) = email else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Some(account) = self.accounts.0.get_mut(username) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let random_u32 = random();
        let email = Email {
            address: address.to_string(),
            code: Some(random_u32),
            username: username.to_string(),
            verified: false,
        };
        info!("{index_supplied} {username} email {}", email.tx());
        let email_send = lettre::Message::builder()
            .from("Hnefatafl Org <no-reply@hnefatafl.org>".parse().ok()?)
            .to(email.to_mailbox()?)
            .subject("Account Verification")
            .header(ContentType::TEXT_PLAIN)
            .body(format!(
                "Dear {username},\nyour email verification code is as follows: {random_u32:x}",
            ))
            .ok()?;
        let credentials = Credentials::new(self.smtp.username.clone(), self.smtp.password.clone());
        let mailer = SmtpTransport::relay(&self.smtp.service)
            .ok()?
            .credentials(credentials)
            .build();
        match mailer.send(&email_send) {
            Ok(_) => {
                info!("email sent to {address} successfully!");
                account.email = Some(email);
                let reply = format!("email {address} false");
                Some((self.clients.get(&index_supplied)?.clone(), true, reply))
            }
            Err(err) => {
                let reply = format!("could not send email to {address}");
                error!("{reply}: {err}");
                Some((self.clients.get(&index_supplied)?.clone(), false, reply))
            }
        }
    }
    fn handle_messages(
        &mut self,
        rx: &mpsc::Receiver<(String, Option<mpsc::Sender<String>>)>,
    ) -> anyhow::Result<()> {
        loop {
            if let Some((tx, ok, command)) = self.handle_messages_internal(rx) {
                if ok {
                    tx.send(format!("= {command}"))?;
                } else {
                    tx.send(format!("? {command}"))?;
                }
            }
        }
    }
    #[allow(clippy::too_many_lines)]
    fn handle_messages_internal(
        &mut self,
        rx: &mpsc::Receiver<(String, Option<mpsc::Sender<String>>)>,
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let args = Args::parse();
        let (message, option_tx) = rx.recv().ok()?;
        let index_username_command: Vec<_> = message.split_ascii_whitespace().collect();
        if let (Some(index_supplied), Some(username), Some(command)) = (
            index_username_command.first(),
            index_username_command.get(1),
            index_username_command.get(2),
        ) {
            let username = *username;
            if *command != "check_update_rd"
                && *command != "create_account"
                && *command != "display_server"
                && *command != "join_game_pending"
                && *command != "leave_game"
                && *command != "login"
                && *command != "logout"
                && *command != "ping"
                && *command != "resume_game"
            {
                debug!("{index_supplied} {username} {command}");
            }
            let index_supplied = index_supplied.parse::<usize>().ok()?;
            let the_rest: Vec<_> = index_username_command.clone().into_iter().skip(3).collect();
            match *command {
                "admin" => {
                    if self.admins.contains(username) {
                        self.clients
                            .get(&index_supplied)?
                            .send("= admin".to_string())
                            .ok()?;
                    }
                    None
                }
                "admin_tournament" => {
                    if self.admins_tournament.contains(username) {
                        self.clients
                            .get(&index_supplied)?
                            .send("= admin_tournament".to_string())
                            .ok()?;
                    }
                    None
                }
                "archived_games" => {
                    self.clients
                        .get(&index_supplied)?
                        .send("= archived_games".to_string())
                        .ok()?;
                    self.clients
                        .get(&index_supplied)?
                        .send(ron::ser::to_string(&self.archived_games).ok()?)
                        .ok()?;
                    None
                }
                "change_password" => {
                    self.change_password(username, index_supplied, command, the_rest.as_slice())
                }
                "check_update_rd" => {
                    let bool = self.check_update_rd();
                    info!("0 {username} check_update_rd {bool}");
                    None
                }
                "connection_add" => {
                    if let Some(address) = the_rest.first()
                        && let Some(tx) = option_tx
                    {
                        if let Some(connections) = self.connections.get(*address)
                            && *connections > 2_000
                        {
                            tx.send("true".to_string()).ok()?;
                        } else {
                            tx.send("false".to_string()).ok()?;
                            let entry = self.connections.entry(address.to_string());
                            entry.and_modify(|value| *value += 1).or_insert(1);
                        }
                    }
                    debug!("connections: {:?}", self.connections);
                    None
                }
                "connection_remove" => {
                    if let Some(connection) = the_rest.first() {
                        let entry = self.connections.entry(connection.to_string());
                        entry.and_modify(|value| *value = value.saturating_sub(1));
                        if let Some(value) = self.connections.get(*connection)
                            && *value == 0
                        {
                            self.connections.remove(*connection);
                        }
                    }
                    debug!("connections: {:?}", self.connections);
                    None
                }
                "create_account" => self.create_account(
                    username,
                    index_supplied,
                    command,
                    the_rest.as_slice(),
                    option_tx,
                ),
                "decline_game" => self.decline_game(
                    username,
                    index_supplied,
                    (*command).to_string(),
                    the_rest.as_slice(),
                ),
                "delete_account" => {
                    self.delete_account(username, index_supplied);
                    None
                }
                "delete_unused_accounts" => {
                    let now = Timestamp::now();
                    let mut accounts = Vec::new();
                    let mut playing = HashSet::new();
                    for game in self.games_light.0.values() {
                        if let Some(attacker) = &game.attacker {
                            playing.insert(attacker);
                        }
                        if let Some(defender) = &game.defender {
                            playing.insert(defender);
                        }
                    }
                    for (name, account) in &self.accounts.0 {
                        if account.wins == 0
                            && account.losses == 0
                            && account.draws == 0
                            && let Ok(timestamp) = now.checked_sub(DAYS_FOR_INACTIVE_ACCOUNT.day())
                            && timestamp > account.last_logged_in.0
                            && !playing.contains(name)
                        {
                            accounts.push(name.clone());
                        }
                    }
                    for name in &accounts {
                        info!("deleting {name}...");
                        self.accounts.0.remove(name);
                    }
                    None
                }
                "display_games" => {
                    if args.skip_advertising_updates {
                        None
                    } else {
                        self.clients.get(&index_supplied).map(|tx| {
                            (
                                tx.clone(),
                                true,
                                format!("display_games {:?}", &self.games_light_vec),
                            )
                        })
                    }
                }
                "display_server" => self.display_server(username),
                "draw" => self.draw(index_supplied, command, the_rest.as_slice()),
                "game" => self.game(
                    index_supplied,
                    username,
                    command,
                    the_rest.as_slice(),
                    args.group_size,
                ),
                "email" => {
                    self.set_email(index_supplied, username, command, the_rest.first().copied())
                }
                "email_everyone" => {
                    if self.admins.contains(username) {
                        info!("{index_supplied} {username} email_everyone");
                    } else {
                        error!("{index_supplied} {username} email_everyone");
                        return None;
                    }
                    let emails_bcc = self.bcc_mailboxes(username);
                    let subject = the_rest.first()?;
                    let email_string = the_rest.get(1..)?.join(" ").replace("\\n", "\n");
                    let mut email = lettre::Message::builder();
                    for email_bcc in emails_bcc {
                        email = email.bcc(email_bcc);
                    }
                    let email = email
                        .from("Hnefatafl Org <no-reply@hnefatafl.org>".parse().ok()?)
                        .subject(*subject)
                        .header(ContentType::TEXT_PLAIN)
                        .body(email_string)
                        .ok()?;
                    let credentials =
                        Credentials::new(self.smtp.username.clone(), self.smtp.password.clone());
                    let mailer = SmtpTransport::relay(&self.smtp.service)
                        .ok()?
                        .credentials(credentials)
                        .build();
                    match mailer.send(&email) {
                        Ok(_) => {
                            info!("emails sent successfully!");
                            Some((
                                self.clients.get(&index_supplied)?.clone(),
                                true,
                                (*command).to_string(),
                            ))
                        }
                        Err(err) => {
                            let reply = "could not send emails";
                            error!("{reply}: {err}");
                            Some((
                                self.clients.get(&index_supplied)?.clone(),
                                false,
                                reply.to_string(),
                            ))
                        }
                    }
                }
                "emails_bcc" => {
                    let emails_bcc = self.bcc_send(username);
                    if !emails_bcc.is_empty() {
                        self.clients
                            .get(&index_supplied)?
                            .send(format!("= emails_bcc {emails_bcc}"))
                            .ok()?;
                    }
                    None
                }
                "email_code" => {
                    if let Some(account) = self.accounts.0.get_mut(username)
                        && let Some(email) = &mut account.email
                        && let (Some(code_1), Some(code_2)) = (email.code, the_rest.first())
                    {
                        if format!("{code_1:x}") == *code_2 {
                            email.verified = true;
                            self.clients
                                .get(&index_supplied)?
                                .send("= email_code".to_string())
                                .ok()?;
                        } else {
                            email.verified = false;
                            self.clients
                                .get(&index_supplied)?
                                .send("? email_code".to_string())
                                .ok()?;
                        }
                    }
                    None
                }
                "email_get" => {
                    if let Some(account) = self.accounts.0.get(username)
                        && let Some(email) = &account.email
                    {
                        self.clients
                            .get(&index_supplied)?
                            .send(format!("= email {} {}", email.address, email.verified))
                            .ok()?;
                    }
                    None
                }
                "email_reset" => {
                    if let Some(account) = self.accounts.0.get_mut(username) {
                        account.email = None;
                        Some((
                            self.clients.get(&index_supplied)?.clone(),
                            true,
                            (*command).to_string(),
                        ))
                    } else {
                        None
                    }
                }
                "exit" => {
                    info!("saving active games...");
                    let mut active_games = Vec::new();
                    for game in self.games.0.values() {
                        let mut serialized_game = ServerGameSerialized::from(game);
                        if let Some(game_light) = self.games_light.0.get(&game.id) {
                            serialized_game.timed = game_light.timed.clone();
                        }
                        active_games.push(serialized_game);
                    }
                    let mut file = handle_error(File::create(data_file(ACTIVE_GAMES_FILE)));
                    handle_error(
                        file.write_all(
                            handle_error(postcard::to_allocvec(&active_games)).as_slice(),
                        ),
                    );
                    exit(0);
                }
                "join_game" => self.join_game(
                    username,
                    index_supplied,
                    (*command).to_string(),
                    the_rest.as_slice(),
                ),
                "join_game_pending" => self.join_game_pending(
                    (*username).to_string(),
                    index_supplied,
                    (*command).to_string(),
                    the_rest.as_slice(),
                ),
                "join_tournament" => {
                    if let Some(tournament) = &mut self.tournament {
                        tournament.players.insert(username.to_string());
                        self.tournament_status_all();
                    }
                    None
                }
                "leave_game" => self.leave_game(
                    username,
                    index_supplied,
                    (*command).to_string(),
                    the_rest.as_slice(),
                ),
                "leave_tournament" => {
                    if let Some(tournament) = &mut self.tournament {
                        tournament.players.remove(username);
                        self.tournament_status_all();
                    }
                    None
                }
                "login" => self.login(
                    username,
                    index_supplied,
                    command,
                    the_rest.as_slice(),
                    option_tx,
                ),
                "logout" => self.logout(username, index_supplied, command),
                "new_game" => self.new_game(username, index_supplied, command, the_rest.as_slice()),
                "ping" => Some((
                    self.clients.get(&index_supplied)?.clone(),
                    true,
                    (*command).to_string(),
                )),
                "reset_password" => {
                    let account = self.accounts.0.get_mut(username)?;
                    if let Some(email) = &account.email {
                        if email.verified {
                            let day = 60 * 60 * 24;
                            let now = Timestamp::now().as_second();
                            if now - account.email_sent > day {
                                let password = format!("{:x}", random::<u32>());
                                account.password = hash_password(&password)?;
                                let message = lettre::Message::builder()
                                .from("Hnefatafl Org <no-reply@hnefatafl.org>".parse().ok()?)
                                .to(email.to_mailbox()?)
                                .subject("Password Reset")
                                .header(ContentType::TEXT_PLAIN)
                                .body(format!(
                                    "Dear {username},\nyour new password is as follows: {password}",
                                ))
                                .ok()?;
                                let credentials = Credentials::new(
                                    self.smtp.username.clone(),
                                    self.smtp.password.clone(),
                                );
                                let mailer = SmtpTransport::relay(&self.smtp.service)
                                    .ok()?
                                    .credentials(credentials)
                                    .build();
                                match mailer.send(&message) {
                                    Ok(_) => {
                                        info!("email sent to {} successfully!", email.address);
                                        account.email_sent = now;
                                    }
                                    Err(err) => {
                                        error!("could not send email to {}: {err}", email.address);
                                    }
                                }
                            }
                            {
                                error!(
                                    "a password reset email was sent less than a day ago for {username}"
                                );
                            }
                        } else {
                            error!("the email address for account {username} is unverified");
                        }
                    } else {
                        error!("no email exists for account {username}");
                    }
                    None
                }
                "resume_game" => self.resume_game(username, index_supplied, command, &the_rest),
                "request_draw" => self.request_draw(username, index_supplied, command, &the_rest),
                "save" => {
                    debug!("saving users file...");
                    self.save_server();
                    None
                }
                "text" => {
                    let timestamp = timestamp();
                    let the_rest = the_rest.join(" ");
                    info!("{index_supplied} {timestamp} {username} text {the_rest}");
                    let text = format!("= text {timestamp} {username}: {the_rest}");
                    if self.texts.len() >= KEEP_TEXTS {
                        self.texts.pop_front();
                    }
                    for tx in &mut self.clients.values() {
                        let _ok = tx.send(text.clone());
                    }
                    self.texts.push_back(text);
                    None
                }
                "texts" => {
                    if !self.texts.is_empty() {
                        let string = Vec::from(self.texts.clone()).join("\n");
                        self.clients.get(&index_supplied)?.send(string).ok()?;
                    }
                    None
                }
                "text_game" => self.text_game(username, index_supplied, command, the_rest),
                "tournament_delete" => {
                    if self.admins_tournament.contains(username) {
                        self.tournament = None;
                        self.tournament_status_all();
                    }
                    None
                }
                "tournament_groups_delete" => {
                    if self.admins_tournament.contains(username)
                        && let Some(tournament) = &mut self.tournament
                    {
                        tournament.groups = None;
                        tournament.tournament_games = HashMap::new();
                        self.tournament_status_all();
                    }
                    None
                }
                "tournament_date" => {
                    if self.admins_tournament.contains(username) {
                        if let Err(error) = self.tournament_date(&the_rest) {
                            error!("tournament_date: {error}");
                        } else {
                            self.tournament_status_all();
                        }
                    }
                    None
                }
                "tournament_status_0" => {
                    trace!("tournament_status: {:#?}", self.tournament);
                    if args.skip_advertising_updates {
                        None
                    } else {
                        let tx = self.clients.get(&index_supplied)?;
                        let tournament = ron::ser::to_string(&self.tournament).ok()?;
                        Some((
                            tx.clone(),
                            true,
                            format!("tournament_status_0 {tournament}"),
                        ))
                    }
                }
                "tournament_start" => {
                    if self.admins_tournament.contains(username)
                        && let Some(tournament) = &mut self.tournament
                        && tournament.groups.is_none()
                        && Timestamp::now() >= tournament.date
                    {
                        info!("Starting tournament...");
                        tournament.groups = Some(Vec::new());
                        tournament.players_left = tournament.players.clone();
                        self.generate_round(args.group_size);
                        self.tournament_status_all();
                    }
                    None
                }
                "watch_game" => self.watch_game(
                    username,
                    index_supplied,
                    (*command).to_string(),
                    the_rest.as_slice(),
                ),
                "=" => None,
                //
                _ => self.clients.get(&index_supplied).map(|channel| {
                    error!("{index_supplied} {username} {command}");
                    (channel.clone(), false, (*command).to_string())
                }),
            }
        } else {
            error!("{index_username_command:?}");
            None
        }
    }
    fn join_game(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: String,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(id) = the_rest.first() else {
            return Some((self.clients.get(&index_supplied)?.clone(), false, command));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((self.clients.get(&index_supplied)?.clone(), false, command));
        };
        info!("{index_supplied} {username} join_game {id}");
        let Some(game) = self.games_light.0.get_mut(&id) else {
            unreachable!();
        };
        game.challenge_accepted = true;
        game.turn = Role::Attacker;
        if let Some(account) = self.accounts.0.get(game.attacker.as_ref()?)
            && let Some(id) = account.logged_in
        {
            game.spectators.insert(game.attacker.clone()?, id);
        }
        if let Some(account) = self.accounts.0.get(game.defender.as_ref()?)
            && let Some(id) = account.logged_in
        {
            game.spectators.insert(game.defender.clone()?, id);
        }
        let (Some(attacker), Some(defender)) = (&game.attacker, &game.defender) else {
            unreachable!();
        };
        let (Some(attacker_account), Some(defender_account)) =
            (self.accounts.0.get(attacker), self.accounts.0.get(defender))
        else {
            unreachable!()
        };
        let mut attacker_channel = None;
        if let Some(channel_id) = attacker_account.logged_in
            && let Some(channel) = self.clients.get(&channel_id)
        {
            attacker_channel = Some(channel);
        }
        let mut defender_channel = None;
        if let Some(channel_id) = defender_account.logged_in
            && let Some(channel) = self.clients.get(&channel_id)
        {
            defender_channel = Some(channel);
        }
        for channel in [&attacker_channel, &defender_channel].into_iter().flatten() {
            channel
                .send(format!(
                    "= join_game {} {} {} {:?} {}",
                    game.attacker.clone()?,
                    game.defender.clone()?,
                    game.rated,
                    game.timed,
                    game.board_size,
                ))
                .ok()?;
        }
        let new_game = ServerGame::new(
            attacker_channel.cloned(),
            defender_channel.cloned(),
            game.clone(),
        );
        self.games.0.insert(id, new_game);
        if let Some(account) = self.accounts.0.get_mut(username) {
            account.pending_games.remove(&id);
        }
        if let Some(channel) = attacker_channel {
            channel
                .send(format!("game {id} generate_move attacker"))
                .ok()?;
        }
        None
    }
    fn join_game_pending(
        &mut self,
        username: String,
        index_supplied: usize,
        mut command: String,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let channel = self.clients.get(&index_supplied)?;
        let Some(id) = the_rest.first() else {
            return Some((channel.clone(), false, command));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((channel.clone(), false, command));
        };
        info!("{index_supplied} {username} join_game_pending {id}");
        let Some(game) = self.games_light.0.get_mut(&id) else {
            command.push_str(" the id doesn't refer to a pending game");
            return Some((channel.clone(), false, command));
        };
        if game.attacker.is_none() {
            game.attacker = Some(username.clone());
            if let Some(defender) = &game.defender
                && let Some(account) = self.accounts.0.get(defender)
                && let Some(channel_id) = account.logged_in
                && let Some(channel) = self.clients.get(&channel_id)
            {
                let _ok = channel.send(format!("= challenge_requested {id}"));
            }
        } else if game.defender.is_none() {
            game.defender = Some(username.clone());
            if let Some(attacker) = &game.attacker
                && let Some(account) = self.accounts.0.get(attacker)
                && let Some(channel_id) = account.logged_in
                && let Some(channel) = self.clients.get(&channel_id)
            {
                let _ok = channel.send(format!("= challenge_requested {id}"));
            }
        }
        game.challenger.0 = Some(username);
        command.push(' ');
        command.push_str(the_rest.first()?);
        Some((channel.clone(), true, command))
    }
    fn leave_game(
        &mut self,
        username: &str,
        index_supplied: usize,
        mut command: String,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(id) = the_rest.first() else {
            return Some((self.clients.get(&index_supplied)?.clone(), false, command));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((self.clients.get(&index_supplied)?.clone(), false, command));
        };
        if let Some(account) = self.accounts.0.get_mut(username) {
            account.pending_games.remove(&id);
        }
        info!("{index_supplied} {username} leave_game {id}");
        let mut remove = false;
        match self.games_light.0.get_mut(&id) {
            Some(game) => {
                if !game.challenge_accepted {
                    if let Some(attacker) = &game.attacker
                        && username == attacker
                    {
                        game.attacker = None;
                    }
                    if let Some(defender) = &game.defender
                        && username == defender
                    {
                        game.defender = None;
                    }
                    if let Some(challenger) = &game.challenger.0
                        && username == challenger
                    {
                        game.challenger.0 = None;
                    }
                }
                game.spectators.remove(username);
                if game.attacker.is_none() && game.defender.is_none() {
                    remove = true;
                }
            }
            None => return Some((self.clients.get(&index_supplied)?.clone(), false, command)),
        }
        if remove {
            self.games_light.0.remove(&id);
        }
        command.push(' ');
        command.push_str(the_rest.first()?);
        Some((self.clients.get(&index_supplied)?.clone(), true, command))
    }
    fn login(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: &str,
        the_rest: &[&str],
        option_tx: Option<Sender<String>>,
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let password_1 = the_rest.join(" ");
        let tx = option_tx?;
        if let Some(account) = self.accounts.0.get_mut(username) {
            // The username is in the database and already logged in.
            if let Some(index_database) = account.logged_in {
                info!("{index_supplied} {username} login failed, {index_database} is logged in");
                Some(((tx), false, (*command).to_string()))
            // The username is in the database, but not logged in yet.
            } else {
                let hash_2 = PasswordHash::try_from(account.password.as_str()).ok()?;
                if let Err(_error) =
                    Argon2::default().verify_password(password_1.as_bytes(), &hash_2)
                {
                    info!("{index_supplied} {username} provided the wrong password");
                    return Some((tx, false, (*command).to_string()));
                }
                self.clients.insert(index_supplied, tx);
                account.logged_in = Some(index_supplied);
                account.last_logged_in = DateTimeUtc(Timestamp::now());
                Some((
                    self.clients.get(&index_supplied)?.clone(),
                    true,
                    (*command).to_string(),
                ))
            }
        // The username is not in the database.
        } else {
            info!("{index_supplied} {username} is not in the database");
            Some((tx, false, (*command).to_string()))
        }
    }
    fn load_data_files(
        &mut self,
        tx: Sender<(String, Option<Sender<String>>)>,
        systemd: bool,
    ) -> anyhow::Result<()> {
        let users_file = data_file(USERS_FILE);
        match &fs::read_to_string(&users_file) {
            Ok(string) => match ron::from_str(string.as_str()) {
                Ok(server_ron) => {
                    *self = server_ron;
                    self.tx = Some(tx.clone());
                    if let Some(tournament) = &mut self.tournament {
                        tournament.remove_duplicate_ids();
                    }
                    self.admins_tournament.insert("server".to_string());
                }
                Err(err) => {
                    return Err(anyhow::Error::msg(format!(
                        "RON: {}: {err}",
                        users_file.display(),
                    )));
                }
            },
            Err(err) => match err.kind() {
                ErrorKind::NotFound => {}
                _ => return Err(anyhow::Error::msg(err.to_string())),
            },
        }
        let archived_games_file = data_file(ARCHIVED_GAMES_FILE);
        match fs::read_to_string(&archived_games_file) {
            Ok(archived_games_string) => {
                let mut archived_games = Vec::new();
                for line in archived_games_string.lines() {
                    let archived_game: ArchivedGame = match ron::from_str(line) {
                        Ok(archived_game) => archived_game,
                        Err(err) => {
                            return Err(anyhow::Error::msg(format!(
                                "RON: {}: {err}",
                                archived_games_file.display(),
                            )));
                        }
                    };
                    archived_games.push(archived_game);
                }
                self.archived_games = archived_games;
            }
            Err(err) => {
                error!("archived games file not found: {err}");
            }
        }
        let active_games_file = data_file(ACTIVE_GAMES_FILE);
        if fs::exists(&active_games_file)? {
            let mut file = File::open(active_games_file)?;
            let mut data = Vec::new();
            file.read_to_end(&mut data)?;
            let games: Vec<ServerGameSerialized> = postcard::from_bytes(data.as_slice())?;
            for game in games {
                let id = game.id;
                let server_game_light = ServerGameLight::from(&game);
                let server_game = ServerGame::from(game);
                self.games_light.0.insert(id, server_game_light);
                self.games.0.insert(id, server_game);
            }
        }
        ctrlc::set_handler(move || {
            if !systemd {
                println!();
            }
            handle_error(tx.send(("0 server save".to_string(), None)));
            handle_error(tx.send(("0 server exit".to_string(), None)));
        })?;
        Ok(())
    }
    fn logout(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: &str,
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        // The username is in the database and already logged in.
        if let Some(account) = self.accounts.0.get_mut(username) {
            for id in &account.pending_games {
                if let Some(tx) = &self.tx
                    && let Some(game) = self.games_light.0.get(id)
                    && let TimeSettings::Timed(Time {
                        milliseconds_left, ..
                    }) = game.timed
                    && milliseconds_left < 1_000 * 60 * 60 * 24
                {
                    let _ok =
                        tx.send((format!("{index_supplied} {username} leave_game {id}"), None));
                }
            }
            if let Some(index_database) = account.logged_in
                && index_database == index_supplied
            {
                account.logged_in = None;
                account.last_logged_in = DateTimeUtc(Timestamp::now());
                self.clients
                    .get(&index_supplied)?
                    .send("= logout".to_string())
                    .ok()?;
                self.clients.remove(&index_database);
                return None;
            }
        }
        self.clients
            .get(&index_supplied)
            .map(|sender| (sender.clone(), false, (*command).to_string()))
    }
    /// ```sh
    /// <- new_game attacker rated fischer 900000 10 13
    /// -> = new_game game 6 player-1 _ rated fischer 900000 10 _ false {}
    /// ```
    fn new_game(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: &str,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        if the_rest.len() < 6 {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        }
        let role = the_rest.first()?;
        let Ok(role) = Role::from_str(role) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let rated = the_rest.get(1)?;
        let Ok(rated) = Rated::from_str(rated) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let timed = the_rest.get(2)?;
        let minutes = the_rest.get(3)?;
        let add_seconds = the_rest.get(4)?;
        let Ok(timed) = TimeSettings::try_from(vec!["time-settings", timed, minutes, add_seconds])
        else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let board_size = the_rest.get(5)?;
        let board_size = BoardSize::from_str(board_size).ok()?;
        info!(
            "{index_supplied} {username} new_game {} {role} {rated} {timed:?} {board_size}",
            self.game_id
        );
        let game = ServerGameLight::new(
            self.game_id,
            (*username).to_string(),
            rated,
            timed,
            board_size,
            role,
        );
        let command = format!("{command} {game:?}");
        self.games_light.0.insert(self.game_id, game);
        if let Some(account) = self.accounts.0.get_mut(username) {
            account.pending_games.insert(self.game_id);
        }
        self.game_id += 1;
        Some((self.clients.get(&index_supplied)?.clone(), true, command))
    }
    fn new_tournament(tx: Sender<(String, Option<Sender<String>>)>) {
        thread::spawn(move || {
            handle_error(tx.send(("0 server tournament_start".to_string(), None)));
            loop {
                let now = Zoned::now().with_time_zone(jiff::tz::TimeZone::UTC);
                match Zoned::now()
                    .with_time_zone(jiff::tz::TimeZone::UTC)
                    .end_of_day()
                {
                    Ok(midnight) => {
                        let duration = now.duration_until(&midnight);
                        debug!("midnight: {midnight}");
                        debug!("seconds until midnight: {}", duration.as_secs());
                        match duration.try_into() {
                            Ok(mut duration) => {
                                duration += Duration::from_secs(2);
                                sleep(duration);
                            }
                            Err(error) => {
                                error!("new_tournament (1): {error}");
                                exit(1);
                            }
                        }
                    }
                    Err(error) => {
                        error!("new_tournament (2): {error}");
                        exit(1);
                    }
                }
                handle_error(tx.send(("0 server tournament_start".to_string(), None)));
            }
        });
    }
    #[must_use]
    fn new_tournament_game(&mut self, attacker: &str, defender: &str) -> Id {
        let id = self.game_id;
        self.game_id += 1;
        let game_light = ServerGameLight {
            id,
            attacker: Some(attacker.to_string()),
            defender: Some(defender.to_string()),
            challenger: Challenger(None),
            rated: Rated::Yes,
            timed: TimeEnum::Long.into(),
            spectators: HashMap::new(),
            challenge_accepted: true,
            game_over: false,
            board_size: BoardSize::_11,
            turn: Role::Attacker,
        };
        info!(
            "0 server new_tournament_game {id} {} {:?} {}",
            game_light.rated, game_light.timed, game_light.board_size
        );
        let game = ServerGame::new(None, None, game_light.clone());
        self.games_light.0.insert(id, game_light);
        self.games.0.insert(id, game);
        id
    }
    fn resume_game(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: &str,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(id) = the_rest.first() else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Some(server_game) = self.games.0.get(&id) else {
            unreachable!()
        };
        let game = &server_game.game;
        let Ok(board) = ron::ser::to_string(game) else {
            unreachable!()
        };
        let texts = &server_game.texts;
        let Ok(texts) = ron::ser::to_string(&texts) else {
            unreachable!()
        };
        info!("{index_supplied} {username} {command} {id}");
        let Some(game_light) = self.games_light.0.get_mut(&id) else {
            unreachable!();
        };
        let mut channel_id = 0;
        if let Some(account) = self.accounts.0.get(username)
            && let Some(id) = account.logged_in
        {
            channel_id = id;
        }
        game_light
            .spectators
            .insert(username.to_string(), channel_id);
        let mut request_draw = Role::Roleless;
        if let Some(server_game) = self.games.0.get_mut(&id) {
            if Some(username) == game_light.attacker.as_deref() {
                server_game.attacker_tx =
                    Messenger::new(self.clients.get(&index_supplied)?.clone());
                if server_game.draw_requested == Role::Defender {
                    request_draw = Role::Attacker;
                }
            } else if Some(username) == game_light.defender.as_deref() {
                server_game.defender_tx =
                    Messenger::new(self.clients.get(&index_supplied)?.clone());
                if server_game.draw_requested == Role::Attacker {
                    request_draw = Role::Defender;
                }
            }
        }
        let client = self.clients.get(&index_supplied)?;
        client
            .send(format!(
                "= resume_game {} {} {} {:?} {} {board} {texts}",
                game_light.attacker.clone()?,
                game_light.defender.clone()?,
                game_light.rated,
                game_light.timed,
                game_light.board_size,
            ))
            .ok()?;
        if request_draw != Role::Roleless {
            client
                .send(format!("request_draw {} {request_draw}", game_light.id))
                .ok()?;
        }
        None
    }
    fn request_draw(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: &str,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(id) = the_rest.first() else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Some(role) = the_rest.get(1) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Ok(role) = Role::from_str(role) else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        info!("{index_supplied} {username} request_draw {id} {role}");
        if let Some(server_game) = self.games.0.get_mut(&id) {
            server_game.draw_requested = role;
        }
        let message = format!("request_draw {id} {role}");
        if let Some(game) = self.games.0.get(&id) {
            match role {
                Role::Attacker => {
                    game.defender_tx.send(message);
                }
                Role::Roleless => {}
                Role::Defender => {
                    game.attacker_tx.send(message);
                }
            }
        }
        Some((
            self.clients.get(&index_supplied)?.clone(),
            true,
            (*command).to_string(),
        ))
    }
    fn save(tx: Sender<(String, Option<Sender<String>>)>) {
        thread::spawn(move || {
            loop {
                thread::sleep(Duration::from_secs(HOUR_IN_SECONDS));
                handle_error(tx.send(("0 server save".to_string(), None)));
            }
        });
    }
    fn save_server(&self) {
        if !self.skip_the_data_files {
            let mut server = self.clone();
            for account in server.accounts.0.values_mut() {
                account.logged_in = None;
            }
            match ron::ser::to_string_pretty(&server, ron::ser::PrettyConfig::default()) {
                Ok(string) => {
                    if !string.trim().is_empty() {
                        let users_file = data_file(USERS_FILE);
                        match File::create(&users_file) {
                            Ok(mut file) => {
                                if let Err(error) = file.write_all(string.as_bytes()) {
                                    error!("save file (3): {error}");
                                }
                            }
                            Err(error) => error!("save file (2): {error}"),
                        }
                    }
                }
                Err(error) => error!("save file (1): {error}"),
            }
        }
    }
    fn sort_games_light(&mut self) {
        let mut games: Vec<_> = self
            .games_light
            .0
            .values()
            .map(|game| {
                let mut rating_1 = 0.0;
                let mut rating_2 = 0.0;
                if let Some(attacker) = &game.attacker
                    && let Some(account) = self.accounts.0.get(attacker)
                {
                    rating_1 = account.rating.rating;
                }
                if let Some(defender) = &game.defender
                    && let Some(account) = self.accounts.0.get(defender)
                {
                    rating_2 = account.rating.rating;
                    if rating_2 > rating_1 {
                        std::mem::swap(&mut rating_1, &mut rating_2);
                    }
                }
                (game, rating_1, rating_2)
            })
            .collect();
        games.sort_by(|a, b| b.2.total_cmp(&a.2));
        games.sort_by(|a, b| b.1.total_cmp(&a.1));
        self.games_light_vec =
            ServerGamesLightVec(games.iter().map(|(game, _, _)| (*game).clone()).collect());
    }
    fn text_game(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: &str,
        mut the_rest: Vec<&str>,
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(id) = the_rest.first() else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((
                self.clients.get(&index_supplied)?.clone(),
                false,
                (*command).to_string(),
            ));
        };
        let timestamp = timestamp();
        let text = the_rest.split_off(1);
        let mut text = text.join(" ");
        text = format!("{timestamp} {username}: {text}");
        info!("{index_supplied} {username} text_game {id} {text}");
        if let Some(game) = self.games.0.get_mut(&id) {
            game.texts.push_front(text.clone());
        }
        text = format!("= text_game {text}");
        if let Some(game) = self.games_light.0.get(&id) {
            for index in game.spectators.values() {
                if let Some(sender) = self.clients.get(index) {
                    let _ok = sender.send(text.clone());
                }
            }
        }
        None
    }
    fn tournament_date(&mut self, the_rest: &[&str]) -> anyhow::Result<()> {
        let mut tournament = Tournament::default();
        let Some(date) = the_rest.first() else {
            return Err(anyhow::Error::msg("tournament_date: date is empty"));
        };
        tournament.date = match date.parse() {
            Ok(timestamp) => timestamp,
            Err(error) => return Err(anyhow::Error::msg(format!("tournament_date: {error}"))),
        };
        self.tournament = Some(tournament);
        Ok(())
    }
    fn tournament_status_all(&self) {
        trace!("tournament_status: {:#?}", self.tournament);
        if let Ok(mut tournament) = ron::ser::to_string(&self.tournament) {
            tournament = format!("= tournament_status_0 {tournament}");
            for tx in self.clients.values() {
                let _ok = tx.send(tournament.clone());
            }
        }
    }
    fn watch_game(
        &mut self,
        username: &str,
        index_supplied: usize,
        command: String,
        the_rest: &[&str],
    ) -> Option<(mpsc::Sender<String>, bool, String)> {
        let Some(id) = the_rest.first() else {
            return Some((self.clients.get(&index_supplied)?.clone(), false, command));
        };
        let Ok(id) = id.parse::<Id>() else {
            return Some((self.clients.get(&index_supplied)?.clone(), false, command));
        };
        if let Some(game) = self.games_light.0.get_mut(&id) {
            game.spectators.insert(username.to_string(), index_supplied);
        }
        let Some(server_game) = self.games.0.get(&id) else {
            unreachable!()
        };
        let game = &server_game.game;
        let Ok(board) = ron::ser::to_string(game) else {
            unreachable!()
        };
        let texts = &server_game.texts;
        let Ok(texts) = ron::ser::to_string(&texts) else {
            unreachable!()
        };
        info!("{index_supplied} {username} watch_game {id}");
        let Some(game) = self.games_light.0.get_mut(&id) else {
            unreachable!()
        };
        self.clients
            .get(&index_supplied)?
            .send(format!(
                "= watch_game {} {} {} {:?} {} {board} {texts}",
                game.attacker.clone()?,
                game.defender.clone()?,
                game.rated,
                game.timed,
                game.board_size,
            ))
            .ok()?;
        None
    }
}