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"
10191019source = "registry+https://github.com/rust-lang/crates.io-index"
10201020checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
10211021
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
10311022[[package]]
10321023name = "hermit-abi"
10331024version = "0.2.6"
@@ -1137,6 +1128,8 @@ dependencies = [
11371128 "gethostname",
11381129 "lazy_static",
11391130 "matrix-sdk",
1131 "mime",
1132 "mime_guess",
11401133 "modalkit",
11411134 "regex",
11421135 "rpassword",
@@ -1271,7 +1264,7 @@ version = "0.4.1"
12711264source = "registry+https://github.com/rust-lang/crates.io-index"
12721265checksum = "927609f78c2913a6f6ac3c27a4fe87f43e2a35367c0c4b0f8265e8f49a104330"
12731266dependencies = [
1274 "hermit-abi 0.2.6",
1267 "hermit-abi",
12751268 "io-lifetimes",
12761269 "rustix",
12771270 "windows-sys",
@@ -1580,6 +1573,16 @@ version = "0.3.16"
15801573source = "registry+https://github.com/rust-lang/crates.io-index"
15811574checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
15821575
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
15831586[[package]]
15841587name = "minimal-lexical"
15851588version = "0.2.1"
@@ -1658,11 +1661,11 @@ dependencies = [
16581661
16591662[[package]]
16601663name = "num_cpus"
1661version = "1.14.0"
1664version = "1.15.0"
16621665source = "registry+https://github.com/rust-lang/crates.io-index"
1663checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5"
1666checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
16641667dependencies = [
1665 "hermit-abi 0.1.19",
1668 "hermit-abi",
16661669 "libc",
16671670]
16681671
@@ -2589,9 +2592,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
25892592
25902593[[package]]
25912594name = "tokio"
2592version = "1.23.0"
2595version = "1.24.1"
25932596source = "registry+https://github.com/rust-lang/crates.io-index"
2594checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46"
2597checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae"
25952598dependencies = [
25962599 "autocfg",
25972600 "bytes",
@@ -2599,9 +2602,7 @@ dependencies = [
25992602 "memchr",
26002603 "mio",
26012604 "num_cpus",
2602 "parking_lot 0.12.1",
26032605 "pin-project-lite",
2604 "signal-hook-registry",
26052606 "socket2",
26062607 "tokio-macros",
26072608 "windows-sys",
@@ -2752,6 +2753,15 @@ version = "1.16.0"
27522753source = "registry+https://github.com/rust-lang/crates.io-index"
27532754checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
27542755
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
27552765[[package]]
27562766name = "unicode-bidi"
27572767version = "0.3.8"
Cargo.toml +3 −1
@@ -19,6 +19,8 @@ dirs = "4.0.0"
1919futures = "0.3.21"
2020gethostname = "0.4.1"
2121matrix-sdk = {version = "0.6", default-features = false, features = ["e2e-encryption", "sled", "rustls-tls"]}
22mime = "^0.3.16"
23mime_guess = "^2.0.4"
2224modalkit = "0.0.9"
2325regex = "^1.5"
2426rpassword = "^7.2"
@@ -26,7 +28,7 @@ serde = "^1.0"
2628serde_json = "^1.0"
2729sled = "0.34"
2830thiserror = "^1.0.37"
29tokio = {version = "1.17.0", features = ["full"]}
31tokio = {version = "1.24.1", features = ["macros", "net", "rt-multi-thread", "sync", "time"]}
3032tracing = "~0.1.36"
3133tracing-appender = "~0.2.2"
3234tracing-subscriber = "0.3.16"
README.md +2 −2
@@ -63,8 +63,8 @@ two other TUI clients and Element Web:
6363| Typing Notification | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
6464| E2E | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
6565| 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: |
6868| Send stickers | :x: | :x: | :x: | :heavy_check_mark: |
6969| Send formatted messages (markdown) | :x: ([#10]) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
7070| Rich Text Editor for formatted messages | :x: | :x: | :x: | :heavy_check_mark: |
src/base.rs +48 −5
@@ -59,6 +59,11 @@ pub enum VerifyAction {
5959 Mismatch,
6060}
6161
62#[derive(Clone, Debug, Eq, PartialEq)]
63pub enum MessageAction {
64 Download(Option<String>, bool),
65}
66
6267#[derive(Clone, Debug, Eq, PartialEq)]
6368pub enum SetRoomField {
6469 Name(String),
@@ -77,26 +82,46 @@ impl From<SetRoomField> for RoomAction {
7782 }
7883}
7984
85#[derive(Clone, Debug, Eq, PartialEq)]
86pub enum SendAction {
87 Submit,
88 Upload(String),
89}
90
8091#[derive(Clone, Debug, Eq, PartialEq)]
8192pub enum IambAction {
93 Message(MessageAction),
8294 Room(RoomAction),
95 Send(SendAction),
8396 Verify(VerifyAction, String),
8497 VerifyRequest(String),
85 SendMessage(OwnedRoomId, String),
8698 ToggleScrollbackFocus,
8799}
88100
101impl From<MessageAction> for IambAction {
102 fn from(act: MessageAction) -> Self {
103 IambAction::Message(act)
104 }
105}
106
89107impl From<RoomAction> for IambAction {
90108 fn from(act: RoomAction) -> Self {
91109 IambAction::Room(act)
92110 }
93111}
94112
113impl From<SendAction> for IambAction {
114 fn from(act: SendAction) -> Self {
115 IambAction::Send(act)
116 }
117}
118
95119impl ApplicationAction for IambAction {
96120 fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
97121 match self {
122 IambAction::Message(..) => SequenceStatus::Break,
98123 IambAction::Room(..) => SequenceStatus::Break,
99 IambAction::SendMessage(..) => SequenceStatus::Break,
124 IambAction::Send(..) => SequenceStatus::Break,
100125 IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
101126 IambAction::Verify(..) => SequenceStatus::Break,
102127 IambAction::VerifyRequest(..) => SequenceStatus::Break,
@@ -105,8 +130,9 @@ impl ApplicationAction for IambAction {
105130
106131 fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
107132 match self {
133 IambAction::Message(..) => SequenceStatus::Atom,
108134 IambAction::Room(..) => SequenceStatus::Atom,
109 IambAction::SendMessage(..) => SequenceStatus::Atom,
135 IambAction::Send(..) => SequenceStatus::Atom,
110136 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
111137 IambAction::Verify(..) => SequenceStatus::Atom,
112138 IambAction::VerifyRequest(..) => SequenceStatus::Atom,
@@ -115,8 +141,9 @@ impl ApplicationAction for IambAction {
115141
116142 fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
117143 match self {
144 IambAction::Message(..) => SequenceStatus::Ignore,
118145 IambAction::Room(..) => SequenceStatus::Ignore,
119 IambAction::SendMessage(..) => SequenceStatus::Ignore,
146 IambAction::Send(..) => SequenceStatus::Ignore,
120147 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
121148 IambAction::Verify(..) => SequenceStatus::Ignore,
122149 IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
@@ -125,8 +152,9 @@ impl ApplicationAction for IambAction {
125152
126153 fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
127154 match self {
155 IambAction::Message(..) => false,
128156 IambAction::Room(..) => false,
129 IambAction::SendMessage(..) => false,
157 IambAction::Send(..) => false,
130158 IambAction::ToggleScrollbackFocus => false,
131159 IambAction::Verify(..) => false,
132160 IambAction::VerifyRequest(..) => false,
@@ -173,6 +201,21 @@ pub enum IambError {
173201 #[error("Serialization/deserialization error: {0}")]
174202 Serde(#[from] serde_json::Error),
175203
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
176219 #[error("Unknown room identifier: {0}")]
177220 UnknownRoom(OwnedRoomId),
178221
src/commands.rs +32
@@ -8,10 +8,12 @@ use modalkit::{
88use crate::base::{
99 IambAction,
1010 IambId,
11 MessageAction,
1112 ProgramCommand,
1213 ProgramCommands,
1314 ProgramContext,
1415 RoomAction,
16 SendAction,
1517 SetRoomField,
1618 VerifyAction,
1719};
@@ -149,13 +151,43 @@ fn iamb_set(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
149151 return Ok(step);
150152}
151153
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
152182fn add_iamb_commands(cmds: &mut ProgramCommands) {
153183 cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms });
184 cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download });
154185 cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
155186 cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
156187 cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
157188 cmds.add_command(ProgramCommand { names: vec!["set".into()], f: iamb_set });
158189 cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
190 cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload });
159191 cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify });
160192 cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome });
161193}
src/config.rs +5 −1
@@ -237,7 +237,11 @@ impl Directories {
237237 fn values(self) -> DirectoryValues {
238238 let cache = self
239239 .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 })
241245 .expect("no dirs.cache value configured!");
242246
243247 let logs = self.logs.unwrap_or_else(|| {
src/main.rs +55 −44
@@ -9,6 +9,7 @@ use std::fs::{create_dir_all, File};
99use std::io::{stdout, BufReader, Stdout};
1010use std::ops::DerefMut;
1111use std::process;
12use std::sync::atomic::{AtomicUsize, Ordering};
1213use std::sync::Arc;
1314use std::time::Duration;
1415
@@ -63,7 +64,6 @@ use crate::{
6364 ProgramStore,
6465 },
6566 config::{ApplicationSettings, Iamb},
66 message::{Message, MessageContent, MessageTimeStamp},
6767 windows::IambWindow,
6868 worker::{ClientWorker, LoginStyle, Requester},
6969};
@@ -226,7 +226,7 @@ impl Application {
226226 }
227227 }
228228
229 fn action_run(
229 async fn action_run(
230230 &mut self,
231231 action: ProgramAction,
232232 ctx: ProgramContext,
@@ -257,7 +257,7 @@ impl Application {
257257 },
258258
259259 // Simple delegations.
260 Action::Application(act) => self.iamb_run(act, ctx, store)?,
260 Action::Application(act) => self.iamb_run(act, ctx, store).await?,
261261 Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
262262 Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
263263 Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
@@ -314,7 +314,7 @@ impl Application {
314314 return Ok(info);
315315 }
316316
317 fn iamb_run(
317 async fn iamb_run(
318318 &mut self,
319319 action: IambAction,
320320 ctx: ProgramContext,
@@ -327,24 +327,19 @@ impl Application {
327327 None
328328 },
329329
330 IambAction::Message(act) => {
331 self.screen.current_window_mut()?.message_command(act, ctx, store).await?
332 },
330333 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?;
332335 self.action_prepend(acts);
333336
334337 None
335338 },
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?
347341 },
342
348343 IambAction::Verify(act, user_dev) => {
349344 if let Some(sas) = store.application.verifications.get(&user_dev) {
350345 self.worker.verify(act, sas.clone())?
@@ -378,7 +373,7 @@ impl Application {
378373 let mut keyskip = false;
379374
380375 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 {
382377 Ok(None) => {
383378 // Continue processing.
384379 continue;
@@ -408,7 +403,7 @@ impl Application {
408403 }
409404}
410405
411fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
406async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
412407 println!("Logging in for {}...", settings.profile.user_id);
413408
414409 if settings.session_json.is_file() {
@@ -447,38 +442,15 @@ fn print_exit<T: Display, N>(v: T) -> N {
447442 process::exit(2);
448443}
449444
450#[tokio::main]
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
445async fn run(settings: ApplicationSettings) -> IambResult<()> {
474446 // Set up the async worker thread and global store.
475 let worker = ClientWorker::spawn(settings.clone());
447 let worker = ClientWorker::spawn(settings.clone()).await;
476448 let store = ChatStore::new(worker.clone(), settings.clone());
477449 let store = Store::new(store);
478450 let store = Arc::new(AsyncMutex::new(store));
479451 worker.init(store.clone());
480452
481 login(worker, &settings).unwrap_or_else(print_exit);
453 login(worker, &settings).await.unwrap_or_else(print_exit);
482454
483455 // Make sure panics clean up the terminal properly.
484456 let orig_hook = std::panic::take_hook();
@@ -495,5 +467,44 @@ async fn main() -> IambResult<()> {
495467 // We can now run the application.
496468 application.run().await?;
497469
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);
498509 process::exit(0);
499510}
src/message.rs +35 −39
@@ -309,46 +309,41 @@ pub enum MessageContent {
309309 Redacted,
310310}
311311
312impl AsRef<str> for MessageContent {
313 fn as_ref(&self) -> &str {
312impl MessageContent {
313 pub fn show(&self) -> Cow<'_, str> {
314314 match self {
315315 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(),
328321
329 return "[server notice]";
330 },
331322 MessageType::VerificationRequest(_) => {
332323 // XXX: implement
333324
334 return "[verification request]";
325 return Cow::Owned("[verification request]".into());
335326 },
336 MessageType::Audio(..) => {
337 return "[audio]";
327 MessageType::Audio(content) => {
328 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
338329 },
339 MessageType::File(..) => {
340 return "[file]";
330 MessageType::File(content) => {
331 return Cow::Owned(format!("[Attached File: {}]", content.body));
341332 },
342 MessageType::Image(..) => {
343 return "[image]";
333 MessageType::Image(content) => {
334 return Cow::Owned(format!("[Attached Image: {}]", content.body));
344335 },
345 MessageType::Video(..) => {
346 return "[video]";
336 MessageType::Video(content) => {
337 return Cow::Owned(format!("[Attached Video: {}]", content.body));
347338 },
348 _ => return "[unknown message type]",
349 }
339 _ => {
340 return Cow::Owned(format!("[Unknown message type: {:?}]", ev.msgtype()));
341 },
342 };
343
344 Cow::Borrowed(s)
350345 },
351 MessageContent::Redacted => "[redacted]",
346 MessageContent::Redacted => Cow::Borrowed("[redacted]"),
352347 }
353348 }
354349}
@@ -358,11 +353,12 @@ pub struct Message {
358353 pub content: MessageContent,
359354 pub sender: OwnedUserId,
360355 pub timestamp: MessageTimeStamp,
356 pub downloaded: bool,
361357}
362358
363359impl Message {
364360 pub fn new(content: MessageContent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
365 Message { content, sender, timestamp }
361 Message { content, sender, timestamp, downloaded: false }
366362 }
367363
368364 pub fn show(
@@ -373,7 +369,13 @@ impl Message {
373369 settings: &ApplicationSettings,
374370 ) -> Text {
375371 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();
377379
378380 let mut lines = vec![];
379381
@@ -391,7 +393,7 @@ impl Message {
391393 let lw = width - USER_GUTTER - TIME_GUTTER;
392394
393395 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);
395397 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
396398
397399 if i == 0 {
@@ -412,7 +414,7 @@ impl Message {
412414 let lw = width - USER_GUTTER;
413415
414416 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);
416418 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
417419
418420 let prefix = if i == 0 {
@@ -478,15 +480,9 @@ impl From<MessageEvent> for Message {
478480 }
479481}
480482
481impl AsRef<str> for Message {
482 fn as_ref(&self) -> &str {
483 self.content.as_ref()
484 }
485}
486
487483impl ToString for Message {
488484 fn to_string(&self) -> String {
489 self.as_ref().to_string()
485 self.content.show().into_owned()
490486 }
491487}
492488
src/tests.rs +6 −4
@@ -1,6 +1,5 @@
11use std::collections::{BTreeMap, HashMap};
22use std::path::PathBuf;
3use std::sync::mpsc::sync_channel;
43
54use matrix_sdk::ruma::{
65 event_id,
@@ -16,6 +15,7 @@ use matrix_sdk::ruma::{
1615
1716use lazy_static::lazy_static;
1817use modalkit::tui::style::Color;
18use tokio::sync::mpsc::unbounded_channel;
1919use url::Url;
2020
2121use crate::{
@@ -154,9 +154,11 @@ pub fn mock_settings() -> ApplicationSettings {
154154 }
155155}
156156
157pub fn mock_store() -> ProgramStore {
158 let (tx, _) = sync_channel(5);
159 let worker = Requester { tx };
157pub 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 };
160162
161163 let mut store = ChatStore::new(worker, mock_settings());
162164 let room_id = TEST_ROOM1_ID.clone();
src/windows/mod.rs +92 −7
@@ -54,13 +54,16 @@ use modalkit::{
5454use crate::base::{
5555 ChatStore,
5656 IambBufferId,
57 IambError,
5758 IambId,
5859 IambInfo,
5960 IambResult,
61 MessageAction,
6062 ProgramAction,
6163 ProgramContext,
6264 ProgramStore,
6365 RoomAction,
66 SendAction,
6467};
6568
6669use self::{room::RoomState, welcome::WelcomeState};
@@ -102,6 +105,20 @@ fn selected_text(s: &str, selected: bool) -> Text {
102105 Text::from(selected_span(s, selected))
103106}
104107
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
105122#[inline]
106123fn room_prompt(
107124 room_id: &RoomId,
@@ -165,19 +182,42 @@ impl IambWindow {
165182 }
166183 }
167184
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(
169199 &mut self,
170200 act: RoomAction,
171201 ctx: ProgramContext,
172202 store: &mut ProgramStore,
173203 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
174204 if let IambWindow::Room(w) = self {
175 w.room_command(act, ctx, store)
205 w.room_command(act, ctx, store).await
176206 } else {
177 let msg = "No room currently focused!";
178 let err = UIError::Failure(msg.into());
207 return Err(IambError::NoSelectedRoomOrSpace.into());
208 }
209 }
179210
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());
181221 }
182222 }
183223}
@@ -304,8 +344,13 @@ impl WindowOps<IambInfo> for IambWindow {
304344 },
305345 IambWindow::RoomList(state) => {
306346 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);
309354
310355 List::new(store)
311356 .empty_message("You haven't joined any rooms yet")
@@ -515,6 +560,26 @@ impl RoomItem {
515560 }
516561}
517562
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
518583impl ToString for RoomItem {
519584 fn to_string(&self) -> String {
520585 return self.name.clone();
@@ -601,6 +666,26 @@ impl SpaceItem {
601666 }
602667}
603668
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
604689impl ToString for SpaceItem {
605690 fn to_string(&self) -> String {
606691 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
16use matrix_sdk::{
7 attachment::AttachmentConfig,
8 media::{MediaFormat, MediaRequest},
29 room::Room as MatrixRoom,
3 ruma::{OwnedRoomId, RoomId},
10 ruma::{
11 events::room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent},
12 OwnedRoomId,
13 RoomId,
14 },
415};
516
6use modalkit::tui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget};
7
817use modalkit::{
18 tui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget},
919 widgets::textbox::{TextBox, TextBoxState},
1020 widgets::TerminalCursor,
1121 widgets::{PromptActions, WindowOps},
@@ -18,10 +28,12 @@ use modalkit::editing::{
1828 EditResult,
1929 Editable,
2030 EditorAction,
31 InfoMessage,
2132 Jumpable,
2233 PromptAction,
2334 Promptable,
2435 Scrollable,
36 UIError,
2537 },
2638 base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle},
2739 context::Resolve,
@@ -32,14 +44,19 @@ use modalkit::editing::{
3244use crate::base::{
3345 IambAction,
3446 IambBufferId,
47 IambError,
3548 IambInfo,
3649 IambResult,
50 MessageAction,
3751 ProgramAction,
3852 ProgramContext,
3953 ProgramStore,
4054 RoomFocus,
55 SendAction,
4156};
4257
58use crate::message::{Message, MessageContent, MessageTimeStamp};
59
4360use super::scrollback::{Scrollback, ScrollbackState};
4461
4562pub struct ChatState {
@@ -75,6 +92,169 @@ impl ChatState {
7592 }
7693 }
7794
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
78258 pub fn focus_toggle(&mut self) {
79259 self.focus = match self.focus {
80260 RoomFocus::Scrollback => RoomFocus::MessageBar,
@@ -229,17 +409,9 @@ impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
229409 ctx: &ProgramContext,
230410 _: &mut ProgramStore,
231411 ) -> 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;
241413
242 Ok(act)
414 Ok(vec![(IambAction::from(act).into(), ctx.clone())])
243415 }
244416
245417 fn abort(
src/windows/room/mod.rs +29 −4
@@ -1,6 +1,4 @@
1use matrix_sdk::room::Room as MatrixRoom;
2use matrix_sdk::ruma::RoomId;
3use matrix_sdk::DisplayName;
1use matrix_sdk::{room::Room as MatrixRoom, ruma::RoomId, DisplayName};
42
53use modalkit::tui::{
64 buffer::Buffer,
@@ -37,13 +35,16 @@ use modalkit::{
3735};
3836
3937use crate::base::{
38 IambError,
4039 IambId,
4140 IambInfo,
4241 IambResult,
42 MessageAction,
4343 ProgramAction,
4444 ProgramContext,
4545 ProgramStore,
4646 RoomAction,
47 SendAction,
4748};
4849
4950use self::chat::ChatState;
@@ -92,7 +93,31 @@ impl RoomState {
9293 }
9394 }
9495
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(
96121 &mut self,
97122 act: RoomAction,
98123 _: ProgramContext,
src/windows/room/scrollback.rs +32 −20
@@ -126,6 +126,14 @@ impl ScrollbackState {
126126 self.viewctx.dimensions = (area.width as usize, area.height as usize);
127127 }
128128
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
129137 pub fn messages<'a>(
130138 &self,
131139 range: EditRange<MessageCursor>,
@@ -389,7 +397,7 @@ impl ScrollbackState {
389397 continue;
390398 }
391399
392 if needle.is_match(msg.as_ref()) {
400 if needle.is_match(msg.content.show().as_ref()) {
393401 mc = MessageCursor::from(key.clone()).into();
394402 count -= 1;
395403 }
@@ -413,7 +421,7 @@ impl ScrollbackState {
413421 break;
414422 }
415423
416 if needle.is_match(msg.as_ref()) {
424 if needle.is_match(msg.content.show().as_ref()) {
417425 mc = MessageCursor::from(key.clone()).into();
418426 count -= 1;
419427 }
@@ -659,7 +667,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
659667 let mut yanked = EditRope::from("");
660668
661669 for (_, msg) in self.messages(range, info) {
662 yanked += EditRope::from(msg.as_ref());
670 yanked += EditRope::from(msg.content.show().into_owned());
663671 yanked += EditRope::from('\n');
664672 }
665673
@@ -1159,12 +1167,14 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11591167 };
11601168
11611169 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)
11661174 };
11671175
1176 let full = cursor.timestamp.is_none();
1177
11681178 let mut lines = vec![];
11691179 let mut sawit = false;
11701180 let mut prev = None;
@@ -1175,8 +1185,10 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11751185
11761186 prev = Some(item);
11771187
1188 let incomplete_ok = !full || !sel;
1189
11781190 for (row, line) in txt.lines.into_iter().enumerate() {
1179 if sawit && lines.len() >= height {
1191 if sawit && lines.len() >= height && incomplete_ok {
11801192 // Check whether we've seen the first line of the
11811193 // selected message and can fill the screen.
11821194 break;
@@ -1224,10 +1236,10 @@ mod tests {
12241236 use super::*;
12251237 use crate::tests::*;
12261238
1227 #[test]
1228 fn test_search_messages() {
1239 #[tokio::test]
1240 async fn test_search_messages() {
12291241 let room_id = TEST_ROOM1_ID.clone();
1230 let mut store = mock_store();
1242 let mut store = mock_store().await;
12311243 let mut scrollback = ScrollbackState::new(room_id.clone());
12321244 let ctx = ProgramContext::default();
12331245
@@ -1268,9 +1280,9 @@ mod tests {
12681280 assert_eq!(scrollback.cursor, MSG1_KEY.clone().into());
12691281 }
12701282
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;
12741286 let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
12751287 let ctx = ProgramContext::default();
12761288
@@ -1302,9 +1314,9 @@ mod tests {
13021314 assert_eq!(scrollback.cursor, MSG1_KEY.clone().into());
13031315 }
13041316
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;
13081320 let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
13091321 let ctx = ProgramContext::default();
13101322
@@ -1436,9 +1448,9 @@ mod tests {
14361448 assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 4));
14371449 }
14381450
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;
14421454 let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
14431455 let ctx = ProgramContext::default();
14441456
src/worker.rs +133 −90
@@ -1,12 +1,14 @@
11use std::convert::TryFrom;
2use std::fmt::{Debug, Formatter};
23use std::fs::File;
34use std::io::BufWriter;
45use std::str::FromStr;
5use std::sync::mpsc::{sync_channel, Receiver, RecvTimeoutError, SyncSender};
6use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
67use std::sync::Arc;
78use std::time::Duration;
89
910use gethostname::gethostname;
11use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
1012use tokio::task::JoinHandle;
1113use tracing::error;
1214
@@ -31,7 +33,7 @@ use matrix_sdk::{
3133 VerificationMethod,
3234 },
3335 room::{
34 message::{MessageType, RoomMessageEventContent, TextMessageEventContent},
36 message::{MessageType, RoomMessageEventContent},
3537 name::RoomNameEventContent,
3638 topic::RoomTopicEventContent,
3739 },
@@ -41,7 +43,6 @@ use matrix_sdk::{
4143 SyncMessageLikeEvent,
4244 SyncStateEvent,
4345 },
44 OwnedEventId,
4546 OwnedRoomId,
4647 OwnedRoomOrAliasId,
4748 OwnedUserId,
@@ -67,6 +68,7 @@ fn initial_devname() -> String {
6768 format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy())
6869}
6970
71#[derive(Debug)]
7072pub enum LoginStyle {
7173 SessionRestore(Session),
7274 Password(String),
@@ -95,8 +97,6 @@ fn oneshot<T>() -> (ClientReply<T>, ClientResponse<T>) {
9597 return (reply, response);
9698}
9799
98type EchoPair = (OwnedEventId, RoomMessageEventContent);
99
100100pub enum WorkerTask {
101101 DirectMessages(ClientReply<Vec<(MatrixRoom, DisplayName)>>),
102102 Init(AsyncProgramStore, ClientReply<()>),
@@ -108,16 +108,101 @@ pub enum WorkerTask {
108108 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
109109 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
110110 Spaces(ClientReply<Vec<(MatrixRoom, DisplayName)>>),
111 SendMessage(OwnedRoomId, String, ClientReply<IambResult<EchoPair>>),
112111 SetRoom(OwnedRoomId, SetRoomField, ClientReply<IambResult<()>>),
113112 TypingNotice(OwnedRoomId),
114113 Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
115114 VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
116115}
117116
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
118202#[derive(Clone)]
119203pub struct Requester {
120 pub tx: SyncSender<WorkerTask>,
204 pub client: Client,
205 pub tx: UnboundedSender<WorkerTask>,
121206}
122207
123208impl Requester {
@@ -152,14 +237,6 @@ impl Requester {
152237 return response.recv();
153238 }
154239
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
163240 pub fn direct_messages(&self) -> Vec<(MatrixRoom, DisplayName)> {
164241 let (reply, response) = oneshot();
165242
@@ -253,60 +330,57 @@ pub struct ClientWorker {
253330}
254331
255332impl 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();
258350
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 };
295369
370 let _ = tokio::spawn(async move {
296371 worker.work(rx).await;
297372 });
298373
299 return Requester { tx };
374 return Requester { client, tx };
300375 }
301376
302 async fn work(&mut self, rx: Receiver<WorkerTask>) {
377 async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) {
303378 loop {
304 let t = rx.recv_timeout(Duration::from_secs(1));
379 let t = rx.recv().await;
305380
306381 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 => {
310384 break;
311385 },
312386 }
@@ -364,10 +438,6 @@ impl ClientWorker {
364438 assert!(self.initialized);
365439 reply.send(self.spaces().await);
366440 },
367 WorkerTask::SendMessage(room_id, msg, reply) => {
368 assert!(self.initialized);
369 reply.send(self.send_message(room_id, msg).await);
370 },
371441 WorkerTask::TypingNotice(room_id) => {
372442 assert!(self.initialized);
373443 self.typing_notice(room_id).await;
@@ -615,33 +685,6 @@ impl ClientWorker {
615685 Ok(Some(InfoMessage::from("Successfully logged in!")))
616686 }
617687
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
645688 async fn direct_message(&mut self, user: OwnedUserId) -> IambResult<(MatrixRoom, DisplayName)> {
646689 for (room, name) in self.direct_messages().await {
647690 if room.get_member(user.as_ref()).await.map_err(IambError::from)?.is_some() {