Commit b6f4b03c12

b6f4b03c1271b422215869aa91e71705895b55e7

parent: 504b520fe1

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-01-11 03:59 UTC

Support uploading and downloading message attachments (#13)

Layout: unified · split

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