summaryrefslogtreecommitdiff
path: root/src/service/admin/mod.rs
blob: 9250a3efe995847a0799f14a535c376d22ef5cc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
use std::{
    collections::BTreeMap,
    convert::{TryFrom, TryInto},
    sync::Arc,
    time::Instant,
};

use clap::Parser;
use regex::Regex;
use ruma::{
    events::{
        room::{
            canonical_alias::RoomCanonicalAliasEventContent,
            create::RoomCreateEventContent,
            guest_access::{GuestAccess, RoomGuestAccessEventContent},
            history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
            join_rules::{JoinRule, RoomJoinRulesEventContent},
            member::{MembershipState, RoomMemberEventContent},
            message::RoomMessageEventContent,
            name::RoomNameEventContent,
            power_levels::RoomPowerLevelsEventContent,
            topic::RoomTopicEventContent,
        },
        TimelineEventType,
    },
    EventId, OwnedRoomAliasId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
};
use serde_json::value::to_raw_value;
use tokio::sync::{mpsc, Mutex, MutexGuard};

use crate::{
    api::client_server::{leave_all_rooms, AUTO_GEN_PASSWORD_LENGTH},
    services,
    utils::{self, HtmlEscape},
    Error, PduEvent, Result,
};

use super::pdu::PduBuilder;

#[cfg_attr(test, derive(Debug))]
#[derive(Parser)]
#[command(name = "@conduit:server.name:", version = env!("CARGO_PKG_VERSION"))]
enum AdminCommand {
    #[command(verbatim_doc_comment)]
    /// Register an appservice using its registration YAML
    ///
    /// This command needs a YAML generated by an appservice (such as a bridge),
    /// which must be provided in a Markdown code-block below the command.
    ///
    /// Registering a new bridge using the ID of an existing bridge will replace
    /// the old one.
    ///
    /// [commandbody]
    /// # ```
    /// # yaml content here
    /// # ```
    RegisterAppservice,

    /// Unregister an appservice using its ID
    ///
    /// You can find the ID using the `list-appservices` command.
    UnregisterAppservice {
        /// The appservice to unregister
        appservice_identifier: String,
    },

    /// List all the currently registered appservices
    ListAppservices,

    /// List all rooms the server knows about
    ListRooms,

    /// List users in the database
    ListLocalUsers,

    /// List all rooms we are currently handling an incoming pdu from
    IncomingFederation,

    /// Deactivate a user
    ///
    /// User will not be removed from all rooms by default.
    /// Use --leave-rooms to force the user to leave all rooms
    DeactivateUser {
        #[arg(short, long)]
        leave_rooms: bool,
        user_id: Box<UserId>,
    },

    #[command(verbatim_doc_comment)]
    /// Deactivate a list of users
    ///
    /// Recommended to use in conjunction with list-local-users.
    ///
    /// Users will not be removed from joined rooms by default.
    /// Can be overridden with --leave-rooms flag.
    /// Removing a mass amount of users from a room may cause a significant amount of leave events.
    /// The time to leave rooms may depend significantly on joined rooms and servers.
    ///
    /// [commandbody]
    /// # ```
    /// # User list here
    /// # ```
    DeactivateAll {
        #[arg(short, long)]
        /// Remove users from their joined rooms
        leave_rooms: bool,
        #[arg(short, long)]
        /// Also deactivate admin accounts
        force: bool,
    },

    /// Get the auth_chain of a PDU
    GetAuthChain {
        /// An event ID (the $ character followed by the base64 reference hash)
        event_id: Box<EventId>,
    },

    #[command(verbatim_doc_comment)]
    /// Parse and print a PDU from a JSON
    ///
    /// The PDU event is only checked for validity and is not added to the
    /// database.
    ///
    /// [commandbody]
    /// # ```
    /// # PDU json content here
    /// # ```
    ParsePdu,

    /// Retrieve and print a PDU by ID from the Conduit database
    GetPdu {
        /// An event ID (a $ followed by the base64 reference hash)
        event_id: Box<EventId>,
    },

    /// Print database memory usage statistics
    MemoryUsage,

