Commit b6f4b03c12
Unregistered key
Layout: unified · split
Cargo.lock +27 −17
| @@ -1019,15 +1019,6 @@ version = "0.4.0" | ||
| 1019 | 1019 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1020 | 1020 | checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" |
| 1021 | 1021 | |
| 1022 | [[package]] | |
| 1023 | name = "hermit-abi" | |
| 1024 | version = "0.1.19" | |
| 1025 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1026 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" | |
| 1027 | dependencies = [ | |
| 1028 | "libc", | |
| 1029 | ] | |
| 1030 | ||
| 1031 | 1022 | [[package]] |
| 1032 | 1023 | name = "hermit-abi" |
| 1033 | 1024 | version = "0.2.6" |
| @@ -1137,6 +1128,8 @@ dependencies = [ | ||
| 1137 | 1128 | "gethostname", |
| 1138 | 1129 | "lazy_static", |
| 1139 | 1130 | "matrix-sdk", |
| 1131 | "mime", | |
| 1132 | "mime_guess", | |
| 1140 | 1133 | "modalkit", |
| 1141 | 1134 | "regex", |
| 1142 | 1135 | "rpassword", |
| @@ -1271,7 +1264,7 @@ version = "0.4.1" | ||
| 1271 | 1264 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1272 | 1265 | checksum = "927609f78c2913a6f6ac3c27a4fe87f43e2a35367c0c4b0f8265e8f49a104330" |
| 1273 | 1266 | dependencies = [ |
| 1274 | "hermit-abi 0.2.6", | |
| 1267 | "hermit-abi", | |
| 1275 | 1268 | "io-lifetimes", |
| 1276 | 1269 | "rustix", |
| 1277 | 1270 | "windows-sys", |
| @@ -1580,6 +1573,16 @@ version = "0.3.16" | ||
| 1580 | 1573 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1581 | 1574 | checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" |
| 1582 | 1575 | |
| 1576 | [[package]] | |
| 1577 | name = "mime_guess" | |
| 1578 | version = "2.0.4" | |
| 1579 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1580 | checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" | |
| 1581 | dependencies = [ | |
| 1582 | "mime", | |
| 1583 | "unicase", | |
| 1584 | ] | |
| 1585 | ||
| 1583 | 1586 | [[package]] |
| 1584 | 1587 | name = "minimal-lexical" |
| 1585 | 1588 | version = "0.2.1" |
| @@ -1658,11 +1661,11 @@ dependencies = [ | ||
| 1658 | 1661 | |
| 1659 | 1662 | [[package]] |
| 1660 | 1663 | name = "num_cpus" |
| 1661 | version = "1.14.0" | |
| 1664 | version = "1.15.0" | |
| 1662 | 1665 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1663 | checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" | |
| 1666 | checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" | |
| 1664 | 1667 | dependencies = [ |
| 1665 | "hermit-abi 0.1.19", | |
| 1668 | "hermit-abi", | |
| 1666 | 1669 | "libc", |
| 1667 | 1670 | ] |
| 1668 | 1671 | |
| @@ -2589,9 +2592,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" | ||
| 2589 | 2592 | |
| 2590 | 2593 | [[package]] |
| 2591 | 2594 | name = "tokio" |
| 2592 | version = "1.23.0" | |
| 2595 | version = "1.24.1" | |
| 2593 | 2596 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2594 | checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46" | |
| 2597 | checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae" | |
| 2595 | 2598 | dependencies = [ |
| 2596 | 2599 | "autocfg", |
| 2597 | 2600 | "bytes", |
| @@ -2599,9 +2602,7 @@ dependencies = [ | ||
| 2599 | 2602 | "memchr", |
| 2600 | 2603 | "mio", |
| 2601 | 2604 | "num_cpus", |
| 2602 | "parking_lot 0.12.1", | |
| 2603 | 2605 | "pin-project-lite", |
| 2604 | "signal-hook-registry", | |
| 2605 | 2606 | "socket2", |
| 2606 | 2607 | "tokio-macros", |
| 2607 | 2608 | "windows-sys", |
| @@ -2752,6 +2753,15 @@ version = "1.16.0" | ||
| 2752 | 2753 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2753 | 2754 | checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" |
| 2754 | 2755 | |
| 2756 | [[package]] | |
| 2757 | name = "unicase" | |
| 2758 | version = "2.6.0" | |
| 2759 | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2760 | checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" | |
| 2761 | dependencies = [ | |
| 2762 | "version_check", | |
| 2763 | ] | |
| 2764 | ||
| 2755 | 2765 | [[package]] |
| 2756 | 2766 | name = "unicode-bidi" |
| 2757 | 2767 | version = "0.3.8" |
Cargo.toml +3 −1
| @@ -19,6 +19,8 @@ dirs = "4.0.0" | ||
| 19 | 19 | futures = "0.3.21" |
| 20 | 20 | gethostname = "0.4.1" |
| 21 | 21 | matrix-sdk = {version = "0.6", default-features = false, features = ["e2e-encryption", "sled", "rustls-tls"]} |
| 22 | mime = "^0.3.16" | |
| 23 | mime_guess = "^2.0.4" | |
| 22 | 24 | modalkit = "0.0.9" |
| 23 | 25 | regex = "^1.5" |
| 24 | 26 | rpassword = "^7.2" |
| @@ -26,7 +28,7 @@ serde = "^1.0" | ||
| 26 | 28 | serde_json = "^1.0" |
| 27 | 29 | sled = "0.34" |
| 28 | 30 | thiserror = "^1.0.37" |
| 29 | tokio = {version = "1.17.0", features = ["full"]} | |
| 31 | tokio = {version = "1.24.1", features = ["macros", "net", "rt-multi-thread", "sync", "time"]} | |
| 30 | 32 | tracing = "~0.1.36" |
| 31 | 33 | tracing-appender = "~0.2.2" |
| 32 | 34 | tracing-subscriber = "0.3.16" |
README.md +2 −2
| @@ -63,8 +63,8 @@ two other TUI clients and Element Web: | ||
| 63 | 63 | | Typing Notification | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | |
| 64 | 64 | | E2E | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | |
| 65 | 65 | | Replies | :x: ([#3]) | :heavy_check_mark: | :x: | :heavy_check_mark: | |
| 66 | | Attachment uploading | :x: ([#13]) | :x: | :heavy_check_mark: | :heavy_check_mark: | | |
| 67 | | Attachment downloading | :x: ([#13]) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | | |
| 66 | | Attachment uploading | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | | |
| 67 | | Attachment downloading | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | | |
| 68 | 68 | | Send stickers | :x: | :x: | :x: | :heavy_check_mark: | |
| 69 | 69 | | Send formatted messages (markdown) | :x: ([#10]) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | |
| 70 | 70 | | Rich Text Editor for formatted messages | :x: | :x: | :x: | :heavy_check_mark: | |
src/base.rs +48 −5
| @@ -59,6 +59,11 @@ pub enum VerifyAction { | ||
| 59 | 59 | Mismatch, |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | #[derive(Clone, Debug, Eq, PartialEq)] | |
| 63 | pub enum MessageAction { | |
| 64 | Download(Option<String>, bool), | |
| 65 | } | |
| 66 | ||
| 62 | 67 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 63 | 68 | pub enum SetRoomField { |
| 64 | 69 | Name(String), |
| @@ -77,26 +82,46 @@ impl From<SetRoomField> for RoomAction { | ||
| 77 | 82 | } |
| 78 | 83 | } |
| 79 | 84 | |
| 85 | #[derive(Clone, Debug, Eq, PartialEq)] | |
| 86 | pub enum SendAction { | |
| 87 | Submit, | |
| 88 | Upload(String), | |
| 89 | } | |
| 90 | ||
| 80 | 91 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 81 | 92 | pub enum IambAction { |
| 93 | Message(MessageAction), | |
| 82 | 94 | Room(RoomAction), |
| 95 | Send(SendAction), | |
| 83 | 96 | Verify(VerifyAction, String), |
| 84 | 97 | VerifyRequest(String), |
| 85 | SendMessage(OwnedRoomId, String), | |
| 86 | 98 | ToggleScrollbackFocus, |
| 87 | 99 | } |
| 88 | 100 | |
| 101 | impl From<MessageAction> for IambAction { | |
| 102 | fn from(act: MessageAction) -> Self { | |
| 103 | IambAction::Message(act) | |
| 104 | } | |
| 105 | } | |
| 106 | ||
| 89 | 107 | impl From<RoomAction> for IambAction { |
| 90 | 108 | fn from(act: RoomAction) -> Self { |
| 91 | 109 | IambAction::Room(act) |
| 92 | 110 | } |
| 93 | 111 | } |
| 94 | 112 | |
| 113 | impl From<SendAction> for IambAction { | |
| 114 | fn from(act: SendAction) -> Self { | |
| 115 | IambAction::Send(act) | |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 95 | 119 | impl ApplicationAction for IambAction { |
| 96 | 120 | fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus { |
| 97 | 121 | match self { |
| 122 | IambAction::Message(..) => SequenceStatus::Break, | |
| 98 | 123 | IambAction::Room(..) => SequenceStatus::Break, |
| 99 | IambAction::SendMessage(..) => SequenceStatus::Break, | |
| 124 | IambAction::Send(..) => SequenceStatus::Break, | |
| 100 | 125 | IambAction::ToggleScrollbackFocus => SequenceStatus::Break, |
| 101 | 126 | IambAction::Verify(..) => SequenceStatus::Break, |
| 102 | 127 | IambAction::VerifyRequest(..) => SequenceStatus::Break, |
| @@ -105,8 +130,9 @@ impl ApplicationAction for IambAction { | ||
| 105 | 130 | |
| 106 | 131 | fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus { |
| 107 | 132 | match self { |
| 133 | IambAction::Message(..) => SequenceStatus::Atom, | |
| 108 | 134 | IambAction::Room(..) => SequenceStatus::Atom, |
| 109 | IambAction::SendMessage(..) => SequenceStatus::Atom, | |
| 135 | IambAction::Send(..) => SequenceStatus::Atom, | |
| 110 | 136 | IambAction::ToggleScrollbackFocus => SequenceStatus::Atom, |
| 111 | 137 | IambAction::Verify(..) => SequenceStatus::Atom, |
| 112 | 138 | IambAction::VerifyRequest(..) => SequenceStatus::Atom, |
| @@ -115,8 +141,9 @@ impl ApplicationAction for IambAction { | ||
| 115 | 141 | |
| 116 | 142 | fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus { |
| 117 | 143 | match self { |
| 144 | IambAction::Message(..) => SequenceStatus::Ignore, | |
| 118 | 145 | IambAction::Room(..) => SequenceStatus::Ignore, |
| 119 | IambAction::SendMessage(..) => SequenceStatus::Ignore, | |
| 146 | IambAction::Send(..) => SequenceStatus::Ignore, | |
| 120 | 147 | IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore, |
| 121 | 148 | IambAction::Verify(..) => SequenceStatus::Ignore, |
| 122 | 149 | IambAction::VerifyRequest(..) => SequenceStatus::Ignore, |
| @@ -125,8 +152,9 @@ impl ApplicationAction for IambAction { | ||
| 125 | 152 | |
| 126 | 153 | fn is_switchable<C: EditContext>(&self, _: &C) -> bool { |
| 127 | 154 | match self { |
| 155 | IambAction::Message(..) => false, | |
| 128 | 156 | IambAction::Room(..) => false, |
| 129 | IambAction::SendMessage(..) => false, | |
| 157 | IambAction::Send(..) => false, | |
| 130 | 158 | IambAction::ToggleScrollbackFocus => false, |
| 131 | 159 | IambAction::Verify(..) => false, |
| 132 | 160 | IambAction::VerifyRequest(..) => false, |
| @@ -173,6 +201,21 @@ pub enum IambError { | ||
| 173 | 201 | #[error("Serialization/deserialization error: {0}")] |
| 174 | 202 | Serde(#[from] serde_json::Error), |
| 175 | 203 | |
| 204 | #[error("Selected message does not have any attachments")] | |
| 205 | NoAttachment, | |
| 206 | ||
| 207 | #[error("No message currently selected")] | |
| 208 | NoSelectedMessage, | |
| 209 | ||
| 210 | #[error("Current window is not a room or space")] | |
| 211 | NoSelectedRoomOrSpace, | |
| 212 | ||
| 213 | #[error("Current window is not a room")] | |
| 214 | NoSelectedRoom, | |
| 215 | ||
| 216 | #[error("You need to join the room before you can do that")] | |
| 217 | NotJoined, | |
| 218 | ||
| 176 | 219 | #[error("Unknown room identifier: {0}")] |
| 177 | 220 | UnknownRoom(OwnedRoomId), |
| 178 | 221 | |
src/commands.rs +32
| @@ -8,10 +8,12 @@ use modalkit::{ | ||
| 8 | 8 | use crate::base::{ |
| 9 | 9 | IambAction, |
| 10 | 10 | IambId, |
| 11 | MessageAction, | |
| 11 | 12 | ProgramCommand, |
| 12 | 13 | ProgramCommands, |
| 13 | 14 | ProgramContext, |
| 14 | 15 | RoomAction, |
| 16 | SendAction, | |
| 15 | 17 | SetRoomField, |
| 16 | 18 | VerifyAction, |
| 17 | 19 | }; |
| @@ -149,13 +151,43 @@ fn iamb_set(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult { | ||
| 149 | 151 | return Ok(step); |
| 150 | 152 | } |
| 151 | 153 | |
| 154 | fn iamb_upload(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult { | |
| 155 | let mut args = desc.arg.strings()?; | |
| 156 | ||
| 157 | if args.len() != 1 { | |
| 158 | return Result::Err(CommandError::InvalidArgument); | |
| 159 | } | |
| 160 | ||
| 161 | let sact = SendAction::Upload(args.remove(0)); | |
| 162 | let iact = IambAction::from(sact); | |
| 163 | let step = CommandStep::Continue(iact.into(), ctx.context.take()); | |
| 164 | ||
| 165 | return Ok(step); | |
| 166 | } | |
| 167 | ||
| 168 | fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult { | |
| 169 | let mut args = desc.arg.strings()?; | |
| 170 | ||
| 171 | if args.len() > 1 { | |
| 172 | return Result::Err(CommandError::InvalidArgument); | |
| 173 | } | |
| 174 | ||
| 175 | let mact = MessageAction::Download(args.pop(), desc.bang); | |
| 176 | let iact = IambAction::from(mact); | |
| 177 | let step = CommandStep::Continue(iact.into(), ctx.context.take()); | |
| 178 | ||
| 179 | return Ok(step); | |
| 180 | } | |
| 181 | ||
| 152 | 182 | fn add_iamb_commands(cmds: &mut ProgramCommands) { |
| 153 | 183 | cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms }); |
| 184 | cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download }); | |
| 154 | 185 | cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join }); |
| 155 | 186 | cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members }); |
| 156 | 187 | cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms }); |
| 157 | 188 | cmds.add_command(ProgramCommand { names: vec!["set".into()], f: iamb_set }); |
| 158 | 189 | cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces }); |
| 190 | cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload }); | |
| 159 | 191 | cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify }); |
| 160 | 192 | cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome }); |
| 161 | 193 | } |
src/config.rs +5 −1
| @@ -237,7 +237,11 @@ impl Directories { | ||
| 237 | 237 | fn values(self) -> DirectoryValues { |
| 238 | 238 | let cache = self |
| 239 | 239 | .cache |
| 240 | .or_else(dirs::cache_dir) | |
| 240 | .or_else(|| { | |
| 241 | let mut dir = dirs::cache_dir()?; | |
| 242 | dir.push("iamb"); | |
| 243 | dir.into() | |
| 244 | }) | |
| 241 | 245 | .expect("no dirs.cache value configured!"); |
| 242 | 246 | |
| 243 | 247 | let logs = self.logs.unwrap_or_else(|| { |
src/main.rs +55 −44
| @@ -9,6 +9,7 @@ use std::fs::{create_dir_all, File}; | ||
| 9 | 9 | use std::io::{stdout, BufReader, Stdout}; |
| 10 | 10 | use std::ops::DerefMut; |
| 11 | 11 | use std::process; |
| 12 | use std::sync::atomic::{AtomicUsize, Ordering}; | |
| 12 | 13 | use std::sync::Arc; |
| 13 | 14 | use std::time::Duration; |
| 14 | 15 | |
| @@ -63,7 +64,6 @@ use crate::{ | ||
| 63 | 64 | ProgramStore, |
| 64 | 65 | }, |
| 65 | 66 | config::{ApplicationSettings, Iamb}, |
| 66 | message::{Message, MessageContent, MessageTimeStamp}, | |
| 67 | 67 | windows::IambWindow, |
| 68 | 68 | worker::{ClientWorker, LoginStyle, Requester}, |
| 69 | 69 | }; |
| @@ -226,7 +226,7 @@ impl Application { | ||
| 226 | 226 | } |
| 227 | 227 | } |
| 228 | 228 | |
| 229 | fn action_run( | |
| 229 | async fn action_run( | |
| 230 | 230 | &mut self, |
| 231 | 231 | action: ProgramAction, |
| 232 | 232 | ctx: ProgramContext, |
| @@ -257,7 +257,7 @@ impl Application { | ||
| 257 | 257 | }, |
| 258 | 258 | |
| 259 | 259 | // Simple delegations. |
| 260 | Action::Application(act) => self.iamb_run(act, ctx, store)?, | |
| 260 | Action::Application(act) => self.iamb_run(act, ctx, store).await?, | |
| 261 | 261 | Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?, |
| 262 | 262 | Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?, |
| 263 | 263 | Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?, |
| @@ -314,7 +314,7 @@ impl Application { | ||
| 314 | 314 | return Ok(info); |
| 315 | 315 | } |
| 316 | 316 | |
| 317 | fn iamb_run( | |
| 317 | async fn iamb_run( | |
| 318 | 318 | &mut self, |
| 319 | 319 | action: IambAction, |
| 320 | 320 | ctx: ProgramContext, |
| @@ -327,24 +327,19 @@ impl Application { | ||
| 327 | 327 | None |
| 328 | 328 | }, |
| 329 | 329 | |
| 330 | IambAction::Message(act) => { | |
| 331 | self.screen.current_window_mut()?.message_command(act, ctx, store).await? | |
| 332 | }, | |
| 330 | 333 | IambAction::Room(act) => { |
| 331 | let acts = self.screen.current_window_mut()?.room_command(act, ctx, store)?; | |
| 334 | let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?; | |
| 332 | 335 | self.action_prepend(acts); |
| 333 | 336 | |
| 334 | 337 | None |
| 335 | 338 | }, |
| 336 | ||
| 337 | IambAction::SendMessage(room_id, msg) => { | |
| 338 | let (event_id, msg) = self.worker.send_message(room_id.clone(), msg)?; | |
| 339 | let user = store.application.settings.profile.user_id.clone(); | |
| 340 | let info = store.application.get_room_info(room_id); | |
| 341 | let key = (MessageTimeStamp::LocalEcho, event_id); | |
| 342 | let msg = MessageContent::Original(msg.into()); | |
| 343 | let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho); | |
| 344 | info.messages.insert(key, msg); | |
| 345 | ||
| 346 | None | |
| 339 | IambAction::Send(act) => { | |
| 340 | self.screen.current_window_mut()?.send_command(act, ctx, store).await? | |
| 347 | 341 | }, |
| 342 | ||
| 348 | 343 | IambAction::Verify(act, user_dev) => { |
| 349 | 344 | if let Some(sas) = store.application.verifications.get(&user_dev) { |
| 350 | 345 | self.worker.verify(act, sas.clone())? |
| @@ -378,7 +373,7 @@ impl Application { | ||
| 378 | 373 | let mut keyskip = false; |
| 379 | 374 | |
| 380 | 375 | while let Some((action, ctx)) = self.action_pop(keyskip) { |
| 381 | match self.action_run(action, ctx, locked.deref_mut()) { | |
| 376 | match self.action_run(action, ctx, locked.deref_mut()).await { | |
| 382 | 377 | Ok(None) => { |
| 383 | 378 | // Continue processing. |
| 384 | 379 | continue; |
| @@ -408,7 +403,7 @@ impl Application { | ||
| 408 | 403 | } |
| 409 | 404 | } |
| 410 | 405 | |
| 411 | fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> { | |
| 406 | async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> { | |
| 412 | 407 | println!("Logging in for {}...", settings.profile.user_id); |
| 413 | 408 | |
| 414 | 409 | if settings.session_json.is_file() { |
| @@ -447,38 +442,15 @@ fn print_exit<T: Display, N>(v: T) -> N { | ||
| 447 | 442 | process::exit(2); |
| 448 | 443 | } |
| 449 | 444 | |
| 450 | #[tokio::main] | |
| 451 | async fn main() -> IambResult<()> { | |
| 452 | // Parse command-line flags. | |
| 453 | let iamb = Iamb::parse(); | |
| 454 | ||
| 455 | // Load configuration and set up the Matrix SDK. | |
| 456 | let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit); | |
| 457 | ||
| 458 | // Set up the tracing subscriber so we can log client messages. | |
| 459 | let log_prefix = format!("iamb-log-{}", settings.profile_name); | |
| 460 | let log_dir = settings.dirs.logs.as_path(); | |
| 461 | ||
| 462 | create_dir_all(settings.matrix_dir.as_path())?; | |
| 463 | create_dir_all(log_dir)?; | |
| 464 | ||
| 465 | let appender = tracing_appender::rolling::daily(log_dir, log_prefix); | |
| 466 | let (appender, _) = tracing_appender::non_blocking(appender); | |
| 467 | ||
| 468 | let subscriber = FmtSubscriber::builder() | |
| 469 | .with_writer(appender) | |
| 470 | .with_max_level(Level::WARN) | |
| 471 | .finish(); | |
| 472 | tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); | |
| 473 | ||
| 445 | async fn run(settings: ApplicationSettings) -> IambResult<()> { | |
| 474 | 446 | // Set up the async worker thread and global store. |
| 475 | let worker = ClientWorker::spawn(settings.clone()); | |
| 447 | let worker = ClientWorker::spawn(settings.clone()).await; | |
| 476 | 448 | let store = ChatStore::new(worker.clone(), settings.clone()); |
| 477 | 449 | let store = Store::new(store); |
| 478 | 450 | let store = Arc::new(AsyncMutex::new(store)); |
| 479 | 451 | worker.init(store.clone()); |
| 480 | 452 | |
| 481 | login(worker, &settings).unwrap_or_else(print_exit); | |
| 453 | login(worker, &settings).await.unwrap_or_else(print_exit); | |
| 482 | 454 | |
| 483 | 455 | // Make sure panics clean up the terminal properly. |
| 484 | 456 | let orig_hook = std::panic::take_hook(); |
| @@ -495,5 +467,44 @@ async fn main() -> IambResult<()> { | ||
| 495 | 467 | // We can now run the application. |
| 496 | 468 | application.run().await?; |
| 497 | 469 | |
| 470 | Ok(()) | |
| 471 | } | |
| 472 | ||
| 473 | fn main() -> IambResult<()> { | |
| 474 | // Parse command-line flags. | |
| 475 | let iamb = Iamb::parse(); | |
| 476 | ||
| 477 | // Load configuration and set up the Matrix SDK. | |
| 478 | let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit); | |
| 479 | ||
| 480 | // Set up the tracing subscriber so we can log client messages. | |
| 481 | let log_prefix = format!("iamb-log-{}", settings.profile_name); | |
| 482 | let log_dir = settings.dirs.logs.as_path(); | |
| 483 | ||
| 484 | create_dir_all(settings.matrix_dir.as_path())?; | |
| 485 | create_dir_all(log_dir)?; | |
| 486 | ||
| 487 | let appender = tracing_appender::rolling::daily(log_dir, log_prefix); | |
| 488 | let (appender, guard) = tracing_appender::non_blocking(appender); | |
| 489 | ||
| 490 | let subscriber = FmtSubscriber::builder() | |
| 491 | .with_writer(appender) | |
| 492 | .with_max_level(Level::TRACE) | |
| 493 | .finish(); | |
| 494 | tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); | |
| 495 | ||
| 496 | let rt = tokio::runtime::Builder::new_multi_thread() | |
| 497 | .enable_all() | |
| 498 | .thread_name_fn(|| { | |
| 499 | static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); | |
| 500 | let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst); | |
| 501 | format!("iamb-worker-{}", id) | |
| 502 | }) | |
| 503 | .build() | |
| 504 | .unwrap(); | |
| 505 | ||
| 506 | rt.block_on(async move { run(settings).await })?; | |
| 507 | ||
| 508 | drop(guard); | |
| 498 | 509 | process::exit(0); |
| 499 | 510 | } |
src/message.rs +35 −39
| @@ -309,46 +309,41 @@ pub enum MessageContent { | ||
| 309 | 309 | Redacted, |
| 310 | 310 | } |
| 311 | 311 | |
| 312 | impl AsRef<str> for MessageContent { | |
| 313 | fn as_ref(&self) -> &str { | |
| 312 | impl MessageContent { | |
| 313 | pub fn show(&self) -> Cow<'_, str> { | |
| 314 | 314 | match self { |
| 315 | 315 | MessageContent::Original(ev) => { |
| 316 | match &ev.msgtype { | |
| 317 | MessageType::Text(content) => { | |
| 318 | return content.body.as_ref(); | |
| 319 | }, | |
| 320 | MessageType::Emote(content) => { | |
| 321 | return content.body.as_ref(); | |
| 322 | }, | |
| 323 | MessageType::Notice(content) => { | |
| 324 | return content.body.as_str(); | |
| 325 | }, | |
| 326 | MessageType::ServerNotice(_) => { | |
| 327 | // XXX: implement | |
| 316 | let s = match &ev.msgtype { | |
| 317 | MessageType::Text(content) => content.body.as_ref(), | |
| 318 | MessageType::Emote(content) => content.body.as_ref(), | |
| 319 | MessageType::Notice(content) => content.body.as_str(), | |
| 320 | MessageType::ServerNotice(content) => content.body.as_str(), | |
| 328 | 321 | |
| 329 | return "[server notice]"; | |
| 330 | }, | |
| 331 | 322 | MessageType::VerificationRequest(_) => { |
| 332 | 323 | // XXX: implement |
| 333 | 324 | |
| 334 | return "[verification request]"; | |
| 325 | return Cow::Owned("[verification request]".into()); | |
| 335 | 326 | }, |
| 336 | MessageType::Audio(..) => { | |
| 337 | return "[audio]"; | |
| 327 | MessageType::Audio(content) => { | |
| 328 | return Cow::Owned(format!("[Attached Audio: {}]", content.body)); | |
| 338 | 329 | }, |
| 339 | MessageType::File(..) => { | |
| 340 | return "[file]"; | |
| 330 | MessageType::File(content) => { | |
| 331 | return Cow::Owned(format!("[Attached File: {}]", content.body)); | |
| 341 | 332 | }, |
| 342 | MessageType::Image(..) => { | |
| 343 | return "[image]"; | |
| 333 | MessageType::Image(content) => { | |
| 334 | return Cow::Owned(format!("[Attached Image: {}]", content.body)); | |
| 344 | 335 | }, |
| 345 | MessageType::Video(..) => { | |
| 346 | return "[video]"; | |
| 336 | MessageType::Video(content) => { | |
| 337 | return Cow::Owned(format!("[Attached Video: {}]", content.body)); | |
| 347 | 338 | }, |
| 348 | _ => return "[unknown message type]", | |
| 349 | } | |
| 339 | _ => { | |
| 340 | return Cow::Owned(format!("[Unknown message type: {:?}]", ev.msgtype())); | |
| 341 | }, | |
| 342 | }; | |
| 343 | ||
| 344 | Cow::Borrowed(s) | |
| 350 | 345 | }, |
| 351 | MessageContent::Redacted => "[redacted]", | |
| 346 | MessageContent::Redacted => Cow::Borrowed("[redacted]"), | |
| 352 | 347 | } |
| 353 | 348 | } |
| 354 | 349 | } |
| @@ -358,11 +353,12 @@ pub struct Message { | ||
| 358 | 353 | pub content: MessageContent, |
| 359 | 354 | pub sender: OwnedUserId, |
| 360 | 355 | pub timestamp: MessageTimeStamp, |
| 356 | pub downloaded: bool, | |
| 361 | 357 | } |
| 362 | 358 | |
| 363 | 359 | impl Message { |
| 364 | 360 | pub fn new(content: MessageContent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self { |
| 365 | Message { content, sender, timestamp } | |
| 361 | Message { content, sender, timestamp, downloaded: false } | |
| 366 | 362 | } |
| 367 | 363 | |
| 368 | 364 | pub fn show( |
| @@ -373,7 +369,13 @@ impl Message { | ||
| 373 | 369 | settings: &ApplicationSettings, |
| 374 | 370 | ) -> Text { |
| 375 | 371 | let width = vwctx.get_width(); |
| 376 | let msg = self.as_ref(); | |
| 372 | let mut msg = self.content.show(); | |
| 373 | ||
| 374 | if self.downloaded { | |
| 375 | msg.to_mut().push_str(" \u{2705}"); | |
| 376 | } | |
| 377 | ||
| 378 | let msg = msg.as_ref(); | |
| 377 | 379 | |
| 378 | 380 | let mut lines = vec![]; |
| 379 | 381 | |
| @@ -391,7 +393,7 @@ impl Message { | ||
| 391 | 393 | let lw = width - USER_GUTTER - TIME_GUTTER; |
| 392 | 394 | |
| 393 | 395 | for (i, (line, w)) in wrap(msg, lw).enumerate() { |
| 394 | let line = Span::styled(line, style); | |
| 396 | let line = Span::styled(line.to_string(), style); | |
| 395 | 397 | let trailing = Span::styled(space(lw.saturating_sub(w)), style); |
| 396 | 398 | |
| 397 | 399 | if i == 0 { |
| @@ -412,7 +414,7 @@ impl Message { | ||
| 412 | 414 | let lw = width - USER_GUTTER; |
| 413 | 415 | |
| 414 | 416 | for (i, (line, w)) in wrap(msg, lw).enumerate() { |
| 415 | let line = Span::styled(line, style); | |
| 417 | let line = Span::styled(line.to_string(), style); | |
| 416 | 418 | let trailing = Span::styled(space(lw.saturating_sub(w)), style); |
| 417 | 419 | |
| 418 | 420 | let prefix = if i == 0 { |
| @@ -478,15 +480,9 @@ impl From<MessageEvent> for Message { | ||
| 478 | 480 | } |
| 479 | 481 | } |
| 480 | 482 | |
| 481 | impl AsRef<str> for Message { | |
| 482 | fn as_ref(&self) -> &str { | |
| 483 | self.content.as_ref() | |
| 484 | } | |
| 485 | } | |
| 486 | ||
| 487 | 483 | impl ToString for Message { |
| 488 | 484 | fn to_string(&self) -> String { |
| 489 | self.as_ref().to_string() | |
| 485 | self.content.show().into_owned() | |
| 490 | 486 | } |
| 491 | 487 | } |
| 492 | 488 | |
src/tests.rs +6 −4
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | use std::collections::{BTreeMap, HashMap}; |
| 2 | 2 | use std::path::PathBuf; |
| 3 | use std::sync::mpsc::sync_channel; | |
| 4 | 3 | |
| 5 | 4 | use matrix_sdk::ruma::{ |
| 6 | 5 | event_id, |
| @@ -16,6 +15,7 @@ use matrix_sdk::ruma::{ | ||
| 16 | 15 | |
| 17 | 16 | use lazy_static::lazy_static; |
| 18 | 17 | use modalkit::tui::style::Color; |
| 18 | use tokio::sync::mpsc::unbounded_channel; | |
| 19 | 19 | use url::Url; |
| 20 | 20 | |
| 21 | 21 | use crate::{ |
| @@ -154,9 +154,11 @@ pub fn mock_settings() -> ApplicationSettings { | ||
| 154 | 154 | } |
| 155 | 155 | } |
| 156 | 156 | |
| 157 | pub fn mock_store() -> ProgramStore { | |
| 158 | let (tx, _) = sync_channel(5); | |
| 159 | let worker = Requester { tx }; | |
| 157 | pub async fn mock_store() -> ProgramStore { | |
| 158 | let (tx, _) = unbounded_channel(); | |
| 159 | let homeserver = Url::parse("https://localhost").unwrap(); | |
| 160 | let client = matrix_sdk::Client::new(homeserver).await.unwrap(); | |
| 161 | let worker = Requester { tx, client }; | |
| 160 | 162 | |
| 161 | 163 | let mut store = ChatStore::new(worker, mock_settings()); |
| 162 | 164 | let room_id = TEST_ROOM1_ID.clone(); |
src/windows/mod.rs +92 −7
| @@ -54,13 +54,16 @@ use modalkit::{ | ||
| 54 | 54 | use crate::base::{ |
| 55 | 55 | ChatStore, |
| 56 | 56 | IambBufferId, |
| 57 | IambError, | |
| 57 | 58 | IambId, |
| 58 | 59 | IambInfo, |
| 59 | 60 | IambResult, |
| 61 | MessageAction, | |
| 60 | 62 | ProgramAction, |
| 61 | 63 | ProgramContext, |
| 62 | 64 | ProgramStore, |
| 63 | 65 | RoomAction, |
| 66 | SendAction, | |
| 64 | 67 | }; |
| 65 | 68 | |
| 66 | 69 | use self::{room::RoomState, welcome::WelcomeState}; |
| @@ -102,6 +105,20 @@ fn selected_text(s: &str, selected: bool) -> Text { | ||
| 102 | 105 | Text::from(selected_span(s, selected)) |
| 103 | 106 | } |
| 104 | 107 | |
| 108 | fn room_cmp(a: &MatrixRoom, b: &MatrixRoom) -> Ordering { | |
| 109 | let ca1 = a.canonical_alias(); | |
| 110 | let ca2 = b.canonical_alias(); | |
| 111 | ||
| 112 | let ord = match (ca1, ca2) { | |
| 113 | (None, None) => Ordering::Equal, | |
| 114 | (None, Some(_)) => Ordering::Greater, | |
| 115 | (Some(_), None) => Ordering::Less, | |
| 116 | (Some(ca1), Some(ca2)) => ca1.cmp(&ca2), | |
| 117 | }; | |
| 118 | ||
| 119 | ord.then_with(|| a.room_id().cmp(b.room_id())) | |
| 120 | } | |
| 121 | ||
| 105 | 122 | #[inline] |
| 106 | 123 | fn room_prompt( |
| 107 | 124 | room_id: &RoomId, |
| @@ -165,19 +182,42 @@ impl IambWindow { | ||
| 165 | 182 | } |
| 166 | 183 | } |
| 167 | 184 | |
| 168 | pub fn room_command( | |
| 185 | pub async fn message_command( | |
| 186 | &mut self, | |
| 187 | act: MessageAction, | |
| 188 | ctx: ProgramContext, | |
| 189 | store: &mut ProgramStore, | |
| 190 | ) -> IambResult<EditInfo> { | |
| 191 | if let IambWindow::Room(w) = self { | |
| 192 | w.message_command(act, ctx, store).await | |
| 193 | } else { | |
| 194 | return Err(IambError::NoSelectedRoom.into()); | |
| 195 | } | |
| 196 | } | |
| 197 | ||
| 198 | pub async fn room_command( | |
| 169 | 199 | &mut self, |
| 170 | 200 | act: RoomAction, |
| 171 | 201 | ctx: ProgramContext, |
| 172 | 202 | store: &mut ProgramStore, |
| 173 | 203 | ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> { |
| 174 | 204 | if let IambWindow::Room(w) = self { |
| 175 | w.room_command(act, ctx, store) | |
| 205 | w.room_command(act, ctx, store).await | |
| 176 | 206 | } else { |
| 177 | let msg = "No room currently focused!"; | |
| 178 | let err = UIError::Failure(msg.into()); | |
| 207 | return Err(IambError::NoSelectedRoomOrSpace.into()); | |
| 208 | } | |
| 209 | } | |
| 179 | 210 | |
| 180 | return Err(err); | |
| 211 | pub async fn send_command( | |
| 212 | &mut self, | |
| 213 | act: SendAction, | |
| 214 | ctx: ProgramContext, | |
| 215 | store: &mut ProgramStore, | |
| 216 | ) -> IambResult<EditInfo> { | |
| 217 | if let IambWindow::Room(w) = self { | |
| 218 | w.send_command(act, ctx, store).await | |
| 219 | } else { | |
| 220 | return Err(IambError::NoSelectedRoom.into()); | |
| 181 | 221 | } |
| 182 | 222 | } |
| 183 | 223 | } |
| @@ -304,8 +344,13 @@ impl WindowOps<IambInfo> for IambWindow { | ||
| 304 | 344 | }, |
| 305 | 345 | IambWindow::RoomList(state) => { |
| 306 | 346 | let joined = store.application.worker.joined_rooms(); |
| 307 | let items = joined.into_iter().map(|(id, name)| RoomItem::new(id, name, store)); | |
| 308 | state.set(items.collect()); | |
| 347 | let mut items = joined | |
| 348 | .into_iter() | |
| 349 | .map(|(id, name)| RoomItem::new(id, name, store)) | |
| 350 | .collect::<Vec<_>>(); | |
| 351 | items.sort(); | |
| 352 | ||
| 353 | state.set(items); | |
| 309 | 354 | |
| 310 | 355 | List::new(store) |
| 311 | 356 | .empty_message("You haven't joined any rooms yet") |
| @@ -515,6 +560,26 @@ impl RoomItem { | ||
| 515 | 560 | } |
| 516 | 561 | } |
| 517 | 562 | |
| 563 | impl PartialEq for RoomItem { | |
| 564 | fn eq(&self, other: &Self) -> bool { | |
| 565 | self.room.room_id() == other.room.room_id() | |
| 566 | } | |
| 567 | } | |
| 568 | ||
| 569 | impl Eq for RoomItem {} | |
| 570 | ||
| 571 | impl Ord for RoomItem { | |
| 572 | fn cmp(&self, other: &Self) -> Ordering { | |
| 573 | room_cmp(&self.room, &other.room) | |
| 574 | } | |
| 575 | } | |
| 576 | ||
| 577 | impl PartialOrd for RoomItem { | |
| 578 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
| 579 | self.cmp(other).into() | |
| 580 | } | |
| 581 | } | |
| 582 | ||
| 518 | 583 | impl ToString for RoomItem { |
| 519 | 584 | fn to_string(&self) -> String { |
| 520 | 585 | return self.name.clone(); |
| @@ -601,6 +666,26 @@ impl SpaceItem { | ||
| 601 | 666 | } |
| 602 | 667 | } |
| 603 | 668 | |
| 669 | impl PartialEq for SpaceItem { | |
| 670 | fn eq(&self, other: &Self) -> bool { | |
| 671 | self.room.room_id() == other.room.room_id() | |
| 672 | } | |
| 673 | } | |
| 674 | ||
| 675 | impl Eq for SpaceItem {} | |
| 676 | ||
| 677 | impl Ord for SpaceItem { | |
| 678 | fn cmp(&self, other: &Self) -> Ordering { | |
| 679 | room_cmp(&self.room, &other.room) | |
| 680 | } | |
| 681 | } | |
| 682 | ||
| 683 | impl PartialOrd for SpaceItem { | |
| 684 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
| 685 | self.cmp(other).into() | |
| 686 | } | |
| 687 | } | |
| 688 | ||
| 604 | 689 | impl ToString for SpaceItem { |
| 605 | 690 | fn to_string(&self) -> String { |
| 606 | 691 | return self.room.room_id().to_string(); |
src/windows/room/chat.rs +185 −13
| @@ -1,11 +1,21 @@ | ||
| 1 | use std::borrow::Cow; | |
| 2 | use std::ffi::OsStr; | |
| 3 | use std::fs; | |
| 4 | use std::path::{Path, PathBuf}; | |
| 5 | ||
| 1 | 6 | use matrix_sdk::{ |
| 7 | attachment::AttachmentConfig, | |
| 8 | media::{MediaFormat, MediaRequest}, | |
| 2 | 9 | room::Room as MatrixRoom, |
| 3 | ruma::{OwnedRoomId, RoomId}, | |
| 10 | ruma::{ | |
| 11 | events::room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, | |
| 12 | OwnedRoomId, | |
| 13 | RoomId, | |
| 14 | }, | |
| 4 | 15 | }; |
| 5 | 16 | |
| 6 | use modalkit::tui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget}; | |
| 7 | ||
| 8 | 17 | use modalkit::{ |
| 18 | tui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget}, | |
| 9 | 19 | widgets::textbox::{TextBox, TextBoxState}, |
| 10 | 20 | widgets::TerminalCursor, |
| 11 | 21 | widgets::{PromptActions, WindowOps}, |
| @@ -18,10 +28,12 @@ use modalkit::editing::{ | ||
| 18 | 28 | EditResult, |
| 19 | 29 | Editable, |
| 20 | 30 | EditorAction, |
| 31 | InfoMessage, | |
| 21 | 32 | Jumpable, |
| 22 | 33 | PromptAction, |
| 23 | 34 | Promptable, |
| 24 | 35 | Scrollable, |
| 36 | UIError, | |
| 25 | 37 | }, |
| 26 | 38 | base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle}, |
| 27 | 39 | context::Resolve, |
| @@ -32,14 +44,19 @@ use modalkit::editing::{ | ||
| 32 | 44 | use crate::base::{ |
| 33 | 45 | IambAction, |
| 34 | 46 | IambBufferId, |
| 47 | IambError, | |
| 35 | 48 | IambInfo, |
| 36 | 49 | IambResult, |
| 50 | MessageAction, | |
| 37 | 51 | ProgramAction, |
| 38 | 52 | ProgramContext, |
| 39 | 53 | ProgramStore, |
| 40 | 54 | RoomFocus, |
| 55 | SendAction, | |
| 41 | 56 | }; |
| 42 | 57 | |
| 58 | use crate::message::{Message, MessageContent, MessageTimeStamp}; | |
| 59 | ||
| 43 | 60 | use super::scrollback::{Scrollback, ScrollbackState}; |
| 44 | 61 | |
| 45 | 62 | pub struct ChatState { |
| @@ -75,6 +92,169 @@ impl ChatState { | ||
| 75 | 92 | } |
| 76 | 93 | } |
| 77 | 94 | |
| 95 | pub async fn message_command( | |
| 96 | &mut self, | |
| 97 | act: MessageAction, | |
| 98 | _: ProgramContext, | |
| 99 | store: &mut ProgramStore, | |
| 100 | ) -> IambResult<EditInfo> { | |
| 101 | let client = &store.application.worker.client; | |
| 102 | ||
| 103 | let settings = &store.application.settings; | |
| 104 | let info = store.application.rooms.entry(self.room_id.clone()).or_default(); | |
| 105 | ||
| 106 | let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?; | |
| 107 | ||
| 108 | match act { | |
| 109 | MessageAction::Download(filename, force) => { | |
| 110 | if let MessageContent::Original(ev) = &msg.content { | |
| 111 | let media = client.media(); | |
| 112 | ||
| 113 | let mut filename = match filename { | |
| 114 | Some(f) => PathBuf::from(f), | |
| 115 | None => settings.dirs.downloads.clone(), | |
| 116 | }; | |
| 117 | ||
| 118 | let source = match &ev.msgtype { | |
| 119 | MessageType::Audio(c) => { | |
| 120 | if filename.is_dir() { | |
| 121 | filename.push(c.body.as_str()); | |
| 122 | } | |
| 123 | ||
| 124 | c.source.clone() | |
| 125 | }, | |
| 126 | MessageType::File(c) => { | |
| 127 | if filename.is_dir() { | |
| 128 | if let Some(name) = &c.filename { | |
| 129 | filename.push(name); | |
| 130 | } else { | |
| 131 | filename.push(c.body.as_str()); | |
| 132 | } | |
| 133 | } | |
| 134 | ||
| 135 | c.source.clone() | |
| 136 | }, | |
| 137 | MessageType::Image(c) => { | |
| 138 | if filename.is_dir() { | |
| 139 | filename.push(c.body.as_str()); | |
| 140 | } | |
| 141 | ||
| 142 | c.source.clone() | |
| 143 | }, | |
| 144 | MessageType::Video(c) => { | |
| 145 | if filename.is_dir() { | |
| 146 | filename.push(c.body.as_str()); | |
| 147 | } | |
| 148 | ||
| 149 | c.source.clone() | |
| 150 | }, | |
| 151 | _ => { | |
| 152 | return Err(IambError::NoAttachment.into()); | |
| 153 | }, | |
| 154 | }; | |
| 155 | ||
| 156 | if !force && filename.exists() { | |
| 157 | let msg = format!( | |
| 158 | "The file {} already exists; use :download! to overwrite it.", | |
| 159 | filename.display() | |
| 160 | ); | |
| 161 | let err = UIError::Failure(msg); | |
| 162 | ||
| 163 | return Err(err); | |
| 164 | } | |
| 165 | ||
| 166 | let req = MediaRequest { source, format: MediaFormat::File }; | |
| 167 | ||
| 168 | let bytes = | |
| 169 | media.get_media_content(&req, true).await.map_err(IambError::from)?; | |
| 170 | ||
| 171 | fs::write(filename.as_path(), bytes.as_slice())?; | |
| 172 | ||
| 173 | msg.downloaded = true; | |
| 174 | ||
| 175 | let info = InfoMessage::from(format!( | |
| 176 | "Attachment downloaded to {}", | |
| 177 | filename.display() | |
| 178 | )); | |
| 179 | ||
| 180 | return Ok(info.into()); | |
| 181 | } | |
| 182 | ||
| 183 | Err(IambError::NoAttachment.into()) | |
| 184 | }, | |
| 185 | } | |
| 186 | } | |
| 187 | ||
| 188 | pub async fn send_command( | |
| 189 | &mut self, | |
| 190 | act: SendAction, | |
| 191 | _: ProgramContext, | |
| 192 | store: &mut ProgramStore, | |
| 193 | ) -> IambResult<EditInfo> { | |
| 194 | let room = store | |
| 195 | .application | |
| 196 | .worker | |
| 197 | .client | |
| 198 | .get_joined_room(self.id()) | |
| 199 | .ok_or(IambError::NotJoined)?; | |
| 200 | ||
| 201 | let (event_id, msg) = match act { | |
| 202 | SendAction::Submit => { | |
| 203 | let msg = self.tbox.get_text(); | |
| 204 | ||
| 205 | if msg.is_empty() { | |
| 206 | return Ok(None); | |
| 207 | } | |
| 208 | ||
| 209 | let msg = TextMessageEventContent::plain(msg); | |
| 210 | let msg = MessageType::Text(msg); | |
| 211 | let msg = RoomMessageEventContent::new(msg); | |
| 212 | ||
| 213 | // XXX: second parameter can be a locally unique transaction id. | |
| 214 | // Useful for doing retries. | |
| 215 | let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?; | |
| 216 | let event_id = resp.event_id; | |
| 217 | ||
| 218 | // Clear the TextBoxState contents now that the message is sent. | |
| 219 | self.tbox.reset(); | |
| 220 | ||
| 221 | (event_id, msg) | |
| 222 | }, | |
| 223 | SendAction::Upload(file) => { | |
| 224 | let path = Path::new(file.as_str()); | |
| 225 | let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM); | |
| 226 | ||
| 227 | let bytes = fs::read(path)?; | |
| 228 | let name = path | |
| 229 | .file_name() | |
| 230 | .map(OsStr::to_string_lossy) | |
| 231 | .unwrap_or_else(|| Cow::from("Attachment")); | |
| 232 | let config = AttachmentConfig::new(); | |
| 233 | ||
| 234 | let resp = room | |
| 235 | .send_attachment(name.as_ref(), &mime, bytes.as_ref(), config) | |
| 236 | .await | |
| 237 | .map_err(IambError::from)?; | |
| 238 | ||
| 239 | // Mock up the local echo message for the scrollback. | |
| 240 | let msg = TextMessageEventContent::plain(format!("[Attached File: {}]", name)); | |
| 241 | let msg = MessageType::Text(msg); | |
| 242 | let msg = RoomMessageEventContent::new(msg); | |
| 243 | ||
| 244 | (resp.event_id, msg) | |
| 245 | }, | |
| 246 | }; | |
| 247 | ||
| 248 | let user = store.application.settings.profile.user_id.clone(); | |
| 249 | let info = store.application.get_room_info(self.id().to_owned()); | |
| 250 | let key = (MessageTimeStamp::LocalEcho, event_id); | |
| 251 | let msg = MessageContent::Original(msg.into()); | |
| 252 | let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho); | |
| 253 | info.messages.insert(key, msg); | |
| 254 | ||
| 255 | Ok(None) | |
| 256 | } | |
| 257 | ||
| 78 | 258 | pub fn focus_toggle(&mut self) { |
| 79 | 259 | self.focus = match self.focus { |
| 80 | 260 | RoomFocus::Scrollback => RoomFocus::MessageBar, |
| @@ -229,17 +409,9 @@ impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState { | ||
| 229 | 409 | ctx: &ProgramContext, |
| 230 | 410 | _: &mut ProgramStore, |
| 231 | 411 | ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> { |
| 232 | let txt = self.tbox.reset_text(); | |
| 233 | ||
| 234 | let act = if txt.is_empty() { | |
| 235 | vec![] | |
| 236 | } else { | |
| 237 | let act = IambAction::SendMessage(self.room_id.clone(), txt).into(); | |
| 238 | ||
| 239 | vec![(act, ctx.clone())] | |
| 240 | }; | |
| 412 | let act = SendAction::Submit; | |
| 241 | 413 | |
| 242 | Ok(act) | |
| 414 | Ok(vec![(IambAction::from(act).into(), ctx.clone())]) | |
| 243 | 415 | } |
| 244 | 416 | |
| 245 | 417 | fn abort( |
src/windows/room/mod.rs +29 −4
| @@ -1,6 +1,4 @@ | ||
| 1 | use matrix_sdk::room::Room as MatrixRoom; | |
| 2 | use matrix_sdk::ruma::RoomId; | |
| 3 | use matrix_sdk::DisplayName; | |
| 1 | use matrix_sdk::{room::Room as MatrixRoom, ruma::RoomId, DisplayName}; | |
| 4 | 2 | |
| 5 | 3 | use modalkit::tui::{ |
| 6 | 4 | buffer::Buffer, |
| @@ -37,13 +35,16 @@ use modalkit::{ | ||
| 37 | 35 | }; |
| 38 | 36 | |
| 39 | 37 | use crate::base::{ |
| 38 | IambError, | |
| 40 | 39 | IambId, |
| 41 | 40 | IambInfo, |
| 42 | 41 | IambResult, |
| 42 | MessageAction, | |
| 43 | 43 | ProgramAction, |
| 44 | 44 | ProgramContext, |
| 45 | 45 | ProgramStore, |
| 46 | 46 | RoomAction, |
| 47 | SendAction, | |
| 47 | 48 | }; |
| 48 | 49 | |
| 49 | 50 | use self::chat::ChatState; |
| @@ -92,7 +93,31 @@ impl RoomState { | ||
| 92 | 93 | } |
| 93 | 94 | } |
| 94 | 95 | |
| 95 | pub fn room_command( | |
| 96 | pub async fn message_command( | |
| 97 | &mut self, | |
| 98 | act: MessageAction, | |
| 99 | ctx: ProgramContext, | |
| 100 | store: &mut ProgramStore, | |
| 101 | ) -> IambResult<EditInfo> { | |
| 102 | match self { | |
| 103 | RoomState::Chat(chat) => chat.message_command(act, ctx, store).await, | |
| 104 | RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()), | |
| 105 | } | |
| 106 | } | |
| 107 | ||
| 108 | pub async fn send_command( | |
| 109 | &mut self, | |
| 110 | act: SendAction, | |
| 111 | ctx: ProgramContext, | |
| 112 | store: &mut ProgramStore, | |
| 113 | ) -> IambResult<EditInfo> { | |
| 114 | match self { | |
| 115 | RoomState::Chat(chat) => chat.send_command(act, ctx, store).await, | |
| 116 | RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()), | |
| 117 | } | |
| 118 | } | |
| 119 | ||
| 120 | pub async fn room_command( | |
| 96 | 121 | &mut self, |
| 97 | 122 | act: RoomAction, |
| 98 | 123 | _: ProgramContext, |
src/windows/room/scrollback.rs +32 −20
| @@ -126,6 +126,14 @@ impl ScrollbackState { | ||
| 126 | 126 | self.viewctx.dimensions = (area.width as usize, area.height as usize); |
| 127 | 127 | } |
| 128 | 128 | |
| 129 | pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> { | |
| 130 | if let Some(k) = &self.cursor.timestamp { | |
| 131 | info.messages.get_mut(k) | |
| 132 | } else { | |
| 133 | info.messages.last_entry().map(|o| o.into_mut()) | |
| 134 | } | |
| 135 | } | |
| 136 | ||
| 129 | 137 | pub fn messages<'a>( |
| 130 | 138 | &self, |
| 131 | 139 | range: EditRange<MessageCursor>, |
| @@ -389,7 +397,7 @@ impl ScrollbackState { | ||
| 389 | 397 | continue; |
| 390 | 398 | } |
| 391 | 399 | |
| 392 | if needle.is_match(msg.as_ref()) { | |
| 400 | if needle.is_match(msg.content.show().as_ref()) { | |
| 393 | 401 | mc = MessageCursor::from(key.clone()).into(); |
| 394 | 402 | count -= 1; |
| 395 | 403 | } |
| @@ -413,7 +421,7 @@ impl ScrollbackState { | ||
| 413 | 421 | break; |
| 414 | 422 | } |
| 415 | 423 | |
| 416 | if needle.is_match(msg.as_ref()) { | |
| 424 | if needle.is_match(msg.content.show().as_ref()) { | |
| 417 | 425 | mc = MessageCursor::from(key.clone()).into(); |
| 418 | 426 | count -= 1; |
| 419 | 427 | } |
| @@ -659,7 +667,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | ||
| 659 | 667 | let mut yanked = EditRope::from(""); |
| 660 | 668 | |
| 661 | 669 | for (_, msg) in self.messages(range, info) { |
| 662 | yanked += EditRope::from(msg.as_ref()); | |
| 670 | yanked += EditRope::from(msg.content.show().into_owned()); | |
| 663 | 671 | yanked += EditRope::from('\n'); |
| 664 | 672 | } |
| 665 | 673 | |
| @@ -1159,12 +1167,14 @@ impl<'a> StatefulWidget for Scrollback<'a> { | ||
| 1159 | 1167 | }; |
| 1160 | 1168 | |
| 1161 | 1169 | let corner = &state.viewctx.corner; |
| 1162 | let corner_key = match (&corner.timestamp, &cursor.timestamp) { | |
| 1163 | (_, None) => nth_key_before(cursor_key.clone(), height, info), | |
| 1164 | (None, _) => nth_key_before(cursor_key.clone(), height, info), | |
| 1165 | (Some(k), _) => k.clone(), | |
| 1170 | let corner_key = if let Some(k) = &corner.timestamp { | |
| 1171 | k.clone() | |
| 1172 | } else { | |
| 1173 | nth_key_before(cursor_key.clone(), height, info) | |
| 1166 | 1174 | }; |
| 1167 | 1175 | |
| 1176 | let full = cursor.timestamp.is_none(); | |
| 1177 | ||
| 1168 | 1178 | let mut lines = vec![]; |
| 1169 | 1179 | let mut sawit = false; |
| 1170 | 1180 | let mut prev = None; |
| @@ -1175,8 +1185,10 @@ impl<'a> StatefulWidget for Scrollback<'a> { | ||
| 1175 | 1185 | |
| 1176 | 1186 | prev = Some(item); |
| 1177 | 1187 | |
| 1188 | let incomplete_ok = !full || !sel; | |
| 1189 | ||
| 1178 | 1190 | for (row, line) in txt.lines.into_iter().enumerate() { |
| 1179 | if sawit && lines.len() >= height { | |
| 1191 | if sawit && lines.len() >= height && incomplete_ok { | |
| 1180 | 1192 | // Check whether we've seen the first line of the |
| 1181 | 1193 | // selected message and can fill the screen. |
| 1182 | 1194 | break; |
| @@ -1224,10 +1236,10 @@ mod tests { | ||
| 1224 | 1236 | use super::*; |
| 1225 | 1237 | use crate::tests::*; |
| 1226 | 1238 | |
| 1227 | #[test] | |
| 1228 | fn test_search_messages() { | |
| 1239 | #[tokio::test] | |
| 1240 | async fn test_search_messages() { | |
| 1229 | 1241 | let room_id = TEST_ROOM1_ID.clone(); |
| 1230 | let mut store = mock_store(); | |
| 1242 | let mut store = mock_store().await; | |
| 1231 | 1243 | let mut scrollback = ScrollbackState::new(room_id.clone()); |
| 1232 | 1244 | let ctx = ProgramContext::default(); |
| 1233 | 1245 | |
| @@ -1268,9 +1280,9 @@ mod tests { | ||
| 1268 | 1280 | assert_eq!(scrollback.cursor, MSG1_KEY.clone().into()); |
| 1269 | 1281 | } |
| 1270 | 1282 | |
| 1271 | #[test] | |
| 1272 | fn test_movement() { | |
| 1273 | let mut store = mock_store(); | |
| 1283 | #[tokio::test] | |
| 1284 | async fn test_movement() { | |
| 1285 | let mut store = mock_store().await; | |
| 1274 | 1286 | let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone()); |
| 1275 | 1287 | let ctx = ProgramContext::default(); |
| 1276 | 1288 | |
| @@ -1302,9 +1314,9 @@ mod tests { | ||
| 1302 | 1314 | assert_eq!(scrollback.cursor, MSG1_KEY.clone().into()); |
| 1303 | 1315 | } |
| 1304 | 1316 | |
| 1305 | #[test] | |
| 1306 | fn test_dirscroll() { | |
| 1307 | let mut store = mock_store(); | |
| 1317 | #[tokio::test] | |
| 1318 | async fn test_dirscroll() { | |
| 1319 | let mut store = mock_store().await; | |
| 1308 | 1320 | let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone()); |
| 1309 | 1321 | let ctx = ProgramContext::default(); |
| 1310 | 1322 | |
| @@ -1436,9 +1448,9 @@ mod tests { | ||
| 1436 | 1448 | assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 4)); |
| 1437 | 1449 | } |
| 1438 | 1450 | |
| 1439 | #[test] | |
| 1440 | fn test_cursorpos() { | |
| 1441 | let mut store = mock_store(); | |
| 1451 | #[tokio::test] | |
| 1452 | async fn test_cursorpos() { | |
| 1453 | let mut store = mock_store().await; | |
| 1442 | 1454 | let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone()); |
| 1443 | 1455 | let ctx = ProgramContext::default(); |
| 1444 | 1456 | |
src/worker.rs +133 −90
| @@ -1,12 +1,14 @@ | ||
| 1 | 1 | use std::convert::TryFrom; |
| 2 | use std::fmt::{Debug, Formatter}; | |
| 2 | 3 | use std::fs::File; |
| 3 | 4 | use std::io::BufWriter; |
| 4 | 5 | use std::str::FromStr; |
| 5 | use std::sync::mpsc::{sync_channel, Receiver, RecvTimeoutError, SyncSender}; | |
| 6 | use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; | |
| 6 | 7 | use std::sync::Arc; |
| 7 | 8 | use std::time::Duration; |
| 8 | 9 | |
| 9 | 10 | use gethostname::gethostname; |
| 11 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; | |
| 10 | 12 | use tokio::task::JoinHandle; |
| 11 | 13 | use tracing::error; |
| 12 | 14 | |
| @@ -31,7 +33,7 @@ use matrix_sdk::{ | ||
| 31 | 33 | VerificationMethod, |
| 32 | 34 | }, |
| 33 | 35 | room::{ |
| 34 | message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, | |
| 36 | message::{MessageType, RoomMessageEventContent}, | |
| 35 | 37 | name::RoomNameEventContent, |
| 36 | 38 | topic::RoomTopicEventContent, |
| 37 | 39 | }, |
| @@ -41,7 +43,6 @@ use matrix_sdk::{ | ||
| 41 | 43 | SyncMessageLikeEvent, |
| 42 | 44 | SyncStateEvent, |
| 43 | 45 | }, |
| 44 | OwnedEventId, | |
| 45 | 46 | OwnedRoomId, |
| 46 | 47 | OwnedRoomOrAliasId, |
| 47 | 48 | OwnedUserId, |
| @@ -67,6 +68,7 @@ fn initial_devname() -> String { | ||
| 67 | 68 | format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy()) |
| 68 | 69 | } |
| 69 | 70 | |
| 71 | #[derive(Debug)] | |
| 70 | 72 | pub enum LoginStyle { |
| 71 | 73 | SessionRestore(Session), |
| 72 | 74 | Password(String), |
| @@ -95,8 +97,6 @@ fn oneshot<T>() -> (ClientReply<T>, ClientResponse<T>) { | ||
| 95 | 97 | return (reply, response); |
| 96 | 98 | } |
| 97 | 99 | |
| 98 | type EchoPair = (OwnedEventId, RoomMessageEventContent); | |
| 99 | ||
| 100 | 100 | pub enum WorkerTask { |
| 101 | 101 | DirectMessages(ClientReply<Vec<(MatrixRoom, DisplayName)>>), |
| 102 | 102 | Init(AsyncProgramStore, ClientReply<()>), |
| @@ -108,16 +108,101 @@ pub enum WorkerTask { | ||
| 108 | 108 | Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>), |
| 109 | 109 | SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>), |
| 110 | 110 | Spaces(ClientReply<Vec<(MatrixRoom, DisplayName)>>), |
| 111 | SendMessage(OwnedRoomId, String, ClientReply<IambResult<EchoPair>>), | |
| 112 | 111 | SetRoom(OwnedRoomId, SetRoomField, ClientReply<IambResult<()>>), |
| 113 | 112 | TypingNotice(OwnedRoomId), |
| 114 | 113 | Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>), |
| 115 | 114 | VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>), |
| 116 | 115 | } |
| 117 | 116 | |
| 117 | impl Debug for WorkerTask { | |
| 118 | fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { | |
| 119 | match self { | |
| 120 | WorkerTask::DirectMessages(_) => { | |
| 121 | f.debug_tuple("WorkerTask::DirectMessages") | |
| 122 | .field(&format_args!("_")) | |
| 123 | .finish() | |
| 124 | }, | |
| 125 | WorkerTask::Init(_, _) => { | |
| 126 | f.debug_tuple("WorkerTask::Init") | |
| 127 | .field(&format_args!("_")) | |
| 128 | .field(&format_args!("_")) | |
| 129 | .finish() | |
| 130 | }, | |
| 131 | WorkerTask::LoadOlder(room_id, from, n, _) => { | |
| 132 | f.debug_tuple("WorkerTask::LoadOlder") | |
| 133 | .field(room_id) | |
| 134 | .field(from) | |
| 135 | .field(n) | |
| 136 | .field(&format_args!("_")) | |
| 137 | .finish() | |
| 138 | }, | |
| 139 | WorkerTask::Login(style, _) => { | |
| 140 | f.debug_tuple("WorkerTask::Login") | |
| 141 | .field(style) | |
| 142 | .field(&format_args!("_")) | |
| 143 | .finish() | |
| 144 | }, | |
| 145 | WorkerTask::GetRoom(room_id, _) => { | |
| 146 | f.debug_tuple("WorkerTask::GetRoom") | |
| 147 | .field(room_id) | |
| 148 | .field(&format_args!("_")) | |
| 149 | .finish() | |
| 150 | }, | |
| 151 | WorkerTask::JoinRoom(s, _) => { | |
| 152 | f.debug_tuple("WorkerTask::JoinRoom") | |
| 153 | .field(s) | |
| 154 | .field(&format_args!("_")) | |
| 155 | .finish() | |
| 156 | }, | |
| 157 | WorkerTask::JoinedRooms(_) => { | |
| 158 | f.debug_tuple("WorkerTask::JoinedRooms").field(&format_args!("_")).finish() | |
| 159 | }, | |
| 160 | WorkerTask::Members(room_id, _) => { | |
| 161 | f.debug_tuple("WorkerTask::Members") | |
| 162 | .field(room_id) | |
| 163 | .field(&format_args!("_")) | |
| 164 | .finish() | |
| 165 | }, | |
| 166 | WorkerTask::SpaceMembers(room_id, _) => { | |
| 167 | f.debug_tuple("WorkerTask::SpaceMembers") | |
| 168 | .field(room_id) | |
| 169 | .field(&format_args!("_")) | |
| 170 | .finish() | |
| 171 | }, | |
| 172 | WorkerTask::Spaces(_) => { | |
| 173 | f.debug_tuple("WorkerTask::Spaces").field(&format_args!("_")).finish() | |
| 174 | }, | |
| 175 | WorkerTask::SetRoom(room_id, field, _) => { | |
| 176 | f.debug_tuple("WorkerTask::SetRoom") | |
| 177 | .field(room_id) | |
| 178 | .field(field) | |
| 179 | .field(&format_args!("_")) | |
| 180 | .finish() | |
| 181 | }, | |
| 182 | WorkerTask::TypingNotice(room_id) => { | |
| 183 | f.debug_tuple("WorkerTask::TypingNotice").field(room_id).finish() | |
| 184 | }, | |
| 185 | WorkerTask::Verify(act, sasv1, _) => { | |
| 186 | f.debug_tuple("WorkerTask::Verify") | |
| 187 | .field(act) | |
| 188 | .field(sasv1) | |
| 189 | .field(&format_args!("_")) | |
| 190 | .finish() | |
| 191 | }, | |
| 192 | WorkerTask::VerifyRequest(user_id, _) => { | |
| 193 | f.debug_tuple("WorkerTask::VerifyRequest") | |
| 194 | .field(user_id) | |
| 195 | .field(&format_args!("_")) | |
| 196 | .finish() | |
| 197 | }, | |
| 198 | } | |
| 199 | } | |
| 200 | } | |
| 201 | ||
| 118 | 202 | #[derive(Clone)] |
| 119 | 203 | pub struct Requester { |
| 120 | pub tx: SyncSender<WorkerTask>, | |
| 204 | pub client: Client, | |
| 205 | pub tx: UnboundedSender<WorkerTask>, | |
| 121 | 206 | } |
| 122 | 207 | |
| 123 | 208 | impl Requester { |
| @@ -152,14 +237,6 @@ impl Requester { | ||
| 152 | 237 | return response.recv(); |
| 153 | 238 | } |
| 154 | 239 | |
| 155 | pub fn send_message(&self, room_id: OwnedRoomId, msg: String) -> IambResult<EchoPair> { | |
| 156 | let (reply, response) = oneshot(); | |
| 157 | ||
| 158 | self.tx.send(WorkerTask::SendMessage(room_id, msg, reply)).unwrap(); | |
| 159 | ||
| 160 | return response.recv(); | |
| 161 | } | |
| 162 | ||
| 163 | 240 | pub fn direct_messages(&self) -> Vec<(MatrixRoom, DisplayName)> { |
| 164 | 241 | let (reply, response) = oneshot(); |
| 165 | 242 | |
| @@ -253,60 +330,57 @@ pub struct ClientWorker { | ||
| 253 | 330 | } |
| 254 | 331 | |
| 255 | 332 | impl ClientWorker { |
| 256 | pub fn spawn(settings: ApplicationSettings) -> Requester { | |
| 257 | let (tx, rx) = sync_channel(5); | |
| 333 | pub async fn spawn(settings: ApplicationSettings) -> Requester { | |
| 334 | let (tx, rx) = unbounded_channel(); | |
| 335 | let account = &settings.profile; | |
| 336 | ||
| 337 | // Set up a custom client that only uses HTTP/1. | |
| 338 | // | |
| 339 | // During my testing, I kept stumbling across something weird with sync and HTTP/2 that | |
| 340 | // will need to be revisited in the future. | |
| 341 | let http = reqwest::Client::builder() | |
| 342 | .user_agent(IAMB_USER_AGENT) | |
| 343 | .timeout(Duration::from_secs(30)) | |
| 344 | .pool_idle_timeout(Duration::from_secs(60)) | |
| 345 | .pool_max_idle_per_host(10) | |
| 346 | .tcp_keepalive(Duration::from_secs(10)) | |
| 347 | .http1_only() | |
| 348 | .build() | |
| 349 | .unwrap(); | |
| 258 | 350 | |
| 259 | let _ = tokio::spawn(async move { | |
| 260 | let account = &settings.profile; | |
| 261 | ||
| 262 | // Set up a custom client that only uses HTTP/1. | |
| 263 | // | |
| 264 | // During my testing, I kept stumbling across something weird with sync and HTTP/2 that | |
| 265 | // will need to be revisited in the future. | |
| 266 | let http = reqwest::Client::builder() | |
| 267 | .user_agent(IAMB_USER_AGENT) | |
| 268 | .timeout(Duration::from_secs(60)) | |
| 269 | .pool_idle_timeout(Duration::from_secs(120)) | |
| 270 | .pool_max_idle_per_host(5) | |
| 271 | .http1_only() | |
| 272 | .build() | |
| 273 | .unwrap(); | |
| 274 | ||
| 275 | // Set up the Matrix client for the selected profile. | |
| 276 | let client = Client::builder() | |
| 277 | .http_client(Arc::new(http)) | |
| 278 | .homeserver_url(account.url.clone()) | |
| 279 | .store_config(StoreConfig::default()) | |
| 280 | .sled_store(settings.matrix_dir.as_path(), None) | |
| 281 | .expect("Failed to setup up sled store for Matrix SDK") | |
| 282 | .request_config( | |
| 283 | RequestConfig::new().timeout(REQ_TIMEOUT).retry_timeout(REQ_TIMEOUT), | |
| 284 | ) | |
| 285 | .build() | |
| 286 | .await | |
| 287 | .expect("Failed to instantiate Matrix client"); | |
| 288 | ||
| 289 | let mut worker = ClientWorker { | |
| 290 | initialized: false, | |
| 291 | settings, | |
| 292 | client, | |
| 293 | sync_handle: None, | |
| 294 | }; | |
| 351 | // Set up the Matrix client for the selected profile. | |
| 352 | let client = Client::builder() | |
| 353 | .http_client(Arc::new(http)) | |
| 354 | .homeserver_url(account.url.clone()) | |
| 355 | .store_config(StoreConfig::default()) | |
| 356 | .sled_store(settings.matrix_dir.as_path(), None) | |
| 357 | .expect("Failed to setup up sled store for Matrix SDK") | |
| 358 | .request_config(RequestConfig::new().timeout(REQ_TIMEOUT).retry_timeout(REQ_TIMEOUT)) | |
| 359 | .build() | |
| 360 | .await | |
| 361 | .expect("Failed to instantiate Matrix client"); | |
| 362 | ||
| 363 | let mut worker = ClientWorker { | |
| 364 | initialized: false, | |
| 365 | settings, | |
| 366 | client: client.clone(), | |
| 367 | sync_handle: None, | |
| 368 | }; | |
| 295 | 369 | |
| 370 | let _ = tokio::spawn(async move { | |
| 296 | 371 | worker.work(rx).await; |
| 297 | 372 | }); |
| 298 | 373 | |
| 299 | return Requester { tx }; | |
| 374 | return Requester { client, tx }; | |
| 300 | 375 | } |
| 301 | 376 | |
| 302 | async fn work(&mut self, rx: Receiver<WorkerTask>) { | |
| 377 | async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) { | |
| 303 | 378 | loop { |
| 304 | let t = rx.recv_timeout(Duration::from_secs(1)); | |
| 379 | let t = rx.recv().await; | |
| 305 | 380 | |
| 306 | 381 | match t { |
| 307 | Ok(task) => self.run(task).await, | |
| 308 | Err(RecvTimeoutError::Timeout) => {}, | |
| 309 | Err(RecvTimeoutError::Disconnected) => { | |
| 382 | Some(task) => self.run(task).await, | |
| 383 | None => { | |
| 310 | 384 | break; |
| 311 | 385 | }, |
| 312 | 386 | } |
| @@ -364,10 +438,6 @@ impl ClientWorker { | ||
| 364 | 438 | assert!(self.initialized); |
| 365 | 439 | reply.send(self.spaces().await); |
| 366 | 440 | }, |
| 367 | WorkerTask::SendMessage(room_id, msg, reply) => { | |
| 368 | assert!(self.initialized); | |
| 369 | reply.send(self.send_message(room_id, msg).await); | |
| 370 | }, | |
| 371 | 441 | WorkerTask::TypingNotice(room_id) => { |
| 372 | 442 | assert!(self.initialized); |
| 373 | 443 | self.typing_notice(room_id).await; |
| @@ -615,33 +685,6 @@ impl ClientWorker { | ||
| 615 | 685 | Ok(Some(InfoMessage::from("Successfully logged in!"))) |
| 616 | 686 | } |
| 617 | 687 | |
| 618 | async fn send_message(&mut self, room_id: OwnedRoomId, msg: String) -> IambResult<EchoPair> { | |
| 619 | let room = if let r @ Some(_) = self.client.get_joined_room(&room_id) { | |
| 620 | r | |
| 621 | } else if self.client.join_room_by_id(&room_id).await.is_ok() { | |
| 622 | self.client.get_joined_room(&room_id) | |
| 623 | } else { | |
| 624 | None | |
| 625 | }; | |
| 626 | ||
| 627 | if let Some(room) = room { | |
| 628 | let msg = TextMessageEventContent::plain(msg); | |
| 629 | let msg = MessageType::Text(msg); | |
| 630 | let msg = RoomMessageEventContent::new(msg); | |
| 631 | ||
| 632 | // XXX: second parameter can be a locally unique transaction id. | |
| 633 | // Useful for doing retries. | |
| 634 | let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?; | |
| 635 | let event_id = resp.event_id; | |
| 636 | ||
| 637 | // XXX: need to either give error messages and retry when needed! | |
| 638 | ||
| 639 | return Ok((event_id, msg)); | |
| 640 | } else { | |
| 641 | Err(IambError::UnknownRoom(room_id).into()) | |
| 642 | } | |
| 643 | } | |
| 644 | ||
| 645 | 688 | async fn direct_message(&mut self, user: OwnedUserId) -> IambResult<(MatrixRoom, DisplayName)> { |
| 646 | 689 | for (room, name) in self.direct_messages().await { |
| 647 | 690 | if room.get_member(user.as_ref()).await.map_err(IambError::from)?.is_some() { |