Commit 4cc5777b63

4cc5777b630ba4d6a9c964248531f283178a4717

parent: a7f92976d1

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2024-10-16 14:30 UTC
committer: <me@panekj.dev>

weechat-matrix: verification support

Layout: unified · split

Cargo.lock +63 −1
@@ -400,12 +400,24 @@ version = "3.7.0"
400400source = "registry+https://github.com/rust-lang/crates.io-index"
401401checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631"
402402
403[[package]]
404name = "bytemuck"
405version = "1.23.0"
406source = "registry+https://github.com/rust-lang/crates.io-index"
407checksum = "9134a6ef01ce4b366b50689c94f82c14bc72bc5d0386829828a2e2752ef7958c"
408
403409[[package]]
404410name = "byteorder"
405411version = "1.5.0"
406412source = "registry+https://github.com/rust-lang/crates.io-index"
407413checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
408414
415[[package]]
416name = "byteorder-lite"
417version = "0.1.0"
418source = "registry+https://github.com/rust-lang/crates.io-index"
419checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
420
409421[[package]]
410422name = "bytes"
411423version = "1.10.1"
@@ -1631,6 +1643,19 @@ dependencies = [
16311643 "icu_properties",
16321644]
16331645
1646[[package]]
1647name = "image"
1648version = "0.25.6"
1649source = "registry+https://github.com/rust-lang/crates.io-index"
1650checksum = "db35664ce6b9810857a38a906215e75a9c879f0696556a39f59c62829710251a"
1651dependencies = [
1652 "bytemuck",
1653 "byteorder-lite",
1654 "num-traits",
1655 "zune-core",
1656 "zune-jpeg",
1657]
1658
16341659[[package]]
16351660name = "imbl"
16361661version = "5.0.0"
@@ -2170,6 +2195,7 @@ dependencies = [
21702195 "itertools 0.14.0",
21712196 "js_option",
21722197 "matrix-sdk-common",
2198 "matrix-sdk-qrcode",
21732199 "pbkdf2",
21742200 "rand 0.8.5",
21752201 "rmp-serde",
@@ -2219,6 +2245,19 @@ dependencies = [
22192245 "zeroize",
22202246]
22212247
2248[[package]]
2249name = "matrix-sdk-qrcode"
2250version = "0.14.0"
2251source = "registry+https://github.com/rust-lang/crates.io-index"
2252checksum = "6e46baa0a7fd0e6e648887c0edfeb739682f7e12242986ffdf4300791cdbe199"
2253dependencies = [
2254 "byteorder",
2255 "qrcode",
2256 "ruma",
2257 "thiserror 2.0.16",
2258 "vodozemac",
2259]
2260
22222261[[package]]
22232262name = "matrix-sdk-search"
22242263version = "0.14.0"
@@ -2761,7 +2800,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
27612800checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
27622801dependencies = [
27632802 "anyhow",
2764 "itertools 0.14.0",
2803 "itertools 0.12.1",
27652804 "proc-macro2",
27662805 "quote",
27672806 "syn 2.0.87",
@@ -2785,6 +2824,12 @@ version = "0.11.0"
27852824source = "registry+https://github.com/rust-lang/crates.io-index"
27862825checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
27872826
2827[[package]]
2828name = "qrcode"
2829version = "0.14.1"
2830source = "registry+https://github.com/rust-lang/crates.io-index"
2831checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
2832
27882833[[package]]
27892834name = "quote"
27902835version = "1.0.37"
@@ -4528,7 +4573,9 @@ dependencies = [
45284573 "chrono",
45294574 "clap",
45304575 "dashmap",
4576 "image",
45314577 "matrix-sdk",
4578 "qrcode",
45324579 "serde_json",
45334580 "strum",
45344581 "tokio",
@@ -4852,3 +4899,18 @@ dependencies = [
48524899 "cc",
48534900 "pkg-config",
48544901]
4902
4903[[package]]
4904name = "zune-core"
4905version = "0.4.12"
4906source = "registry+https://github.com/rust-lang/crates.io-index"
4907checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
4908
4909[[package]]
4910name = "zune-jpeg"
4911version = "0.4.21"
4912source = "registry+https://github.com/rust-lang/crates.io-index"
4913checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
4914dependencies = [
4915 "zune-core",
4916]
Cargo.toml +5 −1
@@ -26,6 +26,10 @@ tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
2626uuid = { version = "1.1.2", features = ["v4"] }
2727unicode-segmentation = "1.10.0"
2828
29# Auto-select version from matrix-sdk
30qrcode = { version = "*", default-features = false }
31image = { version = "*", default-features = false, features = ["jpeg"] }
32
2933[dependencies.weechat]
3034git = "https://github.com/poljar/rust-weechat"
3135features = ["async", "config_macro"]
@@ -34,7 +38,7 @@ features = ["async", "config_macro"]
3438version = "0.14.0"
3539# git = "https://github.com/matrix-org/matrix-rust-sdk.git"
3640# rev = "92192c549b3f53889c23954386743867a73b31b1"
37features = ["markdown", "socks"]
41features = ["markdown", "socks", "qrcode"]
3842
3943[profile.dev.package]
4044sha2 = { opt-level = 2 }
src/bar_items/buffer_name.rs +5
@@ -45,6 +45,11 @@ impl BarItemCallback for BufferName {
4545 format!("{}{}", Weechat::color(color), buffer.short_name())
4646 }
4747
48 BufferOwner::Verification(_, _) => {
49 // TODO special format this
50 format!("{}{}", Weechat::color("status_name"), buffer.name())
51 }
52
4853 BufferOwner::None => {
4954 format!("{}{}", Weechat::color("status_name"), buffer.name())
5055 }
src/bar_items/buffer_plugin.rs +3 −1
@@ -20,7 +20,9 @@ impl BufferPlugin {
2020impl BarItemCallback for BufferPlugin {
2121 fn callback(&mut self, _: &Weechat, buffer: &Buffer) -> String {
2222 match self.servers.buffer_owner(buffer) {
23 BufferOwner::Server(s) | BufferOwner::Room(s, _) => {
23 BufferOwner::Server(s)
24 | BufferOwner::Room(s, _)
25 | BufferOwner::Verification(s, _) => {
2426 format!(
2527 "{plugin_name}{del_color}/{color}{name}",
2628 plugin_name = PLUGIN_NAME,
src/commands/matrix.rs +15 −1
@@ -10,7 +10,7 @@ use weechat::{
1010 Args, Prefix, Weechat,
1111};
1212
13use super::parse_and_run;
13use super::{parse_and_run, verification::VerificationCommand};
1414use crate::{
1515 commands::{DevicesCommand, KeysCommand},
1616 config::ConfigHandle,
@@ -44,14 +44,20 @@ impl MatrixCommand {
4444 reconnect: Reconnect to server(s).
4545 devices: {}
4646 keys: {}
47verification: {}
4748 help: Show detailed command help.\n
4849Use /matrix [command] help to find out more.\n",
4950 DevicesCommand::DESCRIPTION,
5051 KeysCommand::DESCRIPTION,
52 VerificationCommand::DESCRIPTION,
5153 ))
5254 .add_completion("server add|delete|list|listfull")
5355 .add_completion("devices list|delete|set-name %(matrix-users)")
5456 .add_completion(format!("keys {}", KeysCommand::COMPLETION))
57 .add_completion(format!(
58 "verification {}",
59 VerificationCommand::COMPLETION
60 ))
5561 .add_completion("connect %(matrix_servers)")
5662 .add_completion("disconnect %(matrix_servers)")
5763 .add_completion("reconnect %(matrix_servers)")
@@ -224,6 +230,9 @@ Use /matrix [command] help to find out more.\n",
224230 ("keys", Some(subargs)) => {
225231 KeysCommand::run(buffer, &self.servers, subargs)
226232 }
233 ("verification", Some(subargs)) => {
234 VerificationCommand::run(buffer, &self.servers, subargs)
235 }
227236 _ => unreachable!(),
228237 }
229238 }
@@ -291,6 +300,11 @@ impl CommandCallback for MatrixCommand {
291300 .settings(KeysCommand::SETTINGS)
292301 .subcommands(KeysCommand::subcommands()),
293302 )
303 .subcommand(
304 SubCommand::with_name("verification")
305 .about(VerificationCommand::DESCRIPTION)
306 .subcommands(VerificationCommand::subcommands()),
307 )
294308 .subcommand(
295309 SubCommand::with_name("connect")
296310 .about("Connect to Matrix servers.")
src/commands/mod.rs +4
@@ -1,4 +1,5 @@
11use clap::{App, ArgMatches};
2use verification::VerificationCommand;
23use weechat::{
34 hooks::{Command, CommandRun},
45 Args, Weechat,
@@ -12,6 +13,7 @@ mod keys;
1213mod matrix;
1314mod me;
1415mod page_up;
16mod verification;
1517
1618use buffer_clear::BufferClearCommand;
1719use devices::DevicesCommand;
@@ -25,6 +27,7 @@ pub struct Commands {
2527 _keys: Command,
2628 _devices: Command,
2729 _page_up: CommandRun,
30 _verification: Command,
2831 _buffer_clear: CommandRun,
2932 _me: CommandRun,
3033}
@@ -39,6 +42,7 @@ impl Commands {
3942 _devices: DevicesCommand::create(servers)?,
4043 _keys: KeysCommand::create(servers)?,
4144 _page_up: PageUpCommand::create(servers)?,
45 _verification: VerificationCommand::create(servers)?,
4246 _buffer_clear: BufferClearCommand::create(servers)?,
4347 _me: MeCommand::create(servers)?,
4448 })
src/commands/verification.rs added +117
@@ -0,0 +1,117 @@
1use clap::{
2 App as Argparse, AppSettings as ArgParseSettings, ArgMatches, SubCommand,
3};
4
5use weechat::{
6 buffer::Buffer,
7 hooks::{Command, CommandCallback, CommandSettings},
8 Args, Weechat,
9};
10
11use super::parse_and_run;
12use crate::{BufferOwner, Servers};
13
14pub struct VerificationCommand {
15 servers: Servers,
16}
17
18enum CommandType {
19 Accept,
20 Confirm,
21 Cancel,
22}
23
24impl VerificationCommand {
25 pub const DESCRIPTION: &'static str =
26 "Control interactive verification flows";
27
28 pub const COMPLETION: &'static str = "accept|confirm|cancel";
29
30 pub fn create(servers: &Servers) -> Result<Command, ()> {
31 let settings = CommandSettings::new("verification")
32 .description(Self::DESCRIPTION)
33 .add_argument("verification accept|confirm|cancel")
34 .arguments_description(
35 "accept: accept the verification request
36 confirm: confirm that the emojis match on both sides or \
37 confirm that the other side has scanned our QR code
38 cancel: cancel the verification flow or request",
39 )
40 .add_completion(Self::COMPLETION)
41 .add_completion("help accept|confirm|cancel");
42
43 Command::new(
44 settings,
45 VerificationCommand {
46 servers: servers.clone(),
47 },
48 )
49 }
50
51 fn verification(servers: &Servers, buffer: &Buffer, command: CommandType) {
52 let buffer_owner = servers.buffer_owner(buffer);
53
54 match buffer_owner {
55 BufferOwner::Room(_, b) => match command {
56 CommandType::Accept => b.accept_verification(),
57 CommandType::Confirm => b.confirm_verification(),
58 CommandType::Cancel => b.cancel_verification(),
59 },
60 BufferOwner::Verification(_, b) => match command {
61 CommandType::Accept => b.accept(),
62 CommandType::Confirm => b.confirm(),
63 CommandType::Cancel => b.cancel(),
64 },
65 BufferOwner::Server(_) | BufferOwner::None => {
66 Weechat::print(
67 "The verification command needs to be executed in a room or \
68 verification buffer",
69 );
70 }
71 }
72 }
73
74 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
75 match args.subcommand() {
76 ("accept", _) => {
77 Self::verification(servers, buffer, CommandType::Accept)
78 }
79 ("confirm", _) => {
80 Self::verification(servers, buffer, CommandType::Confirm)
81 }
82 ("cancel", _) => {
83 Self::verification(servers, buffer, CommandType::Cancel)
84 }
85 _ => unreachable!(),
86 }
87 }
88
89 pub fn subcommands() -> Vec<Argparse<'static, 'static>> {
90 vec![
91 SubCommand::with_name("accept")
92 .about("Accept a verification request"),
93 SubCommand::with_name("confirm").about(
94 "Confirm that the emoji matches or that the other side has \
95 scanned our QR code",
96 ),
97 SubCommand::with_name("cancel")
98 .about("Cancel the verification flow"),
99 ]
100 }
101}
102
103impl CommandCallback for VerificationCommand {
104 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
105 let argparse = Argparse::new("verification")
106 .about(Self::DESCRIPTION)
107 .global_setting(ArgParseSettings::DisableHelpFlags)
108 .global_setting(ArgParseSettings::DisableVersion)
109 .global_setting(ArgParseSettings::VersionlessSubcommands)
110 .setting(ArgParseSettings::SubcommandRequiredElseHelp)
111 .subcommands(Self::subcommands());
112
113 parse_and_run(argparse, arguments, |matches| {
114 Self::run(buffer, &self.servers, &matches)
115 });
116 }
117}
src/connection.rs +16 −1
@@ -33,7 +33,8 @@ use matrix_sdk::{
3333 },
3434 events::{
3535 room::member::RoomMemberEventContent, AnyMessageLikeEventContent,
36 AnySyncStateEvent, AnySyncTimelineEvent, SyncStateEvent,
36 AnySyncStateEvent, AnySyncTimelineEvent, AnyToDeviceEvent,
37 SyncStateEvent,
3738 },
3839 OwnedDeviceId, OwnedRoomId, OwnedTransactionId,
3940 },
@@ -69,6 +70,7 @@ pub enum ClientMessage {
6970 LoginMessage(LoginResponse),
7071 SyncState(OwnedRoomId, AnySyncStateEvent),
7172 SyncEvent(OwnedRoomId, AnySyncTimelineEvent),
73 ToDeviceEvent(AnyToDeviceEvent),
7274 MemberEvent(
7375 OwnedRoomId,
7476 SyncStateEvent<RoomMemberEventContent>,
@@ -291,6 +293,9 @@ impl Connection {
291293 ClientMessage::RestoredRoom(room) => {
292294 server.restore_room(room).await
293295 }
296 ClientMessage::ToDeviceEvent(e) => {
297 server.receive_to_device_event(e).await
298 }
294299 ClientMessage::MemberEvent(
295300 room_id,
296301 e,
@@ -432,6 +437,16 @@ impl Connection {
432437 loop {
433438 let ret = client
434439 .sync_with_callback(sync_settings.clone(), |response| async move {
440 for event in response.to_device.iter().filter_map(|e| e.to_raw().deserialize().ok()){
441 if sync_channel
442 .send(Ok(ClientMessage::ToDeviceEvent(event)))
443 .await
444 .is_err()
445 {
446 return LoopCtrl::Break;
447 }
448 }
449
435450 for (room_id, room) in response.rooms.joined {
436451 if let State::Before(state) = room.state {
437452 for event in
src/lib.rs +15
@@ -8,6 +8,7 @@ mod render;
88mod room;
99mod server;
1010mod utils;
11mod verification_buffer;
1112
1213use std::{
1314 cell::{Ref, RefCell},
@@ -27,6 +28,7 @@ use weechat::{
2728use crate::{
2829 bar_items::BarItems, commands::Commands, completions::Completions,
2930 config::ConfigHandle, room::RoomHandle, server::MatrixServer,
31 verification_buffer::VerificationBuffer,
3032};
3133
3234const PLUGIN_NAME: &str = "matrix";
@@ -41,6 +43,7 @@ pub struct Servers {
4143pub enum BufferOwner {
4244 Server(MatrixServer),
4345 Room(MatrixServer, RoomHandle),
46 Verification(MatrixServer, VerificationBuffer),
4447 None,
4548}
4649
@@ -49,6 +52,7 @@ impl BufferOwner {
4952 match self {
5053 BufferOwner::Server(s) => Some(s),
5154 BufferOwner::Room(s, _) => Some(s),
55 BufferOwner::Verification(s, _) => Some(s),
5256 BufferOwner::None => None,
5357 }
5458 }
@@ -123,6 +127,17 @@ impl Servers {
123127 }
124128 }
125129 }
130
131 for verification in server.verifications() {
132 if let Ok(b) = verification.buffer().upgrade() {
133 if buffer == &b {
134 return BufferOwner::Verification(
135 server.clone(),
136 verification,
137 );
138 }
139 }
140 }
126141 }
127142
128143 BufferOwner::None
src/render.rs +269 −15
@@ -1,23 +1,45 @@
11use url::Url;
22
3use matrix_sdk::ruma::{
4 events::{
5 room::{
6 encrypted::RoomEncryptedEventContent,
7 member::{MembershipChange, RoomMemberEventContent},
8 message::{
9 AudioMessageEventContent, EmoteMessageEventContent,
10 FileMessageEventContent, ImageMessageEventContent,
11 LocationMessageEventContent, NoticeMessageEventContent,
12 RedactedRoomMessageEventContent,
13 ServerNoticeMessageEventContent, TextMessageEventContent,
14 VideoMessageEventContent,
3use matrix_sdk::{
4 encryption::verification::{
5 SasVerification, Verification, VerificationRequest,
6 },
7 ruma::{
8 events::{
9 key::verification::{
10 key::{
11 KeyVerificationKeyEventContent,
12 ToDeviceKeyVerificationKeyEventContent,
13 },
14 ready::{
15 KeyVerificationReadyEventContent,
16 ToDeviceKeyVerificationReadyEventContent,
17 },
18 request::ToDeviceKeyVerificationRequestEventContent,
19 start::{
20 KeyVerificationStartEventContent,
21 ToDeviceKeyVerificationStartEventContent,
22 },
23 },
24 room::{
25 encrypted::RoomEncryptedEventContent,
26 member::{MembershipChange, RoomMemberEventContent},
27 message::{
28 AudioMessageEventContent, EmoteMessageEventContent,
29 FileMessageEventContent, ImageMessageEventContent,
30 KeyVerificationRequestEventContent,
31 LocationMessageEventContent, NoticeMessageEventContent,
32 RedactedRoomMessageEventContent,
33 ServerNoticeMessageEventContent, TextMessageEventContent,
34 VideoMessageEventContent,
35 },
36 EncryptedFile, MediaSource,
1537 },
16 EncryptedFile, MediaSource,
38 OriginalSyncStateEvent, RedactedSyncMessageLikeEvent,
1739 },
18 OriginalSyncStateEvent, RedactedSyncMessageLikeEvent,
40 uint, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedUserId,
41 TransactionId, UserId,
1942 },
20 uint, EventId, MilliSecondsSinceUnixEpoch, MxcUri, TransactionId, UserId,
2143};
2244
2345use weechat::{Prefix, Weechat};
@@ -473,6 +495,238 @@ impl Render for RedactedSyncMessageLikeEvent<RedactedRoomMessageEventContent> {
473495 }
474496}
475497
498pub enum StartVerificationContext {
499 Room(OwnedUserId, Verification),
500 ToDevice(OwnedUserId, Verification),
501}
502
503impl StartVerificationContext {
504 fn sender(&self) -> &UserId {
505 match self {
506 StartVerificationContext::Room(s, _) => &s,
507 StartVerificationContext::ToDevice(s, _) => &s,
508 }
509 }
510
511 fn verification(&self) -> &Verification {
512 match self {
513 StartVerificationContext::Room(_, v) => &v,
514 StartVerificationContext::ToDevice(_, v) => &v,
515 }
516 }
517
518 fn is_self_verification(&self) -> bool {
519 self.verification().is_self_verification()
520 }
521}
522
523macro_rules! render_start_content {
524 ($type: ident) => {
525 impl Render for $type {
526 const TAGS: &'static [&'static str] = &[];
527
528 type RenderContext = StartVerificationContext;
529
530 fn prefix(&self, _: &WeechatRoomMember) -> String {
531 Weechat::prefix(Prefix::Network)
532 }
533
534 fn render(&self, context: &Self::RenderContext) -> RenderedContent {
535 let message = match context.verification() {
536 Verification::SasV1(sas) => {
537 if context.sender() == sas.own_user_id() {
538 if context.is_self_verification() {
539 if sas.started_from_request() {
540 // We auto accept emoji verifications that start
541 // from a verification request, so don't print
542 // anything.
543 return RenderedContent {
544 lines: vec![],
545 }
546 } else {
547 format!(
548 "You have started an interactive emoji \
549 verification, accept on your other device.",
550 )
551 }
552 } else {
553 format!(
554 "You have started an interactive emoji \
555 verification, waiting for {} to accept",
556 sas.other_device().user_id()
557 )
558 }
559 } else {
560 if sas.started_from_request() {
561 format!(
562 "{} has started an interactive emoji verifiaction \
563 with you, accept with TODO",
564 sas.other_device().user_id()
565 )
566 } else {
567 // We auto accept emoji verifications that start
568 // from a verification request, so don't print
569 // anything.
570 return RenderedContent {
571 lines: vec![],
572 }
573 }
574 }
575 }
576 Verification::QrV1(_) => {
577 // We don't support QR code scanning, so if there's an QR
578 // code verification struct it's because someone else
579 // scanned our QR code.
580 format!(
581 "{} has scanned our QR code, confirm that he \
582 has done so TODO",
583 context.sender(),
584 )
585 }
586 _ => unreachable!(),
587 };
588
589 RenderedContent {
590 lines: vec![RenderedLine {
591 message,
592 tags: self.tags(),
593 }],
594 }
595 }
596 }
597 };
598}
599
600render_start_content!(KeyVerificationStartEventContent);
601render_start_content!(ToDeviceKeyVerificationStartEventContent);
602
603pub enum VerificationContext {
604 Room(WeechatRoomMember, WeechatRoomMember),
605 ToDevice(VerificationRequest),
606}
607
608macro_rules! render_request_content {
609 ($type: ident) => {
610 impl Render for $type {
611 const TAGS: &'static [&'static str] = &[];
612
613 type RenderContext = VerificationContext;
614
615 fn prefix(&self, _: &WeechatRoomMember) -> String {
616 Weechat::prefix(Prefix::Network)
617 }
618
619 fn render(&self, context: &Self::RenderContext) -> RenderedContent {
620 let message = match context {
621 VerificationContext::Room(own_member, sender) => {
622 if own_member == sender {
623 "You sent a verification request".to_string()
624 } else {
625 format!(
626 "{} has sent a verification request",
627 sender.nick_colored()
628 )
629 }
630 }
631 VerificationContext::ToDevice(_) => {
632 format!("You have requested this device to be verified")
633 }
634 };
635
636 RenderedContent {
637 lines: vec![RenderedLine {
638 message,
639 tags: self.tags(),
640 }],
641 }
642 }
643 }
644 };
645}
646
647render_request_content!(KeyVerificationRequestEventContent);
648render_request_content!(ToDeviceKeyVerificationRequestEventContent);
649
650macro_rules! render_ready_content {
651 ($type: ident) => {
652 impl Render for $type {
653 const TAGS: &'static [&'static str] = &[];
654
655 type RenderContext = (WeechatRoomMember, WeechatRoomMember);
656
657 fn prefix(&self, _: &WeechatRoomMember) -> String {
658 Weechat::prefix(Prefix::Network)
659 }
660
661 fn render(&self, context: &Self::RenderContext) -> RenderedContent {
662 let (own_mebmer, sender) = context;
663
664 let message = if own_mebmer == sender {
665 "You answered the verification request".to_string()
666 } else {
667 format!(
668 "{} has answered the verification request",
669 sender.nick_colored()
670 )
671 };
672
673 RenderedContent {
674 lines: vec![RenderedLine {
675 message,
676 tags: self.tags(),
677 }],
678 }
679 }
680 }
681 };
682}
683
684render_ready_content!(KeyVerificationReadyEventContent);
685render_ready_content!(ToDeviceKeyVerificationReadyEventContent);
686
687macro_rules! render_key_content {
688 ($type: ident) => {
689 impl Render for $type {
690 const TAGS: &'static [&'static str] = &[];
691 type RenderContext = SasVerification;
692
693 fn prefix(&self, _: &WeechatRoomMember) -> String {
694 Weechat::prefix(Prefix::Network)
695 }
696
697 fn render(&self, sas: &Self::RenderContext) -> RenderedContent {
698 let (message, short_auth_string) = if sas.supports_emoji() {
699 (
700 "Do the emojis match?".to_string(),
701 format!("{:?}", sas.emoji()),
702 )
703 } else {
704 (
705 "Do the decimals match".to_string(),
706 format!("{:?}", sas.decimals()),
707 )
708 };
709
710 RenderedContent {
711 lines: vec![
712 RenderedLine {
713 message,
714 tags: self.tags(),
715 },
716 RenderedLine {
717 message: short_auth_string,
718 tags: self.tags(),
719 },
720 ],
721 }
722 }
723 }
724 };
725}
726
727render_key_content!(KeyVerificationKeyEventContent);
728render_key_content!(ToDeviceKeyVerificationKeyEventContent);
729
476730/// Trait for message event types that contain an optional formatted body.
477731/// `resolve_body` will return the formatted body if present, else fallback to
478732/// the regular body.
src/room/buffer.rs added +274
@@ -0,0 +1,274 @@
1use std::{borrow::Cow, cell::RefCell, rc::Rc};
2
3use matrix_sdk::{
4 ruma::{EventId, OwnedRoomAliasId, TransactionId, UserId},
5 Room, StoreError,
6};
7use tokio::runtime::Handle;
8use weechat::{
9 buffer::{Buffer, BufferHandle, BufferLine, LineData},
10 Prefix, Weechat,
11};
12
13use crate::{render::RenderedEvent, utils::ToTag};
14
15#[derive(Clone)]
16pub struct RoomBuffer {
17 room: Room,
18 runtime: Handle,
19 pub(super) inner: Rc<RefCell<Option<BufferHandle>>>,
20}
21
22impl RoomBuffer {
23 pub fn new(room: Room, runtime: Handle) -> Self {
24 Self {
25 room,
26 runtime,
27 inner: Rc::new(RefCell::new(None)),
28 }
29 }
30
31 pub fn buffer_handle(&self) -> BufferHandle {
32 self.inner
33 .borrow()
34 .as_ref()
35 .expect("Room struct wasn't initialized properly")
36 .clone()
37 }
38
39 pub fn short_name(&self) -> String {
40 self.inner
41 .borrow()
42 .as_ref()
43 .and_then(|b| b.upgrade().ok().map(|b| b.short_name().to_string()))
44 .unwrap_or_default()
45 }
46
47 /// Replace the local echo of an event with a fully rendered one.
48 pub fn replace_local_echo(
49 &self,
50 transaction_id: &TransactionId,
51 rendered: RenderedEvent,
52 ) {
53 if let Ok(buffer) = self.buffer_handle().upgrade() {
54 let uuid_tag = Cow::from(format!("matrix_echo_{}", transaction_id));
55 let line_contains_uuid =
56 |l: &BufferLine| l.tags().contains(&uuid_tag);
57
58 let mut lines = buffer.lines();
59 let mut current_line = lines.rfind(line_contains_uuid);
60
61 // We go in reverse order here since we also use rfind(). We got from
62 // the bottom of the buffer to the top since we're expecting these
63 // lines to be freshly printed and thus at the bottom.
64 let mut line_num = rendered.content.lines.len();
65
66 while let Some(line) = &current_line {
67 line_num -= 1;
68 let rendered_line = &rendered.content.lines[line_num];
69
70 line.set_message(&rendered_line.message);
71 current_line = lines.next_back().filter(line_contains_uuid);
72 }
73 }
74 }
75
76 pub fn replace_edit(
77 &self,
78 event_id: &EventId,
79 sender: &UserId,
80 event: RenderedEvent,
81 ) {
82 if let Ok(buffer) = self.buffer_handle().upgrade() {
83 let sender_tag = Cow::from(sender.to_tag());
84 let event_id_tag = Cow::from(event_id.to_tag());
85
86 let lines: Vec<BufferLine> = buffer
87 .lines()
88 .filter(|l| l.tags().contains(&event_id_tag))
89 .collect();
90
91 if lines
92 .get(0)
93 .map(|l| l.tags().contains(&sender_tag))
94 .unwrap_or(false)
95 {
96 self.replace_event_helper(&buffer, lines, event);
97 }
98 }
99 }
100
101 fn replace_event_helper(
102 &self,
103 buffer: &Buffer,
104 lines: Vec<BufferLine<'_>>,
105 event: RenderedEvent,
106 ) {
107 use std::cmp::Ordering;
108 let date = lines.get(0).map(|l| l.date()).unwrap_or_default();
109
110 for (line, new) in lines.iter().zip(event.content.lines.iter()) {
111 let data = LineData {
112 // Our prefixes always come with a \t character, but when we
113 // replace stuff we're able to replace the prefix and the
114 // message separately, so trim the whitespace in the prefix.
115 prefix: Some(event.prefix.trim_end()),
116 message: Some(&new.message),
117 ..Default::default()
118 };
119
120 line.update(data);
121 }
122
123 match lines.len().cmp(&event.content.lines.len()) {
124 Ordering::Greater => {
125 for line in &lines[event.content.lines.len()..] {
126 line.set_message("");
127 }
128 }
129 Ordering::Less => {
130 for line in &event.content.lines[lines.len()..] {
131 let message = format!("{}{}", &event.prefix, &line.message);
132 let tags: Vec<&str> =
133 line.tags.iter().map(|t| t.as_str()).collect();
134 buffer.print_date_tags(date, &tags, &message)
135 }
136
137 self.sort_messages()
138 }
139 Ordering::Equal => (),
140 }
141 }
142
143 pub fn sort_messages(&self) {
144 struct LineCopy {
145 date: isize,
146 date_printed: isize,
147 tags: Vec<String>,
148 prefix: String,
149 message: String,
150 }
151
152 impl<'a> From<BufferLine<'a>> for LineCopy {
153 fn from(line: BufferLine) -> Self {
154 Self {
155 date: line.date(),
156 date_printed: line.date_printed(),
157 message: line.message().to_string(),
158 prefix: line.prefix().to_string(),
159 tags: line.tags().iter().map(|t| t.to_string()).collect(),
160 }
161 }
162 }
163
164 // TODO update the highlight once Weechat starts supporting it.
165 if let Ok(buffer) = self.buffer_handle().upgrade() {
166 let mut lines: Vec<LineCopy> =
167 buffer.lines().map(|l| l.into()).collect();
168 lines.sort_by_key(|l| l.date);
169
170 for (line, new) in buffer.lines().zip(lines.drain(..)) {
171 let tags =
172 new.tags.iter().map(|t| t.as_str()).collect::<Vec<&str>>();
173 let data = LineData {
174 prefix: Some(&new.prefix),
175 message: Some(&new.message),
176 date: Some(new.date),
177 date_printed: Some(new.date_printed),
178 tags: Some(&tags),
179 };
180 line.update(data)
181 }
182 }
183 }
184
185 pub fn set_topic(&self) {
186 if let Ok(buffer) = self.buffer_handle().upgrade() {
187 buffer.set_title(&self.room.topic().unwrap_or_default());
188 }
189 }
190
191 pub fn set_alias(&self) {
192 if let Some(alias) = self.alias() {
193 if let Ok(b) = self.buffer_handle().upgrade() {
194 b.set_localvar("alias", alias.as_str());
195 }
196 }
197 }
198
199 fn alias(&self) -> Option<OwnedRoomAliasId> {
200 self.room.canonical_alias()
201 }
202
203 pub fn calculate_buffer_name(&self) -> Result<String, StoreError> {
204 let room = self.room.clone();
205 let room_name = self.runtime.block_on(room.display_name())?.to_string();
206
207 let room_name = if room_name == "#" {
208 "##".to_owned()
209 } else if room_name.starts_with('#')
210 || self.runtime.block_on(room.is_direct()).unwrap_or(false)
211 {
212 room_name
213 } else {
214 format!("#{}", room_name)
215 };
216
217 Ok(room_name.to_string())
218 }
219
220 pub fn update_buffer_name(&self) {
221 let buffer = self.buffer_handle();
222
223 let buffer = if let Ok(b) = buffer.upgrade() {
224 b
225 } else {
226 return;
227 };
228
229 match self.calculate_buffer_name() {
230 Ok(name) => buffer.set_short_name(&name),
231 Err(e) => {
232 Weechat::print(&format!(
233 "{}: Error fetching the room name from the store: {}",
234 Weechat::prefix(Prefix::Error),
235 e.to_string(),
236 ));
237 }
238 }
239 }
240
241 pub fn replace_verification_event(
242 &self,
243 event_id: &EventId,
244 event: RenderedEvent,
245 ) {
246 if let Ok(buffer) = self.buffer_handle().upgrade() {
247 let event_id_tag = Cow::from(event_id.to_tag());
248
249 let lines: Vec<BufferLine> = buffer
250 .lines()
251 .filter(|l| l.tags().contains(&event_id_tag))
252 .collect();
253
254 self.replace_event_helper(&buffer, lines, event);
255 }
256 }
257
258 pub fn print_rendered_event(&self, rendered: RenderedEvent) {
259 let buffer = self.buffer_handle();
260
261 if let Ok(buffer) = buffer.upgrade() {
262 for line in rendered.content.lines {
263 let message = format!("{}{}", &rendered.prefix, &line.message);
264 let tags: Vec<&str> =
265 line.tags.iter().map(|t| t.as_str()).collect();
266 buffer.print_date_tags(
267 rendered.message_timestamp,
268 &tags,
269 &message,
270 )
271 }
272 }
273 }
274}
src/room/members.rs +17 −65
@@ -1,4 +1,4 @@
1use std::{cell::RefCell, rc::Rc};
1use std::rc::Rc;
22
33use dashmap::DashMap;
44use tokio::runtime::Handle;
@@ -17,15 +17,14 @@ use matrix_sdk::{
1717 },
1818 uint, Int, OwnedUserId, UserId,
1919 },
20 StoreError,
2120};
2221
2322use weechat::{
24 buffer::{Buffer, BufferHandle, NickSettings},
23 buffer::{Buffer, NickSettings},
2524 Prefix, Weechat,
2625};
2726
28use crate::render::render_membership;
27use crate::{render::render_membership, room::buffer::RoomBuffer};
2928
3029#[derive(Clone)]
3130pub struct Members {
@@ -33,7 +32,7 @@ pub struct Members {
3332 pub(super) runtime: Handle,
3433 ambiguity_map: Rc<DashMap<OwnedUserId, bool>>,
3534 nicks: Rc<DashMap<OwnedUserId, String>>,
36 pub(super) buffer: Rc<RefCell<Option<BufferHandle>>>,
35 buffer: RoomBuffer,
3736}
3837
3938#[derive(Clone, Debug)]
@@ -43,24 +42,23 @@ pub struct WeechatRoomMember {
4342 ambiguous_nick: Rc<bool>,
4443}
4544
45impl PartialEq for WeechatRoomMember {
46 fn eq(&self, other: &Self) -> bool {
47 self.user_id() == other.user_id()
48 }
49}
50
4651impl Members {
47 pub fn new(room: Room, runtime: Handle) -> Self {
52 pub fn new(room: Room, runtime: Handle, buffer: RoomBuffer) -> Self {
4853 Self {
4954 room,
5055 runtime,
5156 nicks: DashMap::new().into(),
5257 ambiguity_map: DashMap::new().into(),
53 buffer: RefCell::new(None).into(),
58 buffer,
5459 }
5560 }
5661
57 fn buffer(&self) -> BufferHandle {
58 self.buffer
59 .borrow()
60 .clone()
61 .expect("Members struct wasn't initialized properly")
62 }
63
6462 fn add_nick(&self, buffer: &Buffer, member: &WeechatRoomMember) {
6563 let nick = member.nick();
6664
@@ -88,14 +86,6 @@ impl Members {
8886 }
8987
9088 pub async fn restore_member(&self, user_id: OwnedUserId) {
91 let buffer = self.buffer();
92
93 let buffer = if let Ok(b) = buffer.upgrade() {
94 b
95 } else {
96 return;
97 };
98
9989 let room = self.room.clone();
10090 let user = user_id.to_owned();
10191
@@ -114,7 +104,7 @@ impl Members {
114104 panic!(
115105 "Couldn't find member {} in {}",
116106 user_id,
117 buffer.short_name()
107 self.buffer.short_name()
118108 )
119109 }
120110 Err(e) => {
@@ -128,7 +118,7 @@ impl Members {
128118 }
129119
130120 pub async fn update_member(&self, user_id: &UserId) {
131 let buffer = self.buffer();
121 let buffer = self.buffer.buffer_handle();
132122
133123 let buffer = if let Ok(b) = buffer.upgrade() {
134124 b
@@ -198,7 +188,7 @@ impl Members {
198188 }
199189 }
200190
201 let buffer = self.buffer();
191 let buffer = self.buffer.buffer_handle();
202192
203193 let buffer = if let Ok(b) = buffer.upgrade() {
204194 b
@@ -254,51 +244,13 @@ impl Members {
254244 &self.room
255245 }
256246
257 pub fn calculate_buffer_name(&self) -> Result<String, StoreError> {
258 let room = self.room();
259 let room_name = self.runtime.block_on(room.display_name())?.to_string();
260
261 let room_name = if room_name == "#" {
262 "##".to_owned()
263 } else if room_name.starts_with('#')
264 || self.runtime.block_on(room.is_direct()).unwrap_or(false)
265 {
266 room_name
267 } else {
268 format!("#{}", room_name)
269 };
270
271 Ok(room_name.to_string())
272 }
273
274 pub fn update_buffer_name(&self) {
275 let buffer = self.buffer();
276
277 let buffer = if let Ok(b) = buffer.upgrade() {
278 b
279 } else {
280 return;
281 };
282
283 match self.calculate_buffer_name() {
284 Ok(name) => buffer.set_short_name(&name),
285 Err(e) => {
286 Weechat::print(&format!(
287 "{}: Error fetching the room name from the store: {}",
288 Weechat::prefix(Prefix::Error),
289 e,
290 ));
291 }
292 }
293 }
294
295247 pub async fn handle_membership_event(
296248 &self,
297249 event: &SyncStateEvent<RoomMemberEventContent>,
298250 state_event: bool,
299251 ambiguity_change: Option<&AmbiguityChange>,
300252 ) {
301 let buffer = self.buffer();
253 let buffer = self.buffer.buffer_handle();
302254 let buffer = if let Ok(b) = buffer.upgrade() {
303255 b
304256 } else {
@@ -352,7 +304,7 @@ impl Members {
352304
353305 // Names of rooms without display names can get affected by the
354306 // member list so we need to update them.
355 self.update_buffer_name();
307 self.buffer.update_buffer_name();
356308
357309 if !state_event {
358310 let sender = self.get(&sender_id).await;
src/room/mod.rs +53 −201
@@ -22,12 +22,16 @@
2222//! we're sending ourselves before we receive them in a sync response, or if we
2323//! decrypt a previously undecryptable event.
2424
25mod buffer;
2526mod members;
27mod verification;
2628
29use buffer::RoomBuffer;
2730use members::Members;
2831pub use members::WeechatRoomMember;
2932use tokio::runtime::Handle;
3033use tracing::{debug, trace};
34use verification::Verification;
3135
3236use std::{
3337 borrow::Cow,
@@ -71,7 +75,7 @@ use matrix_sdk::{
7175use weechat::{
7276 buffer::{
7377 Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync,
74 BufferLine, LineData,
78 BufferLine,
7579 },
7680 Weechat,
7781};
@@ -80,7 +84,7 @@ use crate::{
8084 config::{Config, RedactionStyle},
8185 connection::Connection,
8286 render::{Render, RenderedEvent},
83 utils::{Edit, ToTag},
87 utils::{Edit, VerificationEvent},
8488 PLUGIN_NAME,
8589};
8690
@@ -149,7 +153,7 @@ pub struct MatrixRoom {
149153 room_id: Rc<RoomId>,
150154 own_user_id: Rc<UserId>,
151155 room: Room,
152 buffer: Rc<RefCell<Option<BufferHandle>>>,
156 buffer: RoomBuffer,
153157
154158 config: Rc<RefCell<Config>>,
155159 connection: Rc<RefCell<Option<Connection>>>,
@@ -160,6 +164,7 @@ pub struct MatrixRoom {
160164 outgoing_messages: MessageQueue,
161165
162166 members: Members,
167 verification: Verification,
163168}
164169
165170#[derive(Debug, Clone, Default)]
@@ -207,7 +212,9 @@ impl RoomHandle {
207212 room_id: &RoomId,
208213 own_user_id: &UserId,
209214 ) -> Self {
210 let members = Members::new(room.clone(), runtime.clone());
215 let buffer = RoomBuffer::new(room.clone(), runtime.clone());
216 let members =
217 Members::new(room.clone(), runtime.clone(), buffer.clone());
211218
212219 let own_nick = runtime
213220 .block_on(room.get_member_no_sync(own_user_id))
@@ -216,6 +223,13 @@ impl RoomHandle {
216223 .map(|m| m.name().to_owned())
217224 .unwrap_or_else(|| own_user_id.localpart().to_owned());
218225
226 let verification = Verification::new(
227 own_user_id.into(),
228 connection.clone(),
229 members.clone(),
230 buffer.clone(),
231 );
232
219233 let room = MatrixRoom {
220234 homeserver: Rc::new(homeserver),
221235 room_id: room_id.into(),
@@ -225,8 +239,9 @@ impl RoomHandle {
225239 room.last_prev_batch().map(PrevBatch::Backwards),
226240 )),
227241 own_user_id: own_user_id.into(),
228 members: members.clone(),
229 buffer: members.buffer,
242 members,
243 buffer,
244 verification,
230245 outgoing_messages: MessageQueue::new(),
231246 messages_in_flight: IntMutex::new(),
232247 room,
@@ -305,7 +320,7 @@ impl RoomHandle {
305320 buffer.set_localvar("alias", alias.as_str());
306321 }
307322
308 *room.members.buffer.borrow_mut() = Some(buffer_handle.clone());
323 *room.buffer.inner.borrow_mut() = Some(buffer_handle.clone());
309324
310325 Self { inner: room }
311326 }
@@ -349,8 +364,8 @@ impl RoomHandle {
349364 *room_buffer.prev_batch.borrow_mut() =
350365 prev_batch.map(PrevBatch::Forward);
351366
352 room_buffer.update_buffer_name();
353 room_buffer.set_topic();
367 room_buffer.buffer.update_buffer_name();
368 room_buffer.buffer.set_topic();
354369
355370 Ok(room_buffer)
356371 }
@@ -409,28 +424,21 @@ impl MatrixRoom {
409424 }
410425
411426 pub fn buffer_handle(&self) -> BufferHandle {
412 self.buffer
413 .borrow()
414 .as_ref()
415 .expect("Room struct wasn't initialized properly")
416 .clone()
427 self.buffer.buffer_handle()
417428 }
418429
419 fn print_rendered_event(&self, rendered: RenderedEvent) {
420 let buffer = self.buffer_handle();
421
422 if let Ok(buffer) = buffer.upgrade() {
423 for line in rendered.content.lines {
424 let message = format!("{}{}", &rendered.prefix, &line.message);
425 let tags: Vec<&str> =
426 line.tags.iter().map(|t| t.as_str()).collect();
427 buffer.print_date_tags(
428 rendered.message_timestamp,
429 &tags,
430 &message,
431 )
432 }
433 }
430 pub fn accept_verification(&self) {
431 let verification = self.verification.clone();
432 Weechat::spawn(async move { verification.accept().await }).detach();
433 }
434
435 pub fn confirm_verification(&self) {
436 let verification = self.verification.clone();
437 Weechat::spawn(async move { verification.confirm().await }).detach();
438 }
439
440 pub fn cancel_verification(&self) {
441 todo!()
434442 }
435443
436444 async fn redact_event(&self, event: &SyncRoomRedactionEvent) {
@@ -650,7 +658,7 @@ impl MatrixRoom {
650658 let local_echo = c
651659 .render_with_prefix_for_echo(&sender, transaction_id, &())
652660 .add_self_tags();
653 self.print_rendered_event(local_echo);
661 self.buffer.print_rendered_event(local_echo);
654662
655663 self.outgoing_messages
656664 .add_with_echo(transaction_id.to_owned(), content.clone());
@@ -693,7 +701,7 @@ impl MatrixRoom {
693701 .send_message(
694702 self.room().clone(),
695703 AnyMessageLikeEventContent::RoomMessage(content),
696 Some(transaction_id.to_owned()),
704 Some(transaction_id.clone()),
697705 )
698706 .await
699707 {
@@ -809,12 +817,12 @@ impl MatrixRoom {
809817
810818 if let Some(PrevBatch::Forward(t)) = prev_batch.as_ref() {
811819 *prev_batch = Some(PrevBatch::Backwards(t.to_owned()));
812 self.sort_messages();
820 self.buffer.sort_messages();
813821 } else if r.chunk.is_empty() {
814822 *prev_batch = None;
815823 } else {
816824 *prev_batch = r.end.map(PrevBatch::Backwards);
817 self.sort_messages();
825 self.buffer.sort_messages();
818826 }
819827 }
820828 }
@@ -825,75 +833,6 @@ impl MatrixRoom {
825833 Weechat::bar_item_update("matrix_modes");
826834 }
827835
828 fn sort_messages(&self) {
829 struct LineCopy {
830 date: isize,
831 date_printed: isize,
832 tags: Vec<String>,
833 prefix: String,
834 message: String,
835 }
836
837 impl From<BufferLine<'_>> for LineCopy {
838 fn from(line: BufferLine) -> Self {
839 Self {
840 date: line.date(),
841 date_printed: line.date_printed(),
842 message: line.message().to_string(),
843 prefix: line.prefix().to_string(),
844 tags: line.tags().iter().map(|t| t.to_string()).collect(),
845 }
846 }
847 }
848
849 // TODO: update the highlight once Weechat starts supporting it.
850 if let Ok(buffer) = self.buffer_handle().upgrade() {
851 let mut lines: Vec<LineCopy> =
852 buffer.lines().map(|l| l.into()).collect();
853 lines.sort_by_key(|l| l.date);
854
855 for (line, new) in buffer.lines().zip(lines.drain(..)) {
856 let tags =
857 new.tags.iter().map(|t| t.as_str()).collect::<Vec<&str>>();
858 let data = LineData {
859 prefix: Some(&new.prefix),
860 message: Some(&new.message),
861 date: Some(new.date),
862 date_printed: Some(new.date_printed),
863 tags: Some(&tags),
864 };
865 line.update(data)
866 }
867 }
868 }
869
870 /// Replace the local echo of an event with a fully rendered one.
871 fn replace_local_echo(
872 &self,
873 transaction_id: &TransactionId,
874 buffer: &Buffer,
875 rendered: RenderedEvent,
876 ) {
877 let uuid_tag = Cow::from(format!("matrix_echo_{}", transaction_id));
878 let line_contains_uuid = |l: &BufferLine| l.tags().contains(&uuid_tag);
879
880 let mut lines = buffer.lines();
881 let mut current_line = lines.rfind(line_contains_uuid);
882
883 // We go in reverse order here since we also use rfind(). We got from
884 // the bottom of the buffer to the top since we're expecting these
885 // lines to be freshly printed and thus at the bottom.
886 let mut line_num = rendered.content.lines.len();
887
888 while let Some(line) = &current_line {
889 line_num -= 1;
890 let rendered_line = &rendered.content.lines[line_num];
891
892 line.set_message(&rendered_line.message);
893 current_line = lines.next_back().filter(line_contains_uuid);
894 }
895 }
896
897836 async fn handle_outgoing_message(
898837 &self,
899838 transaction_id: &TransactionId,
@@ -919,100 +858,11 @@ impl MatrixRoom {
919858 .await
920859 .expect("Sent out an event that we don't know how to render");
921860
922 if let Ok(buffer) = self.buffer_handle().upgrade() {
923 if echo {
924 self.replace_local_echo(transaction_id, &buffer, rendered);
925 } else {
926 self.print_rendered_event(rendered);
927 }
928 }
929 }
930 }
931
932 fn set_topic(&self) {
933 if let Ok(buffer) = self.buffer_handle().upgrade() {
934 buffer.set_title(&self.room().topic().unwrap_or_default());
935 }
936 }
937
938 fn set_alias(&self) {
939 if let Some(alias) = self.alias() {
940 if let Ok(b) = self.buffer_handle().upgrade() {
941 b.set_localvar("alias", alias.as_str());
942 }
943 }
944 }
945
946 fn update_buffer_name(&self) {
947 self.members.update_buffer_name();
948 }
949
950 fn replace_edit(
951 &self,
952 event_id: &EventId,
953 sender: &UserId,
954 event: RenderedEvent,
955 ) {
956 if let Ok(buffer) = self.buffer_handle().upgrade() {
957 let sender_tag = Cow::from(sender.to_tag());
958 let event_id_tag = Cow::from(event_id.to_tag());
959
960 let lines: Vec<BufferLine> = buffer
961 .lines()
962 .filter(|l| l.tags().contains(&event_id_tag))
963 .collect();
964
965 if lines
966 .first()
967 .map(|l| l.tags().contains(&sender_tag))
968 .unwrap_or(false)
969 {
970 self.replace_event_helper(&buffer, lines, event);
971 }
972 }
973 }
974
975 fn replace_event_helper(
976 &self,
977 buffer: &Buffer,
978 lines: Vec<BufferLine<'_>>,
979 event: RenderedEvent,
980 ) {
981 use std::cmp::Ordering;
982 let date = lines.first().map(|l| l.date()).unwrap_or_default();
983
984 for (line, new) in lines.iter().zip(event.content.lines.iter()) {
985 let tags: Vec<&str> = new.tags.iter().map(|t| t.as_str()).collect();
986 let data = LineData {
987 // Our prefixes always come with a \t character, but when we
988 // replace stuff we're able to replace the prefix and the
989 // message separately, so trim the whitespace in the prefix.
990 prefix: Some(event.prefix.trim_end()),
991 message: Some(&new.message),
992 tags: Some(&tags),
993 ..Default::default()
994 };
995
996 line.update(data);
997 }
998
999 match lines.len().cmp(&event.content.lines.len()) {
1000 Ordering::Greater => {
1001 for line in &lines[event.content.lines.len()..] {
1002 line.set_message("");
1003 }
1004 }
1005 Ordering::Less => {
1006 for line in &event.content.lines[lines.len()..] {
1007 let message = format!("{}{}", &event.prefix, &line.message);
1008 let tags: Vec<&str> =
1009 line.tags.iter().map(|t| t.as_str()).collect();
1010 buffer.print_date_tags(date, &tags, &message)
1011 }
1012
1013 self.sort_messages()
861 if echo {
862 self.buffer.replace_local_echo(transaction_id, rendered);
863 } else {
864 self.buffer.print_rendered_event(rendered);
1014865 }
1015 Ordering::Equal => (),
1016866 }
1017867 }
1018868
@@ -1045,7 +895,7 @@ impl MatrixRoom {
1045895 }
1046896 })
1047897 {
1048 self.replace_edit(event_id, event.sender(), rendered);
898 self.buffer.replace_edit(event_id, event.sender(), rendered);
1049899 }
1050900 }
1051901 }
@@ -1061,10 +911,12 @@ impl MatrixRoom {
1061911
1062912 if let AnySyncMessageLikeEvent::RoomRedaction(r) = event {
1063913 self.redact_event(r).await;
914 } else if event.is_verification() {
915 self.verification.handle_room_verification(event).await;
1064916 } else if event.is_edit() {
1065917 self.handle_edits(event).await;
1066918 } else if let Some(rendered) = self.render_sync_message(event).await {
1067 self.print_rendered_event(rendered);
919 self.buffer.print_rendered_event(rendered);
1068920 }
1069921 }
1070922
@@ -1159,7 +1011,7 @@ impl MatrixRoom {
11591011 )
11601012 .await
11611013 {
1162 self.print_rendered_event(rendered);
1014 self.buffer.print_rendered_event(rendered);
11631015 }
11641016 }
11651017 }
@@ -1178,9 +1030,9 @@ impl MatrixRoom {
11781030 _state_event: bool,
11791031 ) {
11801032 match event {
1181 AnySyncStateEvent::RoomName(_) => self.update_buffer_name(),
1182 AnySyncStateEvent::RoomTopic(_) => self.set_topic(),
1183 AnySyncStateEvent::RoomCanonicalAlias(_) => self.set_alias(),
1033 AnySyncStateEvent::RoomName(_) => self.buffer.update_buffer_name(),
1034 AnySyncStateEvent::RoomTopic(_) => self.buffer.set_topic(),
1035 AnySyncStateEvent::RoomCanonicalAlias(_) => self.buffer.set_alias(),
11841036 _ => (),
11851037 }
11861038 }
src/room/verification.rs added +226
@@ -0,0 +1,226 @@
1use std::{cell::RefCell, rc::Rc};
2
3use matrix_sdk::{
4 encryption::verification::{SasVerification, VerificationRequest},
5 ruma::{
6 events::{
7 key::verification::VerificationMethod, room::message::MessageType,
8 AnySyncMessageLikeEvent,
9 },
10 UserId,
11 },
12};
13
14use crate::{
15 connection::Connection,
16 render::{Render, StartVerificationContext, VerificationContext},
17};
18
19use super::{buffer::RoomBuffer, members::Members};
20
21#[derive(Clone)]
22pub struct Verification {
23 own_user_id: Rc<UserId>,
24 connection: Rc<RefCell<Option<Connection>>>,
25 members: Members,
26 buffer: RoomBuffer,
27 inner: Rc<RefCell<Option<ActiveVerification>>>,
28}
29
30#[derive(Clone, Debug)]
31enum ActiveVerification {
32 Request(VerificationRequest),
33 Sas(SasVerification),
34}
35
36impl From<VerificationRequest> for ActiveVerification {
37 fn from(v: VerificationRequest) -> Self {
38 Self::Request(v)
39 }
40}
41
42impl From<SasVerification> for ActiveVerification {
43 fn from(v: SasVerification) -> Self {
44 Self::Sas(v)
45 }
46}
47
48impl Verification {
49 pub fn new(
50 own_user_id: Rc<UserId>,
51 connection: Rc<RefCell<Option<Connection>>>,
52 members: Members,
53 buffer: RoomBuffer,
54 ) -> Self {
55 Self {
56 own_user_id,
57 connection,
58 members,
59 buffer,
60 inner: Rc::new(RefCell::new(None)),
61 }
62 }
63
64 pub async fn confirm(&self) {
65 let connection = self.connection.borrow().clone();
66
67 if let Some(c) = connection {
68 if let Some(ActiveVerification::Sas(verification)) =
69 self.inner.borrow().clone()
70 {
71 let ret =
72 c.spawn(async move { verification.confirm().await }).await;
73 }
74 }
75 }
76
77 pub async fn accept(&self) {
78 let connection = self.connection.borrow().clone();
79 let verification = self.inner.borrow().clone();
80
81 if let Some(c) = connection {
82 if let Some(ActiveVerification::Request(verification)) =
83 verification
84 {
85 let verification_clone = verification.clone();
86
87 let ret = c
88 .spawn(async move {
89 verification
90 .accept_with_methods(vec![
91 VerificationMethod::SasV1,
92 ])
93 .await
94 })
95 .await;
96
97 // We automatically start SAS verification here since it's the
98 // only method we support.
99 if let Some(sas) = c
100 .spawn(async move { verification_clone.start_sas().await })
101 .await
102 .unwrap()
103 {
104 *self.inner.borrow_mut() = Some(sas.into());
105 }
106 }
107 }
108 }
109
110 pub async fn handle_room_verification(
111 &self,
112 event: &AnySyncMessageLikeEvent,
113 ) {
114 // TODO remove this expect.
115 let sender =
116 self.members.get(event.sender()).await.expect(
117 "Rendering a message but the sender isn't in the nicklist",
118 );
119 let own_member = self
120 .members
121 .get(&self.own_user_id)
122 .await
123 .expect("Own member missing from the store");
124 let send_time = event.origin_server_ts();
125 let connection = self.connection.borrow().clone();
126
127 match event {
128 AnySyncMessageLikeEvent::KeyVerificationReady(_) => {}
129 AnySyncMessageLikeEvent::KeyVerificationStart(e) => {
130 if let Some(connection) = connection {
131 let Some(e) = e.as_original() else {
132 // Unhandled redacted event
133 return;
134 };
135 let flow_id = &e.content.relates_to.event_id;
136
137 if let Some(sas) = connection
138 .client()
139 .encryption()
140 .get_verification(&e.sender, flow_id.as_str())
141 .await
142 .map(|s| s.sas())
143 .flatten()
144 {
145 let context = StartVerificationContext::Room(
146 e.sender.to_owned(),
147 sas.clone().into(),
148 );
149 let rendered = e.content.render_with_prefix(
150 send_time,
151 event.event_id(),
152 &sender,
153 &context,
154 );
155 self.buffer
156 .replace_verification_event(flow_id, rendered);
157 *self.inner.borrow_mut() = Some(sas.clone().into());
158
159 // We accept here automatically since the only method
160 // we're supporting is SAS verification
161 let ret = connection
162 .spawn(async move { sas.accept().await })
163 .await;
164 }
165 }
166 }
167 AnySyncMessageLikeEvent::KeyVerificationCancel(_) => {
168 self.inner.borrow_mut().take();
169 }
170 AnySyncMessageLikeEvent::KeyVerificationAccept(_) => {}
171 AnySyncMessageLikeEvent::KeyVerificationKey(e) => {
172 let Some(e) = e.as_original() else {
173 // Unhandled redacted event
174 return;
175 };
176 let flow_id = &e.content.relates_to.event_id;
177 if let Some(ActiveVerification::Sas(sas)) =
178 self.inner.borrow().clone()
179 {
180 if sas.can_be_presented() {
181 let rendered = e.content.render_with_prefix(
182 send_time,
183 event.event_id(),
184 &sender,
185 &sas,
186 );
187 self.buffer
188 .replace_verification_event(flow_id, rendered);
189 }
190 }
191 }
192 AnySyncMessageLikeEvent::KeyVerificationMac(_) => {}
193 AnySyncMessageLikeEvent::KeyVerificationDone(_) => {}
194 AnySyncMessageLikeEvent::RoomMessage(e) => {
195 let Some(e) = e.as_original() else {
196 // Unhandled redacted event
197 return;
198 };
199 if let MessageType::VerificationRequest(content) =
200 &e.content.msgtype
201 {
202 let rendered = content.render_with_prefix(
203 send_time,
204 &e.event_id,
205 &sender.clone(),
206 &VerificationContext::Room(sender, own_member),
207 );
208 self.buffer.print_rendered_event(rendered);
209
210 if let Some(connection) = connection {
211 if let Some(verification) = connection
212 .client()
213 .encryption()
214 .get_verification_request(&e.sender, &e.event_id)
215 .await
216 {
217 *self.inner.borrow_mut() =
218 Some(verification.into());
219 }
220 }
221 }
222 }
223 _ => {}
224 }
225 }
226}
src/server.rs +121 −1
@@ -74,7 +74,7 @@ use matrix_sdk::{
7474 api::client::session::login::v3::Response as LoginResponse,
7575 events::{
7676 room::member::RoomMemberEventContent, AnySyncStateEvent,
77 AnySyncTimelineEvent, SyncStateEvent,
77 AnySyncTimelineEvent, AnyToDeviceEvent, SyncStateEvent,
7878 },
7979 DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch,
8080 OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId,
@@ -92,6 +92,7 @@ use crate::{
9292 config::ServerBuffer,
9393 connection::{Connection, InteractiveAuthInfo},
9494 room::RoomHandle,
95 verification_buffer::VerificationBuffer,
9596 ConfigHandle, Servers, PLUGIN_NAME,
9697};
9798
@@ -173,6 +174,7 @@ pub struct InnerServer {
173174 login_state: Rc<RefCell<Option<LoginInfo>>>,
174175 connection: Rc<RefCell<Option<Connection>>>,
175176 server_buffer: Rc<RefCell<Option<BufferHandle>>>,
177 verification_buffers: Rc<RefCell<HashMap<String, VerificationBuffer>>>,
176178}
177179
178180impl MatrixServer {
@@ -195,6 +197,7 @@ impl MatrixServer {
195197 login_state: Rc::new(RefCell::new(None)),
196198 connection: Rc::new(RefCell::new(None)),
197199 server_buffer: Rc::new(RefCell::new(None)),
200 verification_buffers: Rc::new(RefCell::new(HashMap::new())),
198201 };
199202
200203 let server = server.into();
@@ -451,6 +454,14 @@ impl InnerServer {
451454 self.rooms.borrow().values().cloned().collect()
452455 }
453456
457 pub fn verifications(&self) -> Vec<VerificationBuffer> {
458 self.verification_buffers
459 .borrow()
460 .values()
461 .cloned()
462 .collect()
463 }
464
454465 pub(crate) fn get_or_create_room(&self, room_id: &RoomId) -> RoomHandle {
455466 if !self.rooms.borrow().contains_key(room_id) {
456467 let homeserver = self
@@ -670,6 +681,115 @@ impl InnerServer {
670681 self.connection.borrow().is_some()
671682 }
672683
684 pub async fn receive_to_device_event(&self, event: AnyToDeviceEvent) {
685 let handle_event = |event, transaction_id: String| async move {
686 if let Some(b) =
687 self.verification_buffers.borrow().get(&transaction_id)
688 {
689 b.handle_event(event).await;
690 }
691 };
692
693 match &event {
694 AnyToDeviceEvent::RoomKey(_) => {}
695 AnyToDeviceEvent::RoomKeyRequest(_) => {}
696 AnyToDeviceEvent::KeyVerificationRequest(e) => {
697 if let Some(client) = self.get_client() {
698 if let Some(request) = client
699 .encryption()
700 .get_verification_request(
701 &e.sender,
702 &e.content.transaction_id,
703 )
704 .await
705 {
706 let buffer = VerificationBuffer::new(
707 &self.server_name,
708 &e.sender,
709 request,
710 self.connection.clone(),
711 );
712 buffer.handle_event(&event).await;
713 self.verification_buffers.borrow_mut().insert(
714 e.content.transaction_id.to_string(),
715 buffer,
716 );
717 }
718 }
719 }
720 AnyToDeviceEvent::KeyVerificationStart(e) => {
721 if let Some(client) = self.get_client() {
722 use matrix_sdk::encryption::verification::Verification;
723 match client
724 .encryption()
725 .get_verification(
726 &e.sender,
727 e.content.transaction_id.as_str(),
728 )
729 .await
730 {
731 Some(Verification::SasV1(sas)) => {
732 if !sas.is_cancelled() {
733 let buffer = self
734 .verification_buffers
735 .borrow()
736 .get(e.content.transaction_id.as_str())
737 .cloned();
738
739 if let Some(mut buffer) = buffer {
740 buffer.update(sas).await;
741 buffer.handle_event(&event).await;
742 } else {
743 let buffer = VerificationBuffer::new(
744 &self.server_name,
745 &e.sender,
746 sas,
747 self.connection.clone(),
748 );
749 buffer.handle_event(&event).await;
750 self.verification_buffers
751 .borrow_mut()
752 .insert(
753 e.content
754 .transaction_id
755 .to_string(),
756 buffer,
757 );
758 }
759 }
760 }
761 Some(Verification::QrV1(qr)) => {
762 if let Some(buffer) = self
763 .verification_buffers
764 .borrow_mut()
765 .get_mut(e.content.transaction_id.as_str())
766 {
767 buffer.update_qr(qr).await;
768 buffer.handle_event(&event).await;
769 }
770 }
771 Some(_) => unreachable!(),
772 None => todo!(),
773 }
774 }
775 }
776 AnyToDeviceEvent::KeyVerificationCancel(e) => {
777 handle_event(&event, e.content.transaction_id.to_string())
778 .await;
779 }
780 AnyToDeviceEvent::KeyVerificationAccept(e) => {
781 handle_event(&event, e.content.transaction_id.to_string()).await
782 }
783 AnyToDeviceEvent::KeyVerificationKey(e) => {
784 handle_event(&event, e.content.transaction_id.to_string()).await
785 }
786 AnyToDeviceEvent::KeyVerificationMac(e) => {
787 handle_event(&event, e.content.transaction_id.to_string()).await
788 }
789 _ => {}
790 }
791 }
792
673793 pub async fn receive_member(
674794 &self,
675795 room_id: OwnedRoomId,
src/utils.rs +31 −2
@@ -1,10 +1,10 @@
11use matrix_sdk::ruma::{
22 events::{
33 room::message::{
4 Relation, RoomMessageEventContent,
4 MessageType, Relation, RoomMessageEventContent,
55 RoomMessageEventContentWithoutRelation,
66 },
7 AnyMessageLikeEvent, AnySyncMessageLikeEvent,
7 AnyMessageLikeEvent, AnySyncMessageLikeEvent, SyncMessageLikeEvent,
88 },
99 EventId, UserId,
1010};
@@ -32,6 +32,35 @@ pub trait Edit {
3232 ) -> Option<(&EventId, &RoomMessageEventContentWithoutRelation)>;
3333}
3434
35pub trait VerificationEvent {
36 fn is_verification(&self) -> bool;
37}
38
39impl VerificationEvent for AnySyncMessageLikeEvent {
40 fn is_verification(&self) -> bool {
41 match self {
42 AnySyncMessageLikeEvent::KeyVerificationReady(_)
43 | AnySyncMessageLikeEvent::KeyVerificationStart(_)
44 | AnySyncMessageLikeEvent::KeyVerificationCancel(_)
45 | AnySyncMessageLikeEvent::KeyVerificationAccept(_)
46 | AnySyncMessageLikeEvent::KeyVerificationKey(_)
47 | AnySyncMessageLikeEvent::KeyVerificationMac(_)
48 | AnySyncMessageLikeEvent::KeyVerificationDone(_) => true,
49 AnySyncMessageLikeEvent::RoomMessage(m) => {
50 if let SyncMessageLikeEvent::Original(m) = m {
51 if let MessageType::VerificationRequest(_) =
52 m.content.msgtype
53 {
54 return true;
55 }
56 }
57 false
58 }
59 _ => false,
60 }
61 }
62}
63
3564impl Edit for RoomMessageEventContent {
3665 fn is_edit(&self) -> bool {
3766 matches!(self.relates_to.as_ref(), Some(Relation::Replacement(_)))
src/verification_buffer.rs added +370
@@ -0,0 +1,370 @@
1use std::{cell::RefCell, convert::TryInto, rc::Rc};
2
3use weechat::{
4 buffer::{
5 Buffer, BufferBuilderAsync, BufferCloseCallback, BufferHandle,
6 BufferInputCallbackAsync,
7 },
8 Weechat,
9};
10
11use qrcode::render::unicode::Dense1x2;
12
13use matrix_sdk::{
14 async_trait,
15 encryption::verification::{
16 QrVerification, SasVerification, Verification as SdkVerification,
17 VerificationRequest,
18 },
19 ruma::{
20 events::{
21 key::verification::{
22 key::ToDeviceKeyVerificationKeyEventContent, VerificationMethod,
23 },
24 AnyToDeviceEvent,
25 },
26 UserId,
27 },
28 Error,
29};
30
31use crate::{
32 connection::Connection,
33 render::{
34 Render, RenderedContent, StartVerificationContext, VerificationContext,
35 },
36};
37
38#[derive(Clone)]
39pub struct VerificationBuffer {
40 inner: InnerVerificationBuffer,
41 buffer: BufferHandle,
42}
43
44#[derive(Clone, Debug)]
45pub enum Verification {
46 Request(VerificationRequest),
47 Sas(SasVerification),
48 Qr(QrVerification),
49}
50
51impl TryInto<SdkVerification> for Verification {
52 type Error = ();
53
54 fn try_into(self) -> Result<SdkVerification, Self::Error> {
55 match self {
56 Verification::Request(_) => Err(()),
57 Verification::Sas(s) => Ok(s.into()),
58 Verification::Qr(qr) => Ok(qr.into()),
59 }
60 }
61}
62
63impl From<SasVerification> for Verification {
64 fn from(s: SasVerification) -> Self {
65 Self::Sas(s)
66 }
67}
68
69impl From<VerificationRequest> for Verification {
70 fn from(v: VerificationRequest) -> Self {
71 Self::Request(v)
72 }
73}
74
75impl From<QrVerification> for Verification {
76 fn from(v: QrVerification) -> Self {
77 Self::Qr(v)
78 }
79}
80
81impl Verification {
82 async fn accept(&self) -> Result<(), Error> {
83 match self {
84 Verification::Request(r) => r.accept().await,
85 Verification::Sas(s) => s.accept().await,
86 Verification::Qr(qr) => qr.confirm().await,
87 }
88 }
89
90 async fn generate_qr_code(&self) -> Option<QrVerification> {
91 match self {
92 Verification::Request(r) => r.generate_qr_code().await.unwrap(),
93 Verification::Sas(_) => None,
94 Verification::Qr(_) => None,
95 }
96 }
97
98 async fn cancel(&self) -> Result<(), Error> {
99 match self {
100 Verification::Request(r) => r.cancel().await,
101 Verification::Sas(s) => s.cancel().await,
102 Verification::Qr(qr) => qr.cancel().await,
103 }
104 }
105}
106
107#[derive(Clone)]
108struct InnerVerificationBuffer {
109 verification: Rc<RefCell<Verification>>,
110 connection: Rc<RefCell<Option<Connection>>>,
111}
112
113impl InnerVerificationBuffer {
114 fn print_done(&self, buffer: BufferHandle) {}
115
116 pub async fn accept(&self, buffer: BufferHandle) -> Result<(), Error> {
117 if let Some(c) = self.connection.borrow().clone() {
118 let verification = self.verification.borrow().clone();
119 let verification_clone = verification.clone();
120
121 c.spawn(async move { verification_clone.accept().await })
122 .await?;
123
124 if let Verification::Request(request) = verification {
125 if request
126 .their_supported_methods()
127 .unwrap_or_default()
128 .contains(&VerificationMethod::QrCodeShowV1)
129 {
130 if let Some(qr_code) = request.generate_qr_code().await? {
131 if let Ok(code) = qr_code.to_qr_code() {
132 if let Ok(b) = buffer.upgrade() {
133 let string = code
134 .render::<Dense1x2>()
135 .light_color(Dense1x2::Dark)
136 .dark_color(Dense1x2::Light)
137 .build();
138 b.print(&string);
139 }
140 }
141 }
142 } else if let Some(sas) =
143 c.spawn(async move { request.start_sas().await }).await?
144 {
145 *self.verification.borrow_mut() = sas.into();
146 }
147 }
148 }
149
150 Ok(())
151 }
152
153 pub async fn confirm(&self, buffer: BufferHandle) -> Result<(), Error> {
154 if let Some(c) = self.connection.borrow().clone() {
155 if let Verification::Sas(s) = self.verification.borrow().clone() {
156 let sas = s.clone();
157 c.spawn(async move { s.confirm().await }).await?;
158
159 if sas.is_done() {
160 self.print_done(buffer);
161 }
162 } else if let Verification::Qr(qr) =
163 self.verification.borrow().clone()
164 {
165 c.spawn(async move { qr.confirm().await }).await?;
166
167 // if qr.is_done() {
168 // self.print_done(buffer);
169 // }
170 } else if let Ok(b) = buffer.upgrade() {
171 b.print("Error, can't confirm the verification yet");
172 }
173 }
174
175 Ok(())
176 }
177
178 pub async fn cancel(&self) -> Result<(), Error> {
179 if let Some(c) = self.connection.borrow().clone() {
180 let verification = self.verification.borrow().clone();
181 c.spawn(async move { verification.cancel().await }).await?;
182 }
183
184 Ok(())
185 }
186
187 async fn handle_input(
188 &mut self,
189 buffer: BufferHandle,
190 input: &str,
191 ) -> Result<(), Error> {
192 if input == "accept" {
193 self.accept(buffer).await?;
194 } else if input == "confirm" {
195 self.confirm(buffer).await?;
196 } else if input == "cancel" {
197 self.cancel().await?;
198 }
199
200 Ok(())
201 }
202}
203
204#[async_trait(?Send)]
205impl BufferInputCallbackAsync for InnerVerificationBuffer {
206 async fn callback(&mut self, buffer: BufferHandle, input: String) {
207 if let Err(e) = self.handle_input(buffer.clone(), &input).await {
208 if let Ok(buffer) = buffer.upgrade() {
209 buffer.print(&format!(
210 "Error with the verification flow {:?}",
211 e
212 ));
213 }
214 }
215 }
216}
217
218impl BufferCloseCallback for InnerVerificationBuffer {
219 fn callback(&mut self, _: &Weechat, _: &Buffer) -> Result<(), ()> {
220 let inner = self.clone();
221 Weechat::spawn(async move { inner.cancel().await }).detach();
222
223 Ok(())
224 }
225}
226
227impl VerificationBuffer {
228 pub fn new(
229 server_name: &str,
230 sender: &UserId,
231 verification: impl Into<Verification>,
232 connection: Rc<RefCell<Option<Connection>>>,
233 ) -> Self {
234 let inner = InnerVerificationBuffer {
235 verification: Rc::new(RefCell::new(verification.into())),
236 connection,
237 };
238
239 let buffer_name = format!("{}.verification", server_name);
240
241 let buffer_handle = BufferBuilderAsync::new(&buffer_name)
242 .input_callback(inner.clone())
243 .close_callback(|_weechat: &Weechat, _buffer: &Buffer| {
244 // TODO remove the roombuffer from the server here.
245 // TODO leave the room if the plugin isn't unloading.
246 Ok(())
247 })
248 .build()
249 .expect("Can't create new room buffer");
250
251 let buffer = buffer_handle
252 .upgrade()
253 .expect("Can't upgrade newly created buffer");
254
255 buffer.disable_nicklist();
256 buffer.disable_nicklist_groups();
257 buffer.enable_multiline();
258
259 buffer.set_localvar("server", server_name);
260
261 Self {
262 inner,
263 buffer: buffer_handle,
264 }
265 }
266
267 pub fn buffer(&self) -> BufferHandle {
268 self.buffer.clone()
269 }
270
271 pub fn accept(&self) {
272 let buffer = self.buffer();
273 let inner = self.inner.clone();
274 Weechat::spawn(async move { inner.accept(buffer).await }).detach();
275 }
276
277 pub fn cancel(&self) {
278 let inner = self.inner.clone();
279 Weechat::spawn(async move { inner.cancel().await }).detach();
280 }
281
282 pub fn confirm(&self) {
283 let buffer = self.buffer();
284 let inner = self.inner.clone();
285 Weechat::spawn(async move { inner.confirm(buffer).await }).detach();
286 }
287
288 pub async fn update_qr(&mut self, qr: QrVerification) {
289 *self.inner.verification.borrow_mut() = qr.into();
290 }
291
292 pub async fn update(&mut self, sas: SasVerification) -> Result<(), Error> {
293 *self.inner.verification.borrow_mut() = sas.into();
294 let verification = self.inner.verification.borrow().clone();
295
296 if let Some(c) = self.inner.connection.borrow().clone() {
297 c.spawn(async move { verification.accept().await }).await?;
298 } else {
299 // TODO print an error
300 }
301
302 Ok(())
303 }
304
305 pub async fn handle_event(&self, event: &AnyToDeviceEvent) {
306 match event {
307 AnyToDeviceEvent::KeyVerificationRequest(e) => {
308 if let Verification::Request(request) =
309 self.inner.verification.borrow().clone()
310 {
311 let content = e
312 .content
313 .render(&VerificationContext::ToDevice(request));
314
315 self.print(&content);
316 }
317 }
318 AnyToDeviceEvent::KeyVerificationStart(e) => {
319 let verification = self.inner.verification.borrow().clone();
320
321 if let Ok(verification) = verification.try_into() {
322 let content =
323 e.content.render(&StartVerificationContext::ToDevice(
324 e.sender.clone(),
325 verification,
326 ));
327
328 self.print(&content);
329 }
330 }
331 AnyToDeviceEvent::KeyVerificationCancel(_) => {
332 // let message =
333 // format!("The verification flow has been canceled");
334 // self.print(&message);
335 }
336 AnyToDeviceEvent::KeyVerificationKey(e) => {
337 self.print_sas(&e.content);
338 }
339 AnyToDeviceEvent::KeyVerificationMac(_) => {
340 if let Verification::Sas(sas) =
341 self.inner.verification.borrow().clone()
342 {
343 if sas.is_done() {
344 self.inner.print_done(self.buffer.clone());
345 }
346 }
347 }
348 AnyToDeviceEvent::KeyVerificationDone(_) => {}
349 _ => {}
350 }
351 }
352
353 fn print(&self, message: &RenderedContent) {
354 if let Ok(buffer) = self.buffer.upgrade() {
355 for line in &message.lines {
356 buffer.print_date_tags(0, &[], &line.message);
357 }
358 } else {
359 Weechat::print("BUFFER CLOSED");
360 }
361 }
362
363 fn print_sas(&self, content: &ToDeviceKeyVerificationKeyEventContent) {
364 if let Verification::Sas(sas) = self.inner.verification.borrow().clone()
365 {
366 let message = content.render(&sas);
367 self.print(&message);
368 }
369 }
370}