    /// Clears all of Conduit's database caches with index smaller than the amount
    ClearDatabaseCaches { amount: u32 },

    /// Clears all of Conduit's service caches with index smaller than the amount
    ClearServiceCaches { amount: u32 },

    /// Show configuration values
    ShowConfig,

    /// Reset user password
    ResetPassword {
        /// Username of the user for whom the password should be reset
        username: String,
    },

    /// Create a new user
    CreateUser {
        /// Username of the new user
        username: String,
        /// Password of the new user, if unspecified one is generated
        password: Option<String>,
    },

    /// Disables incoming federation handling for a room.
    DisableRoom { room_id: Box<RoomId> },
    /// Enables incoming federation handling for a room again.
    EnableRoom { room_id: Box<RoomId> },
}

#[derive(Debug)]
pub enum AdminRoomEvent {
    ProcessMessage(String),
    SendMessage(RoomMessageEventContent),
}

pub struct Service {
    pub sender: mpsc::UnboundedSender<AdminRoomEvent>,
    receiver: Mutex<mpsc::UnboundedReceiver<AdminRoomEvent>>,
}

impl Service {
    pub fn build() -> Arc<Self> {
        let (sender, receiver) = mpsc::unbounded_channel();
        Arc::new(Self {
            sender,
            receiver: Mutex::new(receiver),
        })
    }

    pub fn start_handler(self: &Arc<Self>) {
        let self2 = Arc::clone(self);
        tokio::spawn(async move {
            self2.handler().await;
        });
    }

    async fn handler(&self) {
        let mut receiver = self.receiver.lock().await;
        // TODO: Use futures when we have long admin commands
        //let mut futures = FuturesUnordered::new();

        let conduit_user = UserId::parse(format!("@conduit:{}", services().globals.server_name()))
            .expect("@conduit:server_name is valid");

        let conduit_room = services()
            .rooms
            .alias
            .resolve_local_alias(
                format!("#admins:{}", services().globals.server_name())
                    .as_str()
                    .try_into()
                    .expect("#admins:server_name is a valid room alias"),
            )
            .expect("Database data for admin room alias must be valid")
            .expect("Admin room must exist");

        let send_message = |message: RoomMessageEventContent, mutex_lock: &MutexGuard<'_, ()>| {
            services()
                .rooms
                .timeline
                .build_and_append_pdu(
                    PduBuilder {
                        event_type: TimelineEventType::RoomMessage,
                        content: to_raw_value(&message)
                            .expect("event is valid, we just created it"),
                        unsigned: None,
                        state_key: None,
                        redacts: None,
                    },
                    &conduit_user,
                    &conduit_room,
                    mutex_lock,
                )
                .unwrap();
        };

