Commit 4cc5777b63
Unsigned
Layout: unified · split
Cargo.lock +63 −1
| @@ -400,12 +400,24 @@ version = "3.7.0" | ||
| 400 | 400 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 401 | 401 | checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631" |
| 402 | 402 | |
| 403 | [[package]] | |
| 404 | name = "bytemuck" | |
| 405 | version = "1.23.0" | |
| 406 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 407 | checksum = "9134a6ef01ce4b366b50689c94f82c14bc72bc5d0386829828a2e2752ef7958c" | |
| 408 | ||
| 403 | 409 | [[package]] |
| 404 | 410 | name = "byteorder" |
| 405 | 411 | version = "1.5.0" |
| 406 | 412 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 407 | 413 | checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" |
| 408 | 414 | |
| 415 | [[package]] | |
| 416 | name = "byteorder-lite" | |
| 417 | version = "0.1.0" | |
| 418 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 419 | checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" | |
| 420 | ||
| 409 | 421 | [[package]] |
| 410 | 422 | name = "bytes" |
| 411 | 423 | version = "1.10.1" |
| @@ -1631,6 +1643,19 @@ dependencies = [ | ||
| 1631 | 1643 | "icu_properties", |
| 1632 | 1644 | ] |
| 1633 | 1645 | |
| 1646 | [[package]] | |
| 1647 | name = "image" | |
| 1648 | version = "0.25.6" | |
| 1649 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1650 | checksum = "db35664ce6b9810857a38a906215e75a9c879f0696556a39f59c62829710251a" | |
| 1651 | dependencies = [ | |
| 1652 | "bytemuck", | |
| 1653 | "byteorder-lite", | |
| 1654 | "num-traits", | |
| 1655 | "zune-core", | |
| 1656 | "zune-jpeg", | |
| 1657 | ] | |
| 1658 | ||
| 1634 | 1659 | [[package]] |
| 1635 | 1660 | name = "imbl" |
| 1636 | 1661 | version = "5.0.0" |
| @@ -2170,6 +2195,7 @@ dependencies = [ | ||
| 2170 | 2195 | "itertools 0.14.0", |
| 2171 | 2196 | "js_option", |
| 2172 | 2197 | "matrix-sdk-common", |
| 2198 | "matrix-sdk-qrcode", | |
| 2173 | 2199 | "pbkdf2", |
| 2174 | 2200 | "rand 0.8.5", |
| 2175 | 2201 | "rmp-serde", |
| @@ -2219,6 +2245,19 @@ dependencies = [ | ||
| 2219 | 2245 | "zeroize", |
| 2220 | 2246 | ] |
| 2221 | 2247 | |
| 2248 | [[package]] | |
| 2249 | name = "matrix-sdk-qrcode" | |
| 2250 | version = "0.14.0" | |
| 2251 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2252 | checksum = "6e46baa0a7fd0e6e648887c0edfeb739682f7e12242986ffdf4300791cdbe199" | |
| 2253 | dependencies = [ | |
| 2254 | "byteorder", | |
| 2255 | "qrcode", | |
| 2256 | "ruma", | |
| 2257 | "thiserror 2.0.16", | |
| 2258 | "vodozemac", | |
| 2259 | ] | |
| 2260 | ||
| 2222 | 2261 | [[package]] |
| 2223 | 2262 | name = "matrix-sdk-search" |
| 2224 | 2263 | version = "0.14.0" |
| @@ -2761,7 +2800,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2761 | 2800 | checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" |
| 2762 | 2801 | dependencies = [ |
| 2763 | 2802 | "anyhow", |
| 2764 | "itertools 0.14.0", | |
| 2803 | "itertools 0.12.1", | |
| 2765 | 2804 | "proc-macro2", |
| 2766 | 2805 | "quote", |
| 2767 | 2806 | "syn 2.0.87", |
| @@ -2785,6 +2824,12 @@ version = "0.11.0" | ||
| 2785 | 2824 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2786 | 2825 | checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" |
| 2787 | 2826 | |
| 2827 | [[package]] | |
| 2828 | name = "qrcode" | |
| 2829 | version = "0.14.1" | |
| 2830 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2831 | checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" | |
| 2832 | ||
| 2788 | 2833 | [[package]] |
| 2789 | 2834 | name = "quote" |
| 2790 | 2835 | version = "1.0.37" |
| @@ -4528,7 +4573,9 @@ dependencies = [ | ||
| 4528 | 4573 | "chrono", |
| 4529 | 4574 | "clap", |
| 4530 | 4575 | "dashmap", |
| 4576 | "image", | |
| 4531 | 4577 | "matrix-sdk", |
| 4578 | "qrcode", | |
| 4532 | 4579 | "serde_json", |
| 4533 | 4580 | "strum", |
| 4534 | 4581 | "tokio", |
| @@ -4852,3 +4899,18 @@ dependencies = [ | ||
| 4852 | 4899 | "cc", |
| 4853 | 4900 | "pkg-config", |
| 4854 | 4901 | ] |
| 4902 | ||
| 4903 | [[package]] | |
| 4904 | name = "zune-core" | |
| 4905 | version = "0.4.12" | |
| 4906 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 4907 | checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" | |
| 4908 | ||
| 4909 | [[package]] | |
| 4910 | name = "zune-jpeg" | |
| 4911 | version = "0.4.21" | |
| 4912 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 4913 | checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" | |
| 4914 | dependencies = [ | |
| 4915 | "zune-core", | |
| 4916 | ] | |
Cargo.toml +5 −1
| @@ -26,6 +26,10 @@ tracing-subscriber = { version = "0.3.15", features = ["env-filter"] } | ||
| 26 | 26 | uuid = { version = "1.1.2", features = ["v4"] } |
| 27 | 27 | unicode-segmentation = "1.10.0" |
| 28 | 28 | |
| 29 | # Auto-select version from matrix-sdk | |
| 30 | qrcode = { version = "*", default-features = false } | |
| 31 | image = { version = "*", default-features = false, features = ["jpeg"] } | |
| 32 | ||
| 29 | 33 | [dependencies.weechat] |
| 30 | 34 | git = "https://github.com/poljar/rust-weechat" |
| 31 | 35 | features = ["async", "config_macro"] |
| @@ -34,7 +38,7 @@ features = ["async", "config_macro"] | ||
| 34 | 38 | version = "0.14.0" |
| 35 | 39 | # git = "https://github.com/matrix-org/matrix-rust-sdk.git" |
| 36 | 40 | # rev = "92192c549b3f53889c23954386743867a73b31b1" |
| 37 | features = ["markdown", "socks"] | |
| 41 | features = ["markdown", "socks", "qrcode"] | |
| 38 | 42 | |
| 39 | 43 | [profile.dev.package] |
| 40 | 44 | sha2 = { opt-level = 2 } |
src/bar_items/buffer_name.rs +5
| @@ -45,6 +45,11 @@ impl BarItemCallback for BufferName { | ||
| 45 | 45 | format!("{}{}", Weechat::color(color), buffer.short_name()) |
| 46 | 46 | } |
| 47 | 47 | |
| 48 | BufferOwner::Verification(_, _) => { | |
| 49 | // TODO special format this | |
| 50 | format!("{}{}", Weechat::color("status_name"), buffer.name()) | |
| 51 | } | |
| 52 | ||
| 48 | 53 | BufferOwner::None => { |
| 49 | 54 | format!("{}{}", Weechat::color("status_name"), buffer.name()) |
| 50 | 55 | } |
src/bar_items/buffer_plugin.rs +3 −1
| @@ -20,7 +20,9 @@ impl BufferPlugin { | ||
| 20 | 20 | impl BarItemCallback for BufferPlugin { |
| 21 | 21 | fn callback(&mut self, _: &Weechat, buffer: &Buffer) -> String { |
| 22 | 22 | 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, _) => { | |
| 24 | 26 | format!( |
| 25 | 27 | "{plugin_name}{del_color}/{color}{name}", |
| 26 | 28 | plugin_name = PLUGIN_NAME, |
src/commands/matrix.rs +15 −1
| @@ -10,7 +10,7 @@ use weechat::{ | ||
| 10 | 10 | Args, Prefix, Weechat, |
| 11 | 11 | }; |
| 12 | 12 | |
| 13 | use super::parse_and_run; | |
| 13 | use super::{parse_and_run, verification::VerificationCommand}; | |
| 14 | 14 | use crate::{ |
| 15 | 15 | commands::{DevicesCommand, KeysCommand}, |
| 16 | 16 | config::ConfigHandle, |
| @@ -44,14 +44,20 @@ impl MatrixCommand { | ||
| 44 | 44 | reconnect: Reconnect to server(s). |
| 45 | 45 | devices: {} |
| 46 | 46 | keys: {} |
| 47 | verification: {} | |
| 47 | 48 | help: Show detailed command help.\n |
| 48 | 49 | Use /matrix [command] help to find out more.\n", |
| 49 | 50 | DevicesCommand::DESCRIPTION, |
| 50 | 51 | KeysCommand::DESCRIPTION, |
| 52 | VerificationCommand::DESCRIPTION, | |
| 51 | 53 | )) |
| 52 | 54 | .add_completion("server add|delete|list|listfull") |
| 53 | 55 | .add_completion("devices list|delete|set-name %(matrix-users)") |
| 54 | 56 | .add_completion(format!("keys {}", KeysCommand::COMPLETION)) |
| 57 | .add_completion(format!( | |
| 58 | "verification {}", | |
| 59 | VerificationCommand::COMPLETION | |
| 60 | )) | |
| 55 | 61 | .add_completion("connect %(matrix_servers)") |
| 56 | 62 | .add_completion("disconnect %(matrix_servers)") |
| 57 | 63 | .add_completion("reconnect %(matrix_servers)") |
| @@ -224,6 +230,9 @@ Use /matrix [command] help to find out more.\n", | ||
| 224 | 230 | ("keys", Some(subargs)) => { |
| 225 | 231 | KeysCommand::run(buffer, &self.servers, subargs) |
| 226 | 232 | } |
| 233 | ("verification", Some(subargs)) => { | |
| 234 | VerificationCommand::run(buffer, &self.servers, subargs) | |
| 235 | } | |
| 227 | 236 | _ => unreachable!(), |
| 228 | 237 | } |
| 229 | 238 | } |
| @@ -291,6 +300,11 @@ impl CommandCallback for MatrixCommand { | ||
| 291 | 300 | .settings(KeysCommand::SETTINGS) |
| 292 | 301 | .subcommands(KeysCommand::subcommands()), |
| 293 | 302 | ) |
| 303 | .subcommand( | |
| 304 | SubCommand::with_name("verification") | |
| 305 | .about(VerificationCommand::DESCRIPTION) | |
| 306 | .subcommands(VerificationCommand::subcommands()), | |
| 307 | ) | |
| 294 | 308 | .subcommand( |
| 295 | 309 | SubCommand::with_name("connect") |
| 296 | 310 | .about("Connect to Matrix servers.") |
src/commands/mod.rs +4
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | use clap::{App, ArgMatches}; |
| 2 | use verification::VerificationCommand; | |
| 2 | 3 | use weechat::{ |
| 3 | 4 | hooks::{Command, CommandRun}, |
| 4 | 5 | Args, Weechat, |
| @@ -12,6 +13,7 @@ mod keys; | ||
| 12 | 13 | mod matrix; |
| 13 | 14 | mod me; |
| 14 | 15 | mod page_up; |
| 16 | mod verification; | |
| 15 | 17 | |
| 16 | 18 | use buffer_clear::BufferClearCommand; |
| 17 | 19 | use devices::DevicesCommand; |
| @@ -25,6 +27,7 @@ pub struct Commands { | ||
| 25 | 27 | _keys: Command, |
| 26 | 28 | _devices: Command, |
| 27 | 29 | _page_up: CommandRun, |
| 30 | _verification: Command, | |
| 28 | 31 | _buffer_clear: CommandRun, |
| 29 | 32 | _me: CommandRun, |
| 30 | 33 | } |
| @@ -39,6 +42,7 @@ impl Commands { | ||
| 39 | 42 | _devices: DevicesCommand::create(servers)?, |
| 40 | 43 | _keys: KeysCommand::create(servers)?, |
| 41 | 44 | _page_up: PageUpCommand::create(servers)?, |
| 45 | _verification: VerificationCommand::create(servers)?, | |
| 42 | 46 | _buffer_clear: BufferClearCommand::create(servers)?, |
| 43 | 47 | _me: MeCommand::create(servers)?, |
| 44 | 48 | }) |
src/commands/verification.rs added +117
| @@ -0,0 +1,117 @@ | ||
| 1 | use clap::{ | |
| 2 | App as Argparse, AppSettings as ArgParseSettings, ArgMatches, SubCommand, | |
| 3 | }; | |
| 4 | ||
| 5 | use weechat::{ | |
| 6 | buffer::Buffer, | |
| 7 | hooks::{Command, CommandCallback, CommandSettings}, | |
| 8 | Args, Weechat, | |
| 9 | }; | |
| 10 | ||
| 11 | use super::parse_and_run; | |
| 12 | use crate::{BufferOwner, Servers}; | |
| 13 | ||
| 14 | pub struct VerificationCommand { | |
| 15 | servers: Servers, | |
| 16 | } | |
| 17 | ||
| 18 | enum CommandType { | |
| 19 | Accept, | |
| 20 | Confirm, | |
| 21 | Cancel, | |
| 22 | } | |
| 23 | ||
| 24 | impl 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 | ||
| 103 | impl 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::{ | ||
| 33 | 33 | }, |
| 34 | 34 | events::{ |
| 35 | 35 | room::member::RoomMemberEventContent, AnyMessageLikeEventContent, |
| 36 | AnySyncStateEvent, AnySyncTimelineEvent, SyncStateEvent, | |
| 36 | AnySyncStateEvent, AnySyncTimelineEvent, AnyToDeviceEvent, | |
| 37 | SyncStateEvent, | |
| 37 | 38 | }, |
| 38 | 39 | OwnedDeviceId, OwnedRoomId, OwnedTransactionId, |
| 39 | 40 | }, |
| @@ -69,6 +70,7 @@ pub enum ClientMessage { | ||
| 69 | 70 | LoginMessage(LoginResponse), |
| 70 | 71 | SyncState(OwnedRoomId, AnySyncStateEvent), |
| 71 | 72 | SyncEvent(OwnedRoomId, AnySyncTimelineEvent), |
| 73 | ToDeviceEvent(AnyToDeviceEvent), | |
| 72 | 74 | MemberEvent( |
| 73 | 75 | OwnedRoomId, |
| 74 | 76 | SyncStateEvent<RoomMemberEventContent>, |
| @@ -291,6 +293,9 @@ impl Connection { | ||
| 291 | 293 | ClientMessage::RestoredRoom(room) => { |
| 292 | 294 | server.restore_room(room).await |
| 293 | 295 | } |
| 296 | ClientMessage::ToDeviceEvent(e) => { | |
| 297 | server.receive_to_device_event(e).await | |
| 298 | } | |
| 294 | 299 | ClientMessage::MemberEvent( |
| 295 | 300 | room_id, |
| 296 | 301 | e, |
| @@ -432,6 +437,16 @@ impl Connection { | ||
| 432 | 437 | loop { |
| 433 | 438 | let ret = client |
| 434 | 439 | .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 | ||
| 435 | 450 | for (room_id, room) in response.rooms.joined { |
| 436 | 451 | if let State::Before(state) = room.state { |
| 437 | 452 | for event in |
src/lib.rs +15
| @@ -8,6 +8,7 @@ mod render; | ||
| 8 | 8 | mod room; |
| 9 | 9 | mod server; |
| 10 | 10 | mod utils; |
| 11 | mod verification_buffer; | |
| 11 | 12 | |
| 12 | 13 | use std::{ |
| 13 | 14 | cell::{Ref, RefCell}, |
| @@ -27,6 +28,7 @@ use weechat::{ | ||
| 27 | 28 | use crate::{ |
| 28 | 29 | bar_items::BarItems, commands::Commands, completions::Completions, |
| 29 | 30 | config::ConfigHandle, room::RoomHandle, server::MatrixServer, |
| 31 | verification_buffer::VerificationBuffer, | |
| 30 | 32 | }; |
| 31 | 33 | |
| 32 | 34 | const PLUGIN_NAME: &str = "matrix"; |
| @@ -41,6 +43,7 @@ pub struct Servers { | ||
| 41 | 43 | pub enum BufferOwner { |
| 42 | 44 | Server(MatrixServer), |
| 43 | 45 | Room(MatrixServer, RoomHandle), |
| 46 | Verification(MatrixServer, VerificationBuffer), | |
| 44 | 47 | None, |
| 45 | 48 | } |
| 46 | 49 | |
| @@ -49,6 +52,7 @@ impl BufferOwner { | ||
| 49 | 52 | match self { |
| 50 | 53 | BufferOwner::Server(s) => Some(s), |
| 51 | 54 | BufferOwner::Room(s, _) => Some(s), |
| 55 | BufferOwner::Verification(s, _) => Some(s), | |
| 52 | 56 | BufferOwner::None => None, |
| 53 | 57 | } |
| 54 | 58 | } |
| @@ -123,6 +127,17 @@ impl Servers { | ||
| 123 | 127 | } |
| 124 | 128 | } |
| 125 | 129 | } |
| 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 | } | |
| 126 | 141 | } |
| 127 | 142 | |
| 128 | 143 | BufferOwner::None |
src/render.rs +269 −15
| @@ -1,23 +1,45 @@ | ||
| 1 | 1 | use url::Url; |
| 2 | 2 | |
| 3 | use 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, | |
| 3 | use 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, | |
| 15 | 37 | }, |
| 16 | EncryptedFile, MediaSource, | |
| 38 | OriginalSyncStateEvent, RedactedSyncMessageLikeEvent, | |
| 17 | 39 | }, |
| 18 | OriginalSyncStateEvent, RedactedSyncMessageLikeEvent, | |
| 40 | uint, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedUserId, | |
| 41 | TransactionId, UserId, | |
| 19 | 42 | }, |
| 20 | uint, EventId, MilliSecondsSinceUnixEpoch, MxcUri, TransactionId, UserId, | |
| 21 | 43 | }; |
| 22 | 44 | |
| 23 | 45 | use weechat::{Prefix, Weechat}; |
| @@ -473,6 +495,238 @@ impl Render for RedactedSyncMessageLikeEvent<RedactedRoomMessageEventContent> { | ||
| 473 | 495 | } |
| 474 | 496 | } |
| 475 | 497 | |
| 498 | pub enum StartVerificationContext { | |
| 499 | Room(OwnedUserId, Verification), | |
| 500 | ToDevice(OwnedUserId, Verification), | |
| 501 | } | |
| 502 | ||
| 503 | impl 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 | ||
| 523 | macro_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 | ||
| 600 | render_start_content!(KeyVerificationStartEventContent); | |
| 601 | render_start_content!(ToDeviceKeyVerificationStartEventContent); | |
| 602 | ||
| 603 | pub enum VerificationContext { | |
| 604 | Room(WeechatRoomMember, WeechatRoomMember), | |
| 605 | ToDevice(VerificationRequest), | |
| 606 | } | |
| 607 | ||
| 608 | macro_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 | ||
| 647 | render_request_content!(KeyVerificationRequestEventContent); | |
| 648 | render_request_content!(ToDeviceKeyVerificationRequestEventContent); | |
| 649 | ||
| 650 | macro_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 | ||
| 684 | render_ready_content!(KeyVerificationReadyEventContent); | |
| 685 | render_ready_content!(ToDeviceKeyVerificationReadyEventContent); | |
| 686 | ||
| 687 | macro_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 | ||
| 727 | render_key_content!(KeyVerificationKeyEventContent); | |
| 728 | render_key_content!(ToDeviceKeyVerificationKeyEventContent); | |
| 729 | ||
| 476 | 730 | /// Trait for message event types that contain an optional formatted body. |
| 477 | 731 | /// `resolve_body` will return the formatted body if present, else fallback to |
| 478 | 732 | /// the regular body. |
src/room/buffer.rs added +274
| @@ -0,0 +1,274 @@ | ||
| 1 | use std::{borrow::Cow, cell::RefCell, rc::Rc}; | |
| 2 | ||
| 3 | use matrix_sdk::{ | |
| 4 | ruma::{EventId, OwnedRoomAliasId, TransactionId, UserId}, | |
| 5 | Room, StoreError, | |
| 6 | }; | |
| 7 | use tokio::runtime::Handle; | |
| 8 | use weechat::{ | |
| 9 | buffer::{Buffer, BufferHandle, BufferLine, LineData}, | |
| 10 | Prefix, Weechat, | |
| 11 | }; | |
| 12 | ||
| 13 | use crate::{render::RenderedEvent, utils::ToTag}; | |
| 14 | ||
| 15 | #[derive(Clone)] | |
| 16 | pub struct RoomBuffer { | |
| 17 | room: Room, | |
| 18 | runtime: Handle, | |
| 19 | pub(super) inner: Rc<RefCell<Option<BufferHandle>>>, | |
| 20 | } | |
| 21 | ||
| 22 | impl 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) = ¤t_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 @@ | ||
| 1 | use std::{cell::RefCell, rc::Rc}; | |
| 1 | use std::rc::Rc; | |
| 2 | 2 | |
| 3 | 3 | use dashmap::DashMap; |
| 4 | 4 | use tokio::runtime::Handle; |
| @@ -17,15 +17,14 @@ use matrix_sdk::{ | ||
| 17 | 17 | }, |
| 18 | 18 | uint, Int, OwnedUserId, UserId, |
| 19 | 19 | }, |
| 20 | StoreError, | |
| 21 | 20 | }; |
| 22 | 21 | |
| 23 | 22 | use weechat::{ |
| 24 | buffer::{Buffer, BufferHandle, NickSettings}, | |
| 23 | buffer::{Buffer, NickSettings}, | |
| 25 | 24 | Prefix, Weechat, |
| 26 | 25 | }; |
| 27 | 26 | |
| 28 | use crate::render::render_membership; | |
| 27 | use crate::{render::render_membership, room::buffer::RoomBuffer}; | |
| 29 | 28 | |
| 30 | 29 | #[derive(Clone)] |
| 31 | 30 | pub struct Members { |
| @@ -33,7 +32,7 @@ pub struct Members { | ||
| 33 | 32 | pub(super) runtime: Handle, |
| 34 | 33 | ambiguity_map: Rc<DashMap<OwnedUserId, bool>>, |
| 35 | 34 | nicks: Rc<DashMap<OwnedUserId, String>>, |
| 36 | pub(super) buffer: Rc<RefCell<Option<BufferHandle>>>, | |
| 35 | buffer: RoomBuffer, | |
| 37 | 36 | } |
| 38 | 37 | |
| 39 | 38 | #[derive(Clone, Debug)] |
| @@ -43,24 +42,23 @@ pub struct WeechatRoomMember { | ||
| 43 | 42 | ambiguous_nick: Rc<bool>, |
| 44 | 43 | } |
| 45 | 44 | |
| 45 | impl PartialEq for WeechatRoomMember { | |
| 46 | fn eq(&self, other: &Self) -> bool { | |
| 47 | self.user_id() == other.user_id() | |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 46 | 51 | impl Members { |
| 47 | pub fn new(room: Room, runtime: Handle) -> Self { | |
| 52 | pub fn new(room: Room, runtime: Handle, buffer: RoomBuffer) -> Self { | |
| 48 | 53 | Self { |
| 49 | 54 | room, |
| 50 | 55 | runtime, |
| 51 | 56 | nicks: DashMap::new().into(), |
| 52 | 57 | ambiguity_map: DashMap::new().into(), |
| 53 | buffer: RefCell::new(None).into(), | |
| 58 | buffer, | |
| 54 | 59 | } |
| 55 | 60 | } |
| 56 | 61 | |
| 57 | fn buffer(&self) -> BufferHandle { | |
| 58 | self.buffer | |
| 59 | .borrow() | |
| 60 | .clone() | |
| 61 | .expect("Members struct wasn't initialized properly") | |
| 62 | } | |
| 63 | ||
| 64 | 62 | fn add_nick(&self, buffer: &Buffer, member: &WeechatRoomMember) { |
| 65 | 63 | let nick = member.nick(); |
| 66 | 64 | |
| @@ -88,14 +86,6 @@ impl Members { | ||
| 88 | 86 | } |
| 89 | 87 | |
| 90 | 88 | 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 | ||
| 99 | 89 | let room = self.room.clone(); |
| 100 | 90 | let user = user_id.to_owned(); |
| 101 | 91 | |
| @@ -114,7 +104,7 @@ impl Members { | ||
| 114 | 104 | panic!( |
| 115 | 105 | "Couldn't find member {} in {}", |
| 116 | 106 | user_id, |
| 117 | buffer.short_name() | |
| 107 | self.buffer.short_name() | |
| 118 | 108 | ) |
| 119 | 109 | } |
| 120 | 110 | Err(e) => { |
| @@ -128,7 +118,7 @@ impl Members { | ||
| 128 | 118 | } |
| 129 | 119 | |
| 130 | 120 | pub async fn update_member(&self, user_id: &UserId) { |
| 131 | let buffer = self.buffer(); | |
| 121 | let buffer = self.buffer.buffer_handle(); | |
| 132 | 122 | |
| 133 | 123 | let buffer = if let Ok(b) = buffer.upgrade() { |
| 134 | 124 | b |
| @@ -198,7 +188,7 @@ impl Members { | ||
| 198 | 188 | } |
| 199 | 189 | } |
| 200 | 190 | |
| 201 | let buffer = self.buffer(); | |
| 191 | let buffer = self.buffer.buffer_handle(); | |
| 202 | 192 | |
| 203 | 193 | let buffer = if let Ok(b) = buffer.upgrade() { |
| 204 | 194 | b |
| @@ -254,51 +244,13 @@ impl Members { | ||
| 254 | 244 | &self.room |
| 255 | 245 | } |
| 256 | 246 | |
| 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 | ||
| 295 | 247 | pub async fn handle_membership_event( |
| 296 | 248 | &self, |
| 297 | 249 | event: &SyncStateEvent<RoomMemberEventContent>, |
| 298 | 250 | state_event: bool, |
| 299 | 251 | ambiguity_change: Option<&AmbiguityChange>, |
| 300 | 252 | ) { |
| 301 | let buffer = self.buffer(); | |
| 253 | let buffer = self.buffer.buffer_handle(); | |
| 302 | 254 | let buffer = if let Ok(b) = buffer.upgrade() { |
| 303 | 255 | b |
| 304 | 256 | } else { |
| @@ -352,7 +304,7 @@ impl Members { | ||
| 352 | 304 | |
| 353 | 305 | // Names of rooms without display names can get affected by the |
| 354 | 306 | // member list so we need to update them. |
| 355 | self.update_buffer_name(); | |
| 307 | self.buffer.update_buffer_name(); | |
| 356 | 308 | |
| 357 | 309 | if !state_event { |
| 358 | 310 | let sender = self.get(&sender_id).await; |
src/room/mod.rs +53 −201
| @@ -22,12 +22,16 @@ | ||
| 22 | 22 | //! we're sending ourselves before we receive them in a sync response, or if we |
| 23 | 23 | //! decrypt a previously undecryptable event. |
| 24 | 24 | |
| 25 | mod buffer; | |
| 25 | 26 | mod members; |
| 27 | mod verification; | |
| 26 | 28 | |
| 29 | use buffer::RoomBuffer; | |
| 27 | 30 | use members::Members; |
| 28 | 31 | pub use members::WeechatRoomMember; |
| 29 | 32 | use tokio::runtime::Handle; |
| 30 | 33 | use tracing::{debug, trace}; |
| 34 | use verification::Verification; | |
| 31 | 35 | |
| 32 | 36 | use std::{ |
| 33 | 37 | borrow::Cow, |
| @@ -71,7 +75,7 @@ use matrix_sdk::{ | ||
| 71 | 75 | use weechat::{ |
| 72 | 76 | buffer::{ |
| 73 | 77 | Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync, |
| 74 | BufferLine, LineData, | |
| 78 | BufferLine, | |
| 75 | 79 | }, |
| 76 | 80 | Weechat, |
| 77 | 81 | }; |
| @@ -80,7 +84,7 @@ use crate::{ | ||
| 80 | 84 | config::{Config, RedactionStyle}, |
| 81 | 85 | connection::Connection, |
| 82 | 86 | render::{Render, RenderedEvent}, |
| 83 | utils::{Edit, ToTag}, | |
| 87 | utils::{Edit, VerificationEvent}, | |
| 84 | 88 | PLUGIN_NAME, |
| 85 | 89 | }; |
| 86 | 90 | |
| @@ -149,7 +153,7 @@ pub struct MatrixRoom { | ||
| 149 | 153 | room_id: Rc<RoomId>, |
| 150 | 154 | own_user_id: Rc<UserId>, |
| 151 | 155 | room: Room, |
| 152 | buffer: Rc<RefCell<Option<BufferHandle>>>, | |
| 156 | buffer: RoomBuffer, | |
| 153 | 157 | |
| 154 | 158 | config: Rc<RefCell<Config>>, |
| 155 | 159 | connection: Rc<RefCell<Option<Connection>>>, |
| @@ -160,6 +164,7 @@ pub struct MatrixRoom { | ||
| 160 | 164 | outgoing_messages: MessageQueue, |
| 161 | 165 | |
| 162 | 166 | members: Members, |
| 167 | verification: Verification, | |
| 163 | 168 | } |
| 164 | 169 | |
| 165 | 170 | #[derive(Debug, Clone, Default)] |
| @@ -207,7 +212,9 @@ impl RoomHandle { | ||
| 207 | 212 | room_id: &RoomId, |
| 208 | 213 | own_user_id: &UserId, |
| 209 | 214 | ) -> 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()); | |
| 211 | 218 | |
| 212 | 219 | let own_nick = runtime |
| 213 | 220 | .block_on(room.get_member_no_sync(own_user_id)) |
| @@ -216,6 +223,13 @@ impl RoomHandle { | ||
| 216 | 223 | .map(|m| m.name().to_owned()) |
| 217 | 224 | .unwrap_or_else(|| own_user_id.localpart().to_owned()); |
| 218 | 225 | |
| 226 | let verification = Verification::new( | |
| 227 | own_user_id.into(), | |
| 228 | connection.clone(), | |
| 229 | members.clone(), | |
| 230 | buffer.clone(), | |
| 231 | ); | |
| 232 | ||
| 219 | 233 | let room = MatrixRoom { |
| 220 | 234 | homeserver: Rc::new(homeserver), |
| 221 | 235 | room_id: room_id.into(), |
| @@ -225,8 +239,9 @@ impl RoomHandle { | ||
| 225 | 239 | room.last_prev_batch().map(PrevBatch::Backwards), |
| 226 | 240 | )), |
| 227 | 241 | own_user_id: own_user_id.into(), |
| 228 | members: members.clone(), | |
| 229 | buffer: members.buffer, | |
| 242 | members, | |
| 243 | buffer, | |
| 244 | verification, | |
| 230 | 245 | outgoing_messages: MessageQueue::new(), |
| 231 | 246 | messages_in_flight: IntMutex::new(), |
| 232 | 247 | room, |
| @@ -305,7 +320,7 @@ impl RoomHandle { | ||
| 305 | 320 | buffer.set_localvar("alias", alias.as_str()); |
| 306 | 321 | } |
| 307 | 322 | |
| 308 | *room.members.buffer.borrow_mut() = Some(buffer_handle.clone()); | |
| 323 | *room.buffer.inner.borrow_mut() = Some(buffer_handle.clone()); | |
| 309 | 324 | |
| 310 | 325 | Self { inner: room } |
| 311 | 326 | } |
| @@ -349,8 +364,8 @@ impl RoomHandle { | ||
| 349 | 364 | *room_buffer.prev_batch.borrow_mut() = |
| 350 | 365 | prev_batch.map(PrevBatch::Forward); |
| 351 | 366 | |
| 352 | room_buffer.update_buffer_name(); | |
| 353 | room_buffer.set_topic(); | |
| 367 | room_buffer.buffer.update_buffer_name(); | |
| 368 | room_buffer.buffer.set_topic(); | |
| 354 | 369 | |
| 355 | 370 | Ok(room_buffer) |
| 356 | 371 | } |
| @@ -409,28 +424,21 @@ impl MatrixRoom { | ||
| 409 | 424 | } |
| 410 | 425 | |
| 411 | 426 | 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() | |
| 417 | 428 | } |
| 418 | 429 | |
| 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!() | |
| 434 | 442 | } |
| 435 | 443 | |
| 436 | 444 | async fn redact_event(&self, event: &SyncRoomRedactionEvent) { |
| @@ -650,7 +658,7 @@ impl MatrixRoom { | ||
| 650 | 658 | let local_echo = c |
| 651 | 659 | .render_with_prefix_for_echo(&sender, transaction_id, &()) |
| 652 | 660 | .add_self_tags(); |
| 653 | self.print_rendered_event(local_echo); | |
| 661 | self.buffer.print_rendered_event(local_echo); | |
| 654 | 662 | |
| 655 | 663 | self.outgoing_messages |
| 656 | 664 | .add_with_echo(transaction_id.to_owned(), content.clone()); |
| @@ -693,7 +701,7 @@ impl MatrixRoom { | ||
| 693 | 701 | .send_message( |
| 694 | 702 | self.room().clone(), |
| 695 | 703 | AnyMessageLikeEventContent::RoomMessage(content), |
| 696 | Some(transaction_id.to_owned()), | |
| 704 | Some(transaction_id.clone()), | |
| 697 | 705 | ) |
| 698 | 706 | .await |
| 699 | 707 | { |
| @@ -809,12 +817,12 @@ impl MatrixRoom { | ||
| 809 | 817 | |
| 810 | 818 | if let Some(PrevBatch::Forward(t)) = prev_batch.as_ref() { |
| 811 | 819 | *prev_batch = Some(PrevBatch::Backwards(t.to_owned())); |
| 812 | self.sort_messages(); | |
| 820 | self.buffer.sort_messages(); | |
| 813 | 821 | } else if r.chunk.is_empty() { |
| 814 | 822 | *prev_batch = None; |
| 815 | 823 | } else { |
| 816 | 824 | *prev_batch = r.end.map(PrevBatch::Backwards); |
| 817 | self.sort_messages(); | |
| 825 | self.buffer.sort_messages(); | |
| 818 | 826 | } |
| 819 | 827 | } |
| 820 | 828 | } |
| @@ -825,75 +833,6 @@ impl MatrixRoom { | ||
| 825 | 833 | Weechat::bar_item_update("matrix_modes"); |
| 826 | 834 | } |
| 827 | 835 | |
| 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) = ¤t_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 | ||
| 897 | 836 | async fn handle_outgoing_message( |
| 898 | 837 | &self, |
| 899 | 838 | transaction_id: &TransactionId, |
| @@ -919,100 +858,11 @@ impl MatrixRoom { | ||
| 919 | 858 | .await |
| 920 | 859 | .expect("Sent out an event that we don't know how to render"); |
| 921 | 860 | |
| 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); | |
| 1014 | 865 | } |
| 1015 | Ordering::Equal => (), | |
| 1016 | 866 | } |
| 1017 | 867 | } |
| 1018 | 868 | |
| @@ -1045,7 +895,7 @@ impl MatrixRoom { | ||
| 1045 | 895 | } |
| 1046 | 896 | }) |
| 1047 | 897 | { |
| 1048 | self.replace_edit(event_id, event.sender(), rendered); | |
| 898 | self.buffer.replace_edit(event_id, event.sender(), rendered); | |
| 1049 | 899 | } |
| 1050 | 900 | } |
| 1051 | 901 | } |
| @@ -1061,10 +911,12 @@ impl MatrixRoom { | ||
| 1061 | 911 | |
| 1062 | 912 | if let AnySyncMessageLikeEvent::RoomRedaction(r) = event { |
| 1063 | 913 | self.redact_event(r).await; |
| 914 | } else if event.is_verification() { | |
| 915 | self.verification.handle_room_verification(event).await; | |
| 1064 | 916 | } else if event.is_edit() { |
| 1065 | 917 | self.handle_edits(event).await; |
| 1066 | 918 | } else if let Some(rendered) = self.render_sync_message(event).await { |
| 1067 | self.print_rendered_event(rendered); | |
| 919 | self.buffer.print_rendered_event(rendered); | |
| 1068 | 920 | } |
| 1069 | 921 | } |
| 1070 | 922 | |
| @@ -1159,7 +1011,7 @@ impl MatrixRoom { | ||
| 1159 | 1011 | ) |
| 1160 | 1012 | .await |
| 1161 | 1013 | { |
| 1162 | self.print_rendered_event(rendered); | |
| 1014 | self.buffer.print_rendered_event(rendered); | |
| 1163 | 1015 | } |
| 1164 | 1016 | } |
| 1165 | 1017 | } |
| @@ -1178,9 +1030,9 @@ impl MatrixRoom { | ||
| 1178 | 1030 | _state_event: bool, |
| 1179 | 1031 | ) { |
| 1180 | 1032 | 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(), | |
| 1184 | 1036 | _ => (), |
| 1185 | 1037 | } |
| 1186 | 1038 | } |
src/room/verification.rs added +226
| @@ -0,0 +1,226 @@ | ||
| 1 | use std::{cell::RefCell, rc::Rc}; | |
| 2 | ||
| 3 | use 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 | ||
| 14 | use crate::{ | |
| 15 | connection::Connection, | |
| 16 | render::{Render, StartVerificationContext, VerificationContext}, | |
| 17 | }; | |
| 18 | ||
| 19 | use super::{buffer::RoomBuffer, members::Members}; | |
| 20 | ||
| 21 | #[derive(Clone)] | |
| 22 | pub 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)] | |
| 31 | enum ActiveVerification { | |
| 32 | Request(VerificationRequest), | |
| 33 | Sas(SasVerification), | |
| 34 | } | |
| 35 | ||
| 36 | impl From<VerificationRequest> for ActiveVerification { | |
| 37 | fn from(v: VerificationRequest) -> Self { | |
| 38 | Self::Request(v) | |
| 39 | } | |
| 40 | } | |
| 41 | ||
| 42 | impl From<SasVerification> for ActiveVerification { | |
| 43 | fn from(v: SasVerification) -> Self { | |
| 44 | Self::Sas(v) | |
| 45 | } | |
| 46 | } | |
| 47 | ||
| 48 | impl 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::{ | ||
| 74 | 74 | api::client::session::login::v3::Response as LoginResponse, |
| 75 | 75 | events::{ |
| 76 | 76 | room::member::RoomMemberEventContent, AnySyncStateEvent, |
| 77 | AnySyncTimelineEvent, SyncStateEvent, | |
| 77 | AnySyncTimelineEvent, AnyToDeviceEvent, SyncStateEvent, | |
| 78 | 78 | }, |
| 79 | 79 | DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, |
| 80 | 80 | OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, |
| @@ -92,6 +92,7 @@ use crate::{ | ||
| 92 | 92 | config::ServerBuffer, |
| 93 | 93 | connection::{Connection, InteractiveAuthInfo}, |
| 94 | 94 | room::RoomHandle, |
| 95 | verification_buffer::VerificationBuffer, | |
| 95 | 96 | ConfigHandle, Servers, PLUGIN_NAME, |
| 96 | 97 | }; |
| 97 | 98 | |
| @@ -173,6 +174,7 @@ pub struct InnerServer { | ||
| 173 | 174 | login_state: Rc<RefCell<Option<LoginInfo>>>, |
| 174 | 175 | connection: Rc<RefCell<Option<Connection>>>, |
| 175 | 176 | server_buffer: Rc<RefCell<Option<BufferHandle>>>, |
| 177 | verification_buffers: Rc<RefCell<HashMap<String, VerificationBuffer>>>, | |
| 176 | 178 | } |
| 177 | 179 | |
| 178 | 180 | impl MatrixServer { |
| @@ -195,6 +197,7 @@ impl MatrixServer { | ||
| 195 | 197 | login_state: Rc::new(RefCell::new(None)), |
| 196 | 198 | connection: Rc::new(RefCell::new(None)), |
| 197 | 199 | server_buffer: Rc::new(RefCell::new(None)), |
| 200 | verification_buffers: Rc::new(RefCell::new(HashMap::new())), | |
| 198 | 201 | }; |
| 199 | 202 | |
| 200 | 203 | let server = server.into(); |
| @@ -451,6 +454,14 @@ impl InnerServer { | ||
| 451 | 454 | self.rooms.borrow().values().cloned().collect() |
| 452 | 455 | } |
| 453 | 456 | |
| 457 | pub fn verifications(&self) -> Vec<VerificationBuffer> { | |
| 458 | self.verification_buffers | |
| 459 | .borrow() | |
| 460 | .values() | |
| 461 | .cloned() | |
| 462 | .collect() | |
| 463 | } | |
| 464 | ||
| 454 | 465 | pub(crate) fn get_or_create_room(&self, room_id: &RoomId) -> RoomHandle { |
| 455 | 466 | if !self.rooms.borrow().contains_key(room_id) { |
| 456 | 467 | let homeserver = self |
| @@ -670,6 +681,115 @@ impl InnerServer { | ||
| 670 | 681 | self.connection.borrow().is_some() |
| 671 | 682 | } |
| 672 | 683 | |
| 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 | ||
| 673 | 793 | pub async fn receive_member( |
| 674 | 794 | &self, |
| 675 | 795 | room_id: OwnedRoomId, |
src/utils.rs +31 −2
| @@ -1,10 +1,10 @@ | ||
| 1 | 1 | use matrix_sdk::ruma::{ |
| 2 | 2 | events::{ |
| 3 | 3 | room::message::{ |
| 4 | Relation, RoomMessageEventContent, | |
| 4 | MessageType, Relation, RoomMessageEventContent, | |
| 5 | 5 | RoomMessageEventContentWithoutRelation, |
| 6 | 6 | }, |
| 7 | AnyMessageLikeEvent, AnySyncMessageLikeEvent, | |
| 7 | AnyMessageLikeEvent, AnySyncMessageLikeEvent, SyncMessageLikeEvent, | |
| 8 | 8 | }, |
| 9 | 9 | EventId, UserId, |
| 10 | 10 | }; |
| @@ -32,6 +32,35 @@ pub trait Edit { | ||
| 32 | 32 | ) -> Option<(&EventId, &RoomMessageEventContentWithoutRelation)>; |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | pub trait VerificationEvent { | |
| 36 | fn is_verification(&self) -> bool; | |
| 37 | } | |
| 38 | ||
| 39 | impl 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 | ||
| 35 | 64 | impl Edit for RoomMessageEventContent { |
| 36 | 65 | fn is_edit(&self) -> bool { |
| 37 | 66 | matches!(self.relates_to.as_ref(), Some(Relation::Replacement(_))) |
src/verification_buffer.rs added +370
| @@ -0,0 +1,370 @@ | ||
| 1 | use std::{cell::RefCell, convert::TryInto, rc::Rc}; | |
| 2 | ||
| 3 | use weechat::{ | |
| 4 | buffer::{ | |
| 5 | Buffer, BufferBuilderAsync, BufferCloseCallback, BufferHandle, | |
| 6 | BufferInputCallbackAsync, | |
| 7 | }, | |
| 8 | Weechat, | |
| 9 | }; | |
| 10 | ||
| 11 | use qrcode::render::unicode::Dense1x2; | |
| 12 | ||
| 13 | use 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 | ||
| 31 | use crate::{ | |
| 32 | connection::Connection, | |
| 33 | render::{ | |
| 34 | Render, RenderedContent, StartVerificationContext, VerificationContext, | |
| 35 | }, | |
| 36 | }; | |
| 37 | ||
| 38 | #[derive(Clone)] | |
| 39 | pub struct VerificationBuffer { | |
| 40 | inner: InnerVerificationBuffer, | |
| 41 | buffer: BufferHandle, | |
| 42 | } | |
| 43 | ||
| 44 | #[derive(Clone, Debug)] | |
| 45 | pub enum Verification { | |
| 46 | Request(VerificationRequest), | |
| 47 | Sas(SasVerification), | |
| 48 | Qr(QrVerification), | |
| 49 | } | |
| 50 | ||
| 51 | impl 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 | ||
| 63 | impl From<SasVerification> for Verification { | |
| 64 | fn from(s: SasVerification) -> Self { | |
| 65 | Self::Sas(s) | |
| 66 | } | |
| 67 | } | |
| 68 | ||
| 69 | impl From<VerificationRequest> for Verification { | |
| 70 | fn from(v: VerificationRequest) -> Self { | |
| 71 | Self::Request(v) | |
| 72 | } | |
| 73 | } | |
| 74 | ||
| 75 | impl From<QrVerification> for Verification { | |
| 76 | fn from(v: QrVerification) -> Self { | |
| 77 | Self::Qr(v) | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | impl 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)] | |
| 108 | struct InnerVerificationBuffer { | |
| 109 | verification: Rc<RefCell<Verification>>, | |
| 110 | connection: Rc<RefCell<Option<Connection>>>, | |
| 111 | } | |
| 112 | ||
| 113 | impl 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)] | |
| 205 | impl 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 | ||
| 218 | impl 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 | ||
| 227 | impl 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 | } | |