        loop {
            tokio::select! {
                Some(event) = receiver.recv() => {
                    let message_content = match event {
                        AdminRoomEvent::SendMessage(content) => content,
                        AdminRoomEvent::ProcessMessage(room_message) => self.process_admin_message(room_message).await
                    };

                    let mutex_state = Arc::clone(
                        services().globals
                            .roomid_mutex_state
                            .write()
                            .unwrap()
                            .entry(conduit_room.to_owned())
                            .or_default(),
                    );

                    let state_lock = mutex_state.lock().await;

                    send_message(message_content, &state_lock);

                    drop(state_lock);
                }
            }
        }
    }

    pub fn process_message(&self, room_message: String) {
        self.sender
            .send(AdminRoomEvent::ProcessMessage(room_message))
            .unwrap();
    }

    pub fn send_message(&self, message_content: RoomMessageEventContent) {
        self.sender
            .send(AdminRoomEvent::SendMessage(message_content))
            .unwrap();
    }

    // Parse and process a message from the admin room
    async fn process_admin_message(&self, room_message: String) -> RoomMessageEventContent {
        let mut lines = room_message.lines();
        let command_line = lines.next().expect("each string has at least one line");
        let body: Vec<_> = lines.collect();

        let admin_command = match self.parse_admin_command(command_line) {
            Ok(command) => command,
            Err(error) => {
                let server_name = services().globals.server_name();
                let message = error.replace("server.name", server_name.as_str());
                let html_message = self.usage_to_html(&message, server_name);

                return RoomMessageEventContent::text_html(message, html_message);
            }
        };

        match self.process_admin_command(admin_command, body).await {
            Ok(reply_message) => reply_message,
            Err(error) => {
                let markdown_message = format!(
                    "Encountered an error while handling the command:\n\
                    ```\n{error}\n```",
                );
                let html_message = format!(
                    "Encountered an error while handling the command:\n\
                    <pre>\n{error}\n</pre>",
                );

                RoomMessageEventContent::text_html(markdown_message, html_message)
            }
        }
    }

    // Parse chat messages from the admin room into an AdminCommand object
    fn parse_admin_command(&self, command_line: &str) -> std::result::Result<AdminCommand, String> {
        // Note: argv[0] is `@conduit:servername:`, which is treated as the main command
        let mut argv: Vec<_> = command_line.split_whitespace().collect();

        // Replace `help command` with `command --help`
        // Clap has a help subcommand, but it omits the long help description.
        if argv.len() > 1 && argv[1] == "help" {
            argv.remove(1);
            argv.push("--help");
        }

        // Backwards compatibility with `register_appservice`-style commands
        let command_with_dashes;
        if argv.len() > 1 && argv[1].contains('_') {
            command_with_dashes = argv[1].replace('_', "-");
            argv[1] = &command_with_dashes;
        }

        AdminCommand::try_parse_from(argv).map_err(|error| error.to_string())
    }

    async fn process_admin_command(
        &self,
        command: AdminCommand,
        body: Vec<&str>,
    ) -> Result<RoomMessageEventContent> {
        let reply_message_content = match command {
            AdminCommand::RegisterAppservice => {
                if body.len() > 2 && body[0].trim() == "```" && body.last().unwrap().trim() == "```"
                {
                    let appservice_config = body[1..body.len() - 1].join("\n");
                    let parsed_config =
                        serde_yaml::from_str::<serde_yaml::Value>(&appservice_config);
                    match parsed_config {
                        Ok(yaml) => match services().appservice.register_appservice(yaml) {
                            Ok(id) => RoomMessageEventContent::text_plain(format!(
                                "Appservice registered with ID: {id}."
                            )),
                            Err(e) => RoomMessageEventContent::text_plain(format!(
                                "Failed to register appservice: {e}"
                            )),
                        },
                        Err(e) => RoomMessageEventContent::text_plain(format!(
                            "Could not parse appservice config: {e}"
                        )),
                    }
                } else {
                    RoomMessageEventContent::text_plain(
                        "Expected code block in command body. Add --help for details.",
                    )
                }
            }
            AdminCommand::UnregisterAppservice {
                appservice_identifier,
            } => match services()
                .appservice
                .unregister_appservice(&appservice_identifier)
            {
                Ok(()) => RoomMessageEventContent::text_plain("Appservice unregistered."),
                Err(e) => RoomMessageEventContent::text_plain(format!(
                    "Failed to unregister appservice: {e}"
                )),
            },
            AdminCommand::ListAppservices => {
                if let Ok(appservices) = services()
                    .appservice
                    .iter_ids()
                    .map(|ids| ids.collect::<Vec<_>>())
                {
                    let count = appservices.len();
                    let output = format!(
                        "Appservices ({}): {}",
                        count,
                        appservices
                            .into_iter()
                            .filter_map(|r| r.ok())
                            .collect::<Vec<_>>()
                            .join(", ")
                    );
                    RoomMessageEventContent::text_plain(output)
                } else {
                    RoomMessageEventContent::text_plain("Failed to get appservices.")
                }
            }
            AdminCommand::ListRooms => {
                let room_ids = services().rooms.metadata.iter_ids();
                let output = format!(
                    "Rooms:\n{}",
                    room_ids
                        .filter_map(|r| r.ok())
                        .map(|id| id.to_string()
                            + "\tMembers: "
                            + &services()
                                .rooms
                                .state_cache
                                .room_joined_count(&id)
                                .ok()
                                .flatten()
                                .unwrap_or(0)
                                .to_string())
                        .collect::<Vec<_>>()
                        .join("\n")
                );
                RoomMessageEventContent::text_plain(output)
            }
            AdminCommand::ListLocalUsers => match services().users.list_local_users() {
                Ok(users) => {
                    let mut msg: String = format!("Found {} local user account(s):\n", users.len());
                    msg += &users.join("\n");
                    RoomMessageEventContent::text_plain(&msg)
                }
                Err(e) => RoomMessageEventContent::text_plain(e.to_string()),
            },
            AdminCommand::IncomingFederation => {
                let map = services()
                    .globals
                    .roomid_federationhandletime
                    .read()
                    .unwrap();
                let mut msg: String = format!("Handling {} incoming pdus:\n", map.len());

                for (r, (e, i)) in map.iter() {
                    let elapsed = i.elapsed();
                    msg += &format!(
                        "{} {}: {}m{}s\n",
                        r,
                        e,
                        elapsed.as_secs() / 60,
                        elapsed.as_secs() % 60
                    );
                }
                RoomMessageEventContent::text_plain(&msg)
            }
            AdminCommand::GetAuthChain { event_id } => {
                let event_id = Arc::<EventId>::from(event_id);
                if let Some(event) = services().rooms.timeline.get_pdu_json(&event_id)? {
                    let room_id_str = event
                        .get("room_id")
                        .and_then(|val| val.as_str())
                        .ok_or_else(|| Error::bad_database("Invalid event in database"))?;

                    let room_id = <&RoomId>::try_from(room_id_str).map_err(|_| {
                        Error::bad_database("Invalid room id field in event in database")
                    })?;
                    let start = Instant::now();
                    let count = services()
                        .rooms
                        .auth_chain
                        .get_auth_chain(room_id, vec![event_id])
                        .await?
                        .count();
                    let elapsed = start.elapsed();
                    RoomMessageEventContent::text_plain(format!(
                        "Loaded auth chain with length {count} in {elapsed:?}"
                    ))
                } else {
                    RoomMessageEventContent::text_plain("Event not found.")
                }
            }
            AdminCommand::ParsePdu => {
                if body.len() > 2 && body[0].trim() == "```" && body.last().unwrap().trim() == "```"
                {
                    let string = body[1..body.len() - 1].join("\n");
                    match serde_json::from_str(&string) {
                        Ok(value) => {
                            match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
                                Ok(hash) => {
                                    let event_id = EventId::parse(format!("${hash}"));

                                    match serde_json::from_value::<PduEvent>(
                                        serde_json::to_value(value).expect("value is json"),
                                    ) {
                                        Ok(pdu) => RoomMessageEventContent::text_plain(format!(
                                            "EventId: {event_id:?}\n{pdu:#?}"
                                        )),
                                        Err(e) => RoomMessageEventContent::text_plain(format!(
                                            "EventId: {event_id:?}\nCould not parse event: {e}"
                                        )),
                                    }
                                }
                                Err(e) => RoomMessageEventContent::text_plain(format!(
                                    "Could not parse PDU JSON: {e:?}"
                                )),
                            }
                        }
                        Err(e) => RoomMessageEventContent::text_plain(format!(
                            "Invalid json in command body: {e}"
                        )),
                    }
                } else {
                    RoomMessageEventContent::text_plain("Expected code block in command body.")
                }
            }
            AdminCommand::GetPdu { event_id } => {
                let mut outlier = false;
                let mut pdu_json = services()
                    .rooms
                    .timeline
                    .get_non_outlier_pdu_json(&event_id)?;
                if pdu_json.is_none() {
                    outlier = true;
                    pdu_json = services().rooms.timeline.get_pdu_json(&event_id)?;
                }
                match pdu_json {
                    Some(json) => {
                        let json_text = serde_json::to_string_pretty(&json)
                            .expect("canonical json is valid json");
                        RoomMessageEventContent::text_html(
                            format!(
                                "{}\n```json\n{}\n```",
                                if outlier {
                                    "PDU is outlier"
                                } else {
                                    "PDU was accepted"
                                },
                                json_text
                            ),
                            format!(
                                "<p>{}</p>\n<pre><code class=\"language-json\">{}\n</code></pre>\n",
                                if outlier {
                                    "PDU is outlier"
                                } else {
                                    "PDU was accepted"
                                },
                                HtmlEscape(&json_text)
                            ),
                        )
                    }
                    None => RoomMessageEventContent::text_plain("PDU not found."),
                }
            }
            AdminCommand::MemoryUsage => {
                let response1 = services().memory_usage();
                let response2 = services().globals.db.memory_usage();

                RoomMessageEventContent::text_plain(format!(
                    "Services:\n{response1}\n\nDatabase:\n{response2}"
                ))
            }
            AdminCommand::ClearDatabaseCaches { amount } => {
                services().globals.db.clear_caches(amount);

                RoomMessageEventContent::text_plain("Done.")
            }
            AdminCommand::ClearServiceCaches { amount } => {
                services().clear_caches(amount);

                RoomMessageEventContent::text_plain("Done.")
            }
            AdminCommand::ShowConfig => {
                // Construct and send the response
                RoomMessageEventContent::text_plain(format!("{}", services().globals.config))
            }
            AdminCommand::ResetPassword { username } => {
                let user_id = match UserId::parse_with_server_name(
                    username.as_str().to_lowercase(),
                    services().globals.server_name(),
                ) {
                    Ok(id) => id,
                    Err(e) => {
                        return Ok(RoomMessageEventContent::text_plain(format!(
                            "The supplied username is not a valid username: {e}"
                        )))
                    }
                };

                // Check if the specified user is valid
                if !services().users.exists(&user_id)?
                    || user_id
                        == UserId::parse_with_server_name(
                            "conduit",
                            services().globals.server_name(),
                        )
                        .expect("conduit user exists")
                {
                    return Ok(RoomMessageEventContent::text_plain(
                        "The specified user does not exist!",
                    ));
                }

                let new_password = utils::random_string(AUTO_GEN_PASSWORD_LENGTH);

                match services()
                    .users
                    .set_password(&user_id, Some(new_password.as_str()))
                {
                    Ok(()) => RoomMessageEventContent::text_plain(format!(
                        "Successfully reset the password for user {user_id}: {new_password}"
                    )),
                    Err(e) => RoomMessageEventContent::text_plain(format!(
                        "Couldn't reset the password for user {user_id}: {e}"
                    )),
                }
            }
            AdminCommand::CreateUser { username, password } => {
                let password =
                    password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
                // Validate user id
                let user_id = match UserId::parse_with_server_name(
                    username.as_str().to_lowercase(),
                    services().globals.server_name(),
                ) {
                    Ok(id) => id,
                    Err(e) => {
                        return Ok(RoomMessageEventContent::text_plain(format!(
                            "The supplied username is not a valid username: {e}"
                        )))
                    }
                };
                if user_id.is_historical() {
                    return Ok(RoomMessageEventContent::text_plain(format!(
                        "Userid {user_id} is not allowed due to historical"
                    )));
                }
                if services().users.exists(&user_id)? {
                    return Ok(RoomMessageEventContent::text_plain(format!(
                        "Userid {user_id} already exists"
                    )));
                }
                // Create user
                services().users.create(&user_id, Some(password.as_str()))?;

                // Default to pretty displayname
                let mut displayname = user_id.localpart().to_owned();

                // If enabled append lightning bolt to display name (default true)
                if services().globals.enable_lightning_bolt() {
                    displayname.push_str(" ⚡️");
                }

                services()
                    .users
                    .set_displayname(&user_id, Some(displayname))?;

                // Initial account data
                services().account_data.update(
                    None,
                    &user_id,
                    ruma::events::GlobalAccountDataEventType::PushRules
                        .to_string()
                        .into(),
                    &serde_json::to_value(ruma::events::push_rules::PushRulesEvent {
                        content: ruma::events::push_rules::PushRulesEventContent {
                            global: ruma::push::Ruleset::server_default(&user_id),
                        },
                    })
                    .expect("to json value always works"),
                )?;

                // we dont add a device since we're not the user, just the creator

                // Inhibit login does not work for guests
                RoomMessageEventContent::text_plain(format!(
                    "Created user with user_id: {user_id} and password: {password}"
                ))
            }
            AdminCommand::DisableRoom { room_id } => {
                services().rooms.metadata.disable_room(&room_id, true)?;
                RoomMessageEventContent::text_plain("Room disabled.")
            }
            AdminCommand::EnableRoom { room_id } => {
                services().rooms.metadata.disable_room(&room_id, false)?;
                RoomMessageEventContent::text_plain("Room enabled.")
            }
            AdminCommand::DeactivateUser {
                leave_rooms,
                user_id,
            } => {
                let user_id = Arc::<UserId>::from(user_id);
                if services().users.exists(&user_id)? {
                    RoomMessageEventContent::text_plain(format!(
                        "Making {user_id} leave all rooms before deactivation..."
                    ));

                    services().users.deactivate_account(&user_id)?;

                    if leave_rooms {
                        leave_all_rooms(&user_id).await?;
                    }

                    RoomMessageEventContent::text_plain(format!(
                        "User {user_id} has been deactivated"
                    ))
                } else {
                    RoomMessageEventContent::text_plain(format!(
                        "User {user_id} doesn't exist on this server"
                    ))
                }
            }
            AdminCommand::DeactivateAll { leave_rooms, force } => {
                if body.len() > 2 && body[0].trim() == "```" && body.last().unwrap().trim() == "```"
                {
                    let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();

                    let mut user_ids: Vec<&UserId> = Vec::new();

                    for &username in &usernames {
                        match <&UserId>::try_from(username) {
                            Ok(user_id) => user_ids.push(user_id),
                            Err(_) => {
                                return Ok(RoomMessageEventContent::text_plain(format!(
                                    "{username} is not a valid username"
                                )))
                            }
                        }
                    }

                    let mut deactivation_count = 0;
                    let mut admins = Vec::new();

                    if !force {
                        user_ids.retain(|&user_id| match services().users.is_admin(user_id) {
                            Ok(is_admin) => match is_admin {
                                true => {
                                    admins.push(user_id.localpart());
                                    false
                                }
                                false => true,
                            },
                            Err(_) => false,
                        })
                    }

                    for &user_id in &user_ids {
                        if services().users.deactivate_account(user_id).is_ok() {
                            deactivation_count += 1
                        }
                    }

                    if leave_rooms {
                        for &user_id in &user_ids {
                            let _ = leave_all_rooms(user_id).await;
                        }
                    }

                    if admins.is_empty() {
                        RoomMessageEventContent::text_plain(format!(
                            "Deactivated {deactivation_count} accounts."
                        ))
                    } else {
                        RoomMessageEventContent::text_plain(format!("Deactivated {} accounts.\nSkipped admin accounts: {:?}. Use --force to deactivate admin accounts", deactivation_count, admins.join(", ")))
                    }
                } else {
                    RoomMessageEventContent::text_plain(
                        "Expected code block in command body. Add --help for details.",
                    )
                }
            }
        };

        Ok(reply_message_content)
    }

    // Utility to turn clap's `--help` text to HTML.
    fn usage_to_html(&self, text: &str, server_name: &ServerName) -> String {
        // Replace `@conduit:servername:-subcmdname` with `@conduit:servername: subcmdname`
        let text = text.replace(
            &format!("@conduit:{server_name}:-"),
            &format!("@conduit:{server_name}: "),
        );

        // For the conduit admin room, subcommands become main commands
        let text = text.replace("SUBCOMMAND", "COMMAND");
        let text = text.replace("subcommand", "command");

        // Escape option names (e.g. `<element-id>`) since they look like HTML tags
        let text = text.replace('<', "&lt;").replace('>', "&gt;");

        // Italicize the first line (command name and version text)
        let re = Regex::new("^(.*?)\n").expect("Regex compilation should not fail");
        let text = re.replace_all(&text, "<em>$1</em>\n");

        // Unmerge wrapped lines
        let text = text.replace("\n            ", "  ");

        // Wrap option names in backticks. The lines look like:
        //     -V, --version  Prints version information
        // And are converted to:
        // <code>-V, --version</code>: Prints version information
        // (?m) enables multi-line mode for ^ and $
        let re = Regex::new("(?m)^    (([a-zA-Z_&;-]+(, )?)+)  +(.*)$")
            .expect("Regex compilation should not fail");
        let text = re.replace_all(&text, "<code>$1</code>: $4");

        // Look for a `[commandbody]` tag. If it exists, use all lines below it that
        // start with a `#` in the USAGE section.
        let mut text_lines: Vec<&str> = text.lines().collect();
        let mut command_body = String::new();

        if let Some(line_index) = text_lines.iter().position(|line| *line == "[commandbody]") {
            text_lines.remove(line_index);

            while text_lines
                .get(line_index)
                .map(|line| line.starts_with('#'))
                .unwrap_or(false)
            {
                command_body += if text_lines[line_index].starts_with("# ") {
                    &text_lines[line_index][2..]
                } else {
                    &text_lines[line_index][1..]
                };
                command_body += "[nobr]\n";
                text_lines.remove(line_index);
            }
        }

        let text = text_lines.join("\n");

        // Improve the usage section
        let text = if command_body.is_empty() {
            // Wrap the usage line in code tags
            let re = Regex::new("(?m)^USAGE:\n    (@conduit:.*)$")
                .expect("Regex compilation should not fail");
            re.replace_all(&text, "USAGE:\n<code>$1</code>").to_string()
        } else {
            // Wrap the usage line in a code block, and add a yaml block example
            // This makes the usage of e.g. `register-appservice` more accurate
            let re = Regex::new("(?m)^USAGE:\n    (.*?)\n\n")
                .expect("Regex compilation should not fail");
            re.replace_all(&text, "USAGE:\n<pre>$1[nobr]\n[commandbodyblock]</pre>")
                .replace("[commandbodyblock]", &command_body)
        };

        // Add HTML line-breaks

        text.replace("\n\n\n", "\n\n")
            .replace('\n', "<br>\n")
            .replace("[nobr]<br>", "")
    }

    /// Create the admin room.
    ///
    /// Users in this room are considered admins by conduit, and the room can be
    /// used to issue admin commands by talking to the server user inside it.
    pub(crate) async fn create_admin_room(&self) -> Result<()> {
        let room_id = RoomId::new(services().globals.server_name());

        services().rooms.short.get_or_create_shortroomid(&room_id)?;

        let mutex_state = Arc::clone(
            services()
                .globals
                .roomid_mutex_state
                .write()
                .unwrap()
                .entry(room_id.clone())
                .or_default(),
        );
        let state_lock = mutex_state.lock().await;

        // Create a user for the server
        let conduit_user =
            UserId::parse_with_server_name("conduit", services().globals.server_name())
                .expect("@conduit:server_name is valid");

        services().users.create(&conduit_user, None)?;

        let mut content = RoomCreateEventContent::new(conduit_user.clone());
        content.federate = true;
        content.predecessor = None;
        content.room_version = services().globals.default_room_version();

        // 1. The room create event
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomCreate,
                content: to_raw_value(&content).expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 2. Make conduit bot join
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomMember,
                content: to_raw_value(&RoomMemberEventContent {
                    membership: MembershipState::Join,
                    displayname: None,
                    avatar_url: None,
                    is_direct: None,
                    third_party_invite: None,
                    blurhash: None,
                    reason: None,
                    join_authorized_via_users_server: None,
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some(conduit_user.to_string()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 3. Power levels
        let mut users = BTreeMap::new();
        users.insert(conduit_user.clone(), 100.into());

        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomPowerLevels,
                content: to_raw_value(&RoomPowerLevelsEventContent {
                    users,
                    ..Default::default()
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 4.1 Join Rules
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomJoinRules,
                content: to_raw_value(&RoomJoinRulesEventContent::new(JoinRule::Invite))
                    .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 4.2 History Visibility
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomHistoryVisibility,
                content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
                    HistoryVisibility::Shared,
                ))
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 4.3 Guest Access
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomGuestAccess,
                content: to_raw_value(&RoomGuestAccessEventContent::new(GuestAccess::Forbidden))
                    .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 5. Events implied by name and topic
        let room_name = format!("{} Admin Room", services().globals.server_name());
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomName,
                content: to_raw_value(&RoomNameEventContent::new(Some(room_name)))
                    .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomTopic,
                content: to_raw_value(&RoomTopicEventContent {
                    topic: format!("Manage {}", services().globals.server_name()),
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // 6. Room alias
        let alias: OwnedRoomAliasId = format!("#admins:{}", services().globals.server_name())
            .try_into()
            .expect("#admins:server_name is a valid alias name");

        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomCanonicalAlias,
                content: to_raw_value(&RoomCanonicalAliasEventContent {
                    alias: Some(alias.clone()),
                    alt_aliases: Vec::new(),
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        services().rooms.alias.set_alias(&alias, &room_id)?;

        Ok(())
    }

    /// Invite the user to the conduit admin room.
    ///
    /// In conduit, this is equivalent to granting admin privileges.
    pub(crate) async fn make_user_admin(
        &self,
        user_id: &UserId,
        displayname: String,
    ) -> Result<()> {
        let admin_room_alias: Box<RoomAliasId> =
            format!("#admins:{}", services().globals.server_name())
                .try_into()
                .expect("#admins:server_name is a valid alias name");
        let room_id = services()
            .rooms
            .alias
            .resolve_local_alias(&admin_room_alias)?
            .expect("Admin room must exist");

        let mutex_state = Arc::clone(
            services()
                .globals
                .roomid_mutex_state
                .write()
                .unwrap()
                .entry(room_id.clone())
                .or_default(),
        );
        let state_lock = mutex_state.lock().await;

        // Use the server user to grant the new admin's power level
        let conduit_user =
            UserId::parse_with_server_name("conduit", services().globals.server_name())
                .expect("@conduit:server_name is valid");

        // Invite and join the real user
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomMember,
                content: to_raw_value(&RoomMemberEventContent {
                    membership: MembershipState::Invite,
                    displayname: None,
                    avatar_url: None,
                    is_direct: None,
                    third_party_invite: None,
                    blurhash: None,
                    reason: None,
                    join_authorized_via_users_server: None,
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some(user_id.to_string()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomMember,
                content: to_raw_value(&RoomMemberEventContent {
                    membership: MembershipState::Join,
                    displayname: Some(displayname),
                    avatar_url: None,
                    is_direct: None,
                    third_party_invite: None,
                    blurhash: None,
                    reason: None,
                    join_authorized_via_users_server: None,
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some(user_id.to_string()),
                redacts: None,
            },
            user_id,
            &room_id,
            &state_lock,
        )?;

        // Set power level
        let mut users = BTreeMap::new();
        users.insert(conduit_user.to_owned(), 100.into());
        users.insert(user_id.to_owned(), 100.into());

        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomPowerLevels,
                content: to_raw_value(&RoomPowerLevelsEventContent {
                    users,
                    ..Default::default()
                })
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: Some("".to_owned()),
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        // Send welcome message
        services().rooms.timeline.build_and_append_pdu(
            PduBuilder {
                event_type: TimelineEventType::RoomMessage,
                content: to_raw_value(&RoomMessageEventContent::text_html(
                        format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", services().globals.server_name()),
                        format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", services().globals.server_name()),
                ))
                .expect("event is valid, we just created it"),
                unsigned: None,
                state_key: None,
                redacts: None,
            },
            &conduit_user,
            &room_id,
            &state_lock,
        )?;

        Ok(())
    }
}

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

    #[test]
    fn get_help_short() {
        get_help_inner("-h");
    }

    #[test]
    fn get_help_long() {
        get_help_inner("--help");
    }

    #[test]
    fn get_help_subcommand() {
        get_help_inner("help");
    }

    fn get_help_inner(input: &str) {
        let error = AdminCommand::try_parse_from(["argv[0] doesn't matter", input])
            .unwrap_err()
            .to_string();

        // Search for a handful of keywords that suggest the help printed properly
        assert!(error.contains("Usage:"));
        assert!(error.contains("Commands:"));
        assert!(error.contains("Options:"));
    }
}