-
Notifications
You must be signed in to change notification settings - Fork 27
/
mod.rs
1126 lines (975 loc) · 35.4 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Room buffer module.
//!
//! This module implements creates buffers that processes and prints out all the
//! user visible events
//!
//! Care should be taken when handling events. Events can be state events or
//! timeline events and they can come from a sync response or from a room
//! messages response.
//!
//! Events coming from a sync response and are part of the timeline need to be
//! printed out and they need to change the buffer state (e.g. when someone
//! joins, they need to be added to the nicklist).
//!
//! Events coming from a sync response and are part of the room state only need
//! to change the buffer state.
//!
//! Events coming from a room messages response, meaning they are old events,
//! should never change the room state. They only should be printed out.
//!
//! Care should be taken to model this in a way that event formatting methods
//! are pure functions so they can be reused e.g. if we print messages that
//! we're sending ourselves before we receive them in a sync response, or if we
//! decrypt a previously undecryptable event.
mod members;
use members::Members;
pub use members::WeechatRoomMember;
use tracing::{debug, trace};
pub const BUFFER_CLOSED_ERROR: &str =
"Buffer got closed but Room is still lingering around";
use std::{
borrow::Cow,
cell::RefCell,
collections::HashMap,
ops::Deref,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Mutex, MutexGuard,
},
time::{Instant, SystemTime},
};
use futures::executor::block_on;
use unicode_segmentation::UnicodeSegmentation;
use url::Url;
use matrix_sdk::{
async_trait,
deserialized_responses::AmbiguityChange,
events::{
room::{
member::MemberEventContent,
message::{MessageEventContent, TextMessageEventContent},
redaction::SyncRedactionEvent,
},
AnyMessageEventContent, AnyRedactedSyncMessageEvent, AnyRoomEvent,
AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent,
SyncMessageEvent, SyncStateEvent,
},
identifiers::{EventId, RoomAliasId, RoomId, UserId},
uuid::Uuid,
JoinedRoom, StoreError,
};
use weechat::{
buffer::{
Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync,
BufferLine, LineData,
},
Weechat,
};
use crate::{
config::{Config, RedactionStyle},
connection::{Connection, TYPING_NOTICE_TIMEOUT},
render::{Render, RenderedEvent},
utils::Edit,
PLUGIN_NAME,
};
#[derive(Clone)]
pub struct RoomHandle {
inner: MatrixRoom,
buffer_handle: BufferHandle,
}
#[derive(Debug, Clone)]
pub enum PrevBatch {
Forward(String),
Backwards(String),
}
impl Deref for RoomHandle {
type Target = MatrixRoom;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[derive(Clone, Debug)]
struct IntMutex {
inner: Rc<Mutex<Rc<AtomicBool>>>,
locked: Rc<AtomicBool>,
}
struct IntMutexGuard<'a> {
inner: MutexGuard<'a, Rc<AtomicBool>>,
}
impl<'a> Drop for IntMutexGuard<'a> {
fn drop(&mut self) {
self.inner.store(false, Ordering::SeqCst)
}
}
impl IntMutex {
fn new() -> Self {
let locked = Rc::new(AtomicBool::from(false));
let inner = Rc::new(Mutex::new(locked.clone()));
Self { inner, locked }
}
fn locked(&self) -> bool {
self.locked.load(Ordering::SeqCst)
}
fn try_lock(&self) -> Result<IntMutexGuard<'_>, ()> {
match self.inner.try_lock() {
Ok(guard) => {
guard.store(true, Ordering::SeqCst);
Ok(IntMutexGuard { inner: guard })
}
Err(_) => Err(()),
}
}
}
#[derive(Clone)]
pub struct MatrixRoom {
homeserver: Rc<Url>,
room_id: Rc<RoomId>,
own_user_id: Rc<UserId>,
room: JoinedRoom,
buffer: Rc<Option<BufferHandle>>,
config: Rc<RefCell<Config>>,
connection: Rc<RefCell<Option<Connection>>>,
typing_notice_time: Rc<RefCell<Option<Instant>>>,
typing_in_flight: Rc<Mutex<()>>,
messages_in_flight: IntMutex,
prev_batch: Rc<RefCell<Option<PrevBatch>>>,
outgoing_messages: MessageQueue,
members: Members,
}
#[derive(Debug, Clone, Default)]
pub struct MessageQueue {
queue: Rc<RefCell<HashMap<Uuid, (bool, MessageEventContent)>>>,
}
impl MessageQueue {
fn new() -> Self {
Self {
queue: Rc::new(RefCell::new(HashMap::new())),
}
}
fn add(&self, uuid: Uuid, content: MessageEventContent) {
self.queue.borrow_mut().insert(uuid, (false, content));
}
fn add_with_echo(&self, uuid: Uuid, content: MessageEventContent) {
self.queue.borrow_mut().insert(uuid, (true, content));
}
fn remove(&self, uuid: Uuid) -> Option<(bool, MessageEventContent)> {
self.queue.borrow_mut().remove(&uuid)
}
}
impl RoomHandle {
pub fn new(
server_name: &str,
connection: &Rc<RefCell<Option<Connection>>>,
config: Rc<RefCell<Config>>,
room: JoinedRoom,
homeserver: &Url,
room_id: RoomId,
own_user_id: &UserId,
) -> Self {
let members = Members::new(room.clone());
let own_nick = block_on(room.get_member(own_user_id))
.ok()
.flatten()
.map(|m| m.name().to_owned())
.unwrap_or_else(|| own_user_id.localpart().to_owned());
let mut room = MatrixRoom {
homeserver: Rc::new(homeserver.clone()),
room_id: Rc::new(room_id.clone()),
connection: connection.clone(),
typing_notice_time: Rc::new(RefCell::new(None)),
typing_in_flight: Rc::new(Mutex::new(())),
config,
prev_batch: Rc::new(RefCell::new(
room.last_prev_batch().map(PrevBatch::Backwards),
)),
own_user_id: Rc::new(own_user_id.to_owned()),
members: members.clone(),
buffer: members.buffer,
outgoing_messages: MessageQueue::new(),
messages_in_flight: IntMutex::new(),
room,
};
let buffer_name = format!("{}.{}", server_name, room_id);
let buffer_handle = BufferBuilderAsync::new(&buffer_name)
.input_callback(room.clone())
.close_callback(|_weechat: &Weechat, _buffer: &Buffer| {
// TODO remove the roombuffer from the server here.
// TODO leave the room if the plugin isn't unloading.
Ok(())
})
.build()
.expect("Can't create new room buffer");
let buffer = buffer_handle
.upgrade()
.expect("Can't upgrade newly created buffer");
buffer
.add_nicklist_group(
"000|o",
"weechat.color.nicklist_group",
true,
None,
)
.expect("Can't create nicklist group");
buffer
.add_nicklist_group(
"001|h",
"weechat.color.nicklist_group",
true,
None,
)
.expect("Can't create nicklist group");
buffer
.add_nicklist_group(
"002|v",
"weechat.color.nicklist_group",
true,
None,
)
.expect("Can't create nicklist group");
buffer
.add_nicklist_group(
"999|...",
"weechat.color.nicklist_group",
true,
None,
)
.expect("Can't create nicklist group");
buffer.enable_nicklist();
buffer.disable_nicklist_groups();
buffer.enable_multiline();
buffer.set_localvar("server", server_name);
buffer.set_localvar("nick", &own_nick);
buffer.set_localvar("domain", room.room_id().server_name().as_str());
buffer.set_localvar("room_id", room.room_id().as_str());
if let Some(alias) = room.alias() {
buffer.set_localvar("alias", alias.as_str());
}
// This is fine since we're only given the room to the buffer input and
// the callback can only run once we yield controll back to Weechat.
unsafe {
*Rc::get_mut_unchecked(&mut room.members.buffer) =
Some(buffer_handle.clone());
}
Self {
inner: room,
buffer_handle,
}
}
pub async fn restore(
server_name: &str,
room: JoinedRoom,
connection: &Rc<RefCell<Option<Connection>>>,
config: Rc<RefCell<Config>>,
homeserver: &Url,
) -> Result<Self, StoreError> {
let room_clone = room.clone();
let room_id = room.room_id();
let own_user_id = room.own_user_id();
let prev_batch = room.last_prev_batch();
let room_buffer = Self::new(
server_name,
connection,
config,
room_clone,
homeserver,
room_id.clone(),
own_user_id,
);
debug!("Restoring room {}", room.room_id());
let matrix_members = room.joined_user_ids().await?;
for user_id in matrix_members {
trace!("Restoring member {}", user_id);
room_buffer.members.restore_member(&user_id).await;
}
*room_buffer.prev_batch.borrow_mut() =
prev_batch.map(PrevBatch::Forward);
room_buffer.update_buffer_name();
room_buffer.set_topic();
Ok(room_buffer)
}
}
#[async_trait(?Send)]
impl BufferInputCallbackAsync for MatrixRoom {
async fn callback(&mut self, _: BufferHandle, input: String) {
// TODO parse the input here and produce a formatted body.
let content =
MessageEventContent::Text(TextMessageEventContent::markdown(input));
self.send_message(content).await;
}
}
impl MatrixRoom {
pub fn is_encrypted(&self) -> bool {
self.room.is_encrypted()
}
pub fn is_public(&self) -> bool {
self.room.is_public()
}
pub fn alias(&self) -> Option<RoomAliasId> {
self.room.canonical_alias()
}
pub fn room_id(&self) -> &RoomId {
&self.room_id
}
pub fn buffer_handle(&self) -> BufferHandle {
(&*self.buffer)
.as_ref()
.expect("Room struct wasn't initialized properly")
.clone()
}
fn print_rendered_event(&self, rendered: RenderedEvent) {
let buffer = self.buffer_handle();
if let Ok(buffer) = buffer.upgrade() {
for line in rendered.content.lines {
let message = format!("{}{}", &rendered.prefix, &line.message);
let tags: Vec<&str> =
line.tags.iter().map(|t| t.as_str()).collect();
buffer.print_date_tags(
rendered.message_timestamp,
&tags,
&message,
)
}
}
}
async fn redact_event(&self, event: &SyncRedactionEvent) {
let buffer_handle = self.buffer_handle();
let buffer = if let Ok(b) = buffer_handle.upgrade() {
b
} else {
return;
};
// TODO remove this unwrap.
let redacter = self.members.get(&event.sender).await.unwrap();
let event_id_tag =
Cow::from(format!("{}_id_{}", PLUGIN_NAME, event.redacts));
let tag = Cow::from("matrix_redacted");
let reason = if let Some(r) = &event.content.reason {
format!(", reason: {}", r)
} else {
"".to_owned()
};
let redaction_message = format!(
"{}<{}Message redacted by: {}{}{}>{}",
Weechat::color("chat_delimiters"),
Weechat::color("logger.color.backlog_line"),
redacter.nick(),
reason,
Weechat::color("chat_delimiters"),
Weechat::color("reset"),
);
let redaction_style = self.config.borrow().look().redaction_style();
let predicate = |l: &BufferLine| {
let tags = l.tags();
tags.contains(&event_id_tag)
&& !tags.contains(&Cow::from("matrix_redacted"))
};
let strike_through = |string: Cow<str>| {
Weechat::remove_color(&string)
.graphemes(true)
.map(|g| format!("{}\u{0336}", g))
.collect::<Vec<String>>()
.join("")
};
let redact_first_line = |message: Cow<str>| match redaction_style {
RedactionStyle::Delete => redaction_message.clone(),
RedactionStyle::Notice => {
format!("{} {}", message, redaction_message)
}
RedactionStyle::StrikeThrough => {
format!("{} {}", strike_through(message), redaction_message)
}
};
let redact_string = |message: Cow<str>| match redaction_style {
RedactionStyle::Delete => redaction_message.clone(),
RedactionStyle::Notice => {
format!("{} {}", message, redaction_message)
}
RedactionStyle::StrikeThrough => strike_through(message),
};
fn modify_line<F>(line: BufferLine, tag: Cow<str>, redaction_func: F)
where
F: Fn(Cow<str>) -> String,
{
let message = line.message();
let new_message = redaction_func(message);
let mut tags = line.tags();
tags.push(tag);
let tags: Vec<&str> = tags.iter().map(|t| t.as_ref()).collect();
line.set_message(&new_message);
line.set_tags(&tags);
}
let mut lines = buffer.lines();
let first_line = lines.rfind(predicate);
if let Some(line) = first_line {
modify_line(line, tag.clone(), redact_first_line);
} else {
return;
}
while let Some(line) = lines.next_back().filter(predicate) {
modify_line(line, tag.clone(), redact_string);
}
}
async fn render_message_content(
&self,
event_id: &EventId,
send_time: &SystemTime,
sender: &WeechatRoomMember,
content: &AnyMessageEventContent,
) -> Option<RenderedEvent> {
use AnyMessageEventContent::*;
use MessageEventContent::*;
let rendered = match content {
RoomEncrypted(c) => {
c.render_with_prefix(send_time, event_id, sender, &())
}
RoomMessage(c) => match c {
Text(c) => {
c.render_with_prefix(send_time, event_id, sender, &())
}
Emote(c) => {
c.render_with_prefix(send_time, event_id, &sender, &sender)
}
Notice(c) => {
c.render_with_prefix(send_time, event_id, &sender, &sender)
}
ServerNotice(c) => {
c.render_with_prefix(send_time, event_id, &sender, &sender)
}
Location(c) => {
c.render_with_prefix(send_time, event_id, &sender, &sender)
}
Audio(c) => c.render_with_prefix(
send_time,
event_id,
&sender,
&self.homeserver,
),
Video(c) => c.render_with_prefix(
send_time,
event_id,
&sender,
&self.homeserver,
),
File(c) => c.render_with_prefix(
send_time,
event_id,
&sender,
&self.homeserver,
),
Image(c) => c.render_with_prefix(
send_time,
event_id,
&sender,
&self.homeserver,
),
_ => return None,
},
_ => return None,
};
Some(rendered)
}
async fn render_sync_message(
&self,
event: &AnySyncMessageEvent,
) -> Option<RenderedEvent> {
// TODO remove this expect.
let sender =
self.members.get(event.sender()).await.expect(
"Rendering a message but the sender isn't in the nicklist",
);
let send_time = event.origin_server_ts();
self.render_message_content(
event.event_id(),
send_time,
&sender,
&event.content(),
)
.await
.map(|r| {
// TODO the tags are different if the room is a DM.
if sender.user_id() == &*self.own_user_id {
r.add_self_tags()
} else {
r.add_msg_tags()
}
})
}
// Add the content of the message to our outgoing messag queue and print out
// a local echo line if local echo is enabled.
async fn queue_outgoing_message(
&self,
uuid: Uuid,
content: &MessageEventContent,
) {
if self.config.borrow().look().local_echo() {
if let MessageEventContent::Text(c) = content {
let sender =
self.members.get(&self.own_user_id).await.unwrap_or_else(
|| panic!("No own member {}", self.own_user_id),
);
let local_echo = c
.render_with_prefix_for_echo(&sender, uuid, &())
.add_self_tags();
self.print_rendered_event(local_echo);
self.outgoing_messages.add_with_echo(uuid, content.clone());
} else {
self.outgoing_messages.add(uuid, content.clone());
}
} else {
self.outgoing_messages.add(uuid, content.clone());
}
}
/// Send the given content to the server.
///
/// # Arguments
///
/// * `content` - The content that should be sent to the server.
///
/// # Examples
///
/// ```
/// let content = MessageEventContent::Text(TextMessageEventContent {
/// body: "Hello world".to_owned(),
/// formatted: None,
/// relates_to: None,
/// });
/// let content = AnyMessageEventContent::RoomMessage(content);
///
/// buffer.send_message(content).await
/// ```
pub async fn send_message(&self, content: MessageEventContent) {
let uuid = Uuid::new_v4();
if let Some(c) = &*self.connection.borrow() {
self.queue_outgoing_message(uuid, &content).await;
match c
.send_message(
&self.room_id,
AnyMessageEventContent::RoomMessage(content),
Some(uuid),
)
.await
{
Ok(r) => {
self.handle_outgoing_message(uuid, &r.event_id).await;
}
Err(_e) => {
// TODO print out an error, remember to modify the local
// echo line if there is one.
self.outgoing_messages.remove(uuid);
}
}
} else if let Ok(buffer) = self.buffer_handle().upgrade() {
buffer.print("Error not connected");
}
}
/// Send out a typing notice.
///
/// This will send out a typing notice or reset the one in progress, if
/// needed. It will make sure that only one typing notice request is in
/// flight at a time.
///
/// Typing notices are sent out only if we have more than 4 letters in the
/// input and the input isn't a command.
///
/// If the input is empty the typing notice is disabled.
pub fn update_typing_notice(&self) {
let typing_in_flight = self.typing_in_flight.clone();
let buffer_handle = self.buffer_handle();
let buffer = if let Ok(b) = buffer_handle.upgrade() {
b
} else {
return;
};
let input = buffer.input();
if input.starts_with('/') && !input.starts_with("//") {
// Don't send typing notices for commands.
return;
}
let connection = self.connection.clone();
let room_id = self.room_id.clone();
let typing_notice_time = self.typing_notice_time.clone();
let send = |typing: bool| async move {
let typing_time = typing_notice_time;
// We're in the process of sending out a typing notice, so don't
// make the same request twice.
let guard = match typing_in_flight.try_lock() {
Ok(guard) => guard,
Err(_) => {
return;
}
};
if let Some(connection) = &*connection.borrow() {
let response =
connection.send_typing_notice(&*room_id, typing).await;
// We need to record the time when the last typing notice was
// sent to ensure we don't send out new ones while a previous
// one is active. If we cancelled the last notice (`!typing`),
// we record that there is currently no active notice.
//
// An unsuccessful response indicates the send operation failed.
// In this case we need to retry, so we don't update anything.
if response.is_ok() {
if typing {
*typing_time.borrow_mut() = Some(Instant::now());
} else {
*typing_time.borrow_mut() = None;
}
}
};
drop(guard)
};
let typing_time = self.typing_notice_time.borrow_mut();
if input.len() < 4 && typing_time.is_some() {
// If we have an active typing notice and our input is short, e.g.
// we removed the input set the typing notice to false.
Weechat::spawn(send(false)).detach();
} else if input.len() >= 4 {
if let Some(typing_time) = &*typing_time {
// If we have some valid input, check if the typing notice
// expired and send one out if it indeed expired.
if typing_time.elapsed() > TYPING_NOTICE_TIMEOUT {
Weechat::spawn(send(true)).detach();
}
} else {
// If we have some valid input and no active typing notice, send
// one out.
Weechat::spawn(send(true)).detach();
}
}
}
pub fn is_busy(&self) -> bool {
self.messages_in_flight.locked()
}
pub fn reset_prev_batch(&self) {
// TODO we'll want to be able to scroll up again after we clear the
// buffer.
*self.prev_batch.borrow_mut() = None;
}
pub async fn get_messages(&self) {
let messages_lock = self.messages_in_flight.clone();
let connection = self.connection.borrow().as_ref().cloned();
let room_id = self.room_id().clone();
let prev_batch =
if let Some(p) = self.prev_batch.borrow().as_ref().cloned() {
p
} else {
return;
};
let guard = if let Ok(l) = messages_lock.try_lock() {
l
} else {
return;
};
Weechat::bar_item_update("buffer_modes");
Weechat::bar_item_update("matrix_modes");
if let Some(connection) = connection {
if let Ok(r) = connection.room_messages(room_id, prev_batch).await {
for event in r.chunk.iter().filter_map(|e| e.deserialize().ok())
{
self.handle_room_event(&event).await;
}
let mut prev_batch = self.prev_batch.borrow_mut();
if let Some(PrevBatch::Forward(t)) = prev_batch.as_ref() {
*prev_batch = Some(PrevBatch::Backwards(t.to_owned()));
self.sort_messages();
} else if r.chunk.is_empty() {
*prev_batch = None;
} else {
*prev_batch = r.end.map(PrevBatch::Backwards);
self.sort_messages();
}
}
}
drop(guard);
Weechat::bar_item_update("buffer_modes");
Weechat::bar_item_update("matrix_modes");
}
fn sort_messages(&self) {
struct LineCopy {
date: i64,
date_printed: i64,
tags: Vec<String>,
prefix: String,
message: String,
}
impl<'a> From<BufferLine<'a>> for LineCopy {
fn from(line: BufferLine) -> Self {
Self {
date: line.date(),
date_printed: line.date_printed(),
message: line.message().to_string(),
prefix: line.prefix().to_string(),
tags: line.tags().iter().map(|t| t.to_string()).collect(),
}
}
}
// TODO update the highlight once Weechat starts supporting it.
if let Ok(buffer) = self.buffer_handle().upgrade() {
let mut lines: Vec<LineCopy> =
buffer.lines().map(|l| l.into()).collect();
lines.sort_by_key(|l| l.date);
for (line, new) in buffer.lines().zip(lines.drain(..)) {
let tags =
new.tags.iter().map(|t| t.as_str()).collect::<Vec<&str>>();
let data = LineData {
prefix: Some(&new.prefix),
message: Some(&new.message),
date: Some(new.date),
date_printed: Some(new.date_printed),
tags: Some(&tags),
};
line.update(data)
}
}
}
/// Replace the local echo of an event with a fully rendered one.
fn replace_local_echo(
&self,
uuid: Uuid,
buffer: &Buffer,
rendered: RenderedEvent,
) {
let uuid_tag = Cow::from(format!("matrix_echo_{}", uuid.to_string()));
let line_contains_uuid = |l: &BufferLine| l.tags().contains(&uuid_tag);
let mut lines = buffer.lines();
let mut first_line = lines.rfind(line_contains_uuid);
// We go in reverse order here since we also use rfind(). We got from
// the bottom of the buffer to the top since we're expecting these
// lines to be freshly printed and thus at the bottom.
let mut line_num = rendered.content.lines.len() - 1;
while let Some(line) = &first_line {
let rendered_line = &rendered.content.lines[line_num];
line.set_message(&rendered_line.message);
line_num -= 1;
first_line = lines.next_back().filter(line_contains_uuid);
}
}
async fn handle_outgoing_message(&self, uuid: Uuid, event_id: &EventId) {
if let Some((echo, content)) = self.outgoing_messages.remove(uuid) {
let event = SyncMessageEvent {
sender: (&*self.own_user_id).clone(),
origin_server_ts: std::time::SystemTime::now(),
event_id: event_id.clone(),
content,
unsigned: Default::default(),
};
let event = AnySyncMessageEvent::RoomMessage(event);
let rendered = self
.render_sync_message(&event)
.await
.expect("Sent out an event that we don't know how to render");
if let Ok(buffer) = self.buffer_handle().upgrade() {
if echo {
self.replace_local_echo(uuid, &buffer, rendered);
} else {
self.print_rendered_event(rendered);
}
}
}
}
fn set_topic(&self) {
if let Ok(buffer) = self.buffer_handle().upgrade() {
buffer.set_title(&self.room().topic().unwrap_or_default());
}
}
fn set_alias(&self) {
if let Some(alias) = self.alias() {
if let Ok(b) = self.buffer_handle().upgrade() {
b.set_localvar("alias", alias.as_str());
}
}
}
fn update_buffer_name(&self) {
self.members.update_buffer_name();
}
async fn replace_event(&self, event_id: &EventId, event: RenderedEvent) {
use std::cmp::Ordering;
if let Ok(buffer) = self.buffer_handle().upgrade() {
let event_id_tag = Cow::from(format!("matrix_id_{}", event_id));
let lines: Vec<BufferLine> = buffer
.lines()
.filter(|l| l.tags().contains(&event_id_tag))
.collect();
let date = lines.get(0).map(|l| l.date()).unwrap_or_default();
for (line, new) in lines.iter().zip(event.content.lines.iter()) {
let tags: Vec<&str> =
new.tags.iter().map(|t| t.as_str()).collect();
let data = LineData {
prefix: Some(&event.prefix),
message: Some(&new.message),
tags: Some(&tags),
..Default::default()
};
line.update(data);
}
match lines.len().cmp(&event.content.lines.len()) {
Ordering::Greater => {
for line in &lines[event.content.lines.len()..] {
line.set_message("");
}
}
Ordering::Less => {
for line in &event.content.lines[lines.len()..] {
let message =
format!("{}{}", &event.prefix, &line.message);
let tags: Vec<&str> =
line.tags.iter().map(|t| t.as_str()).collect();
buffer.print_date_tags(date, &tags, &message)
}
self.sort_messages()
}
_ => (),
}
}
}
async fn handle_edits(&self, event: &AnySyncMessageEvent) {
// TODO remove this expect.
let sender =
self.members.get(event.sender()).await.expect(
"Rendering a message but the sender isn't in the nicklist",
);
if let Some((event_id, content)) = event.get_edit() {
let send_time = event.origin_server_ts();
if let Some(rendered) = self
.render_message_content(
event_id,
send_time,
&sender,
&AnyMessageEventContent::RoomMessage(content.clone()),
)
.await
.map(|r| {
// TODO the tags are different if the room is a DM.
if sender.user_id() == &*self.own_user_id {
r.add_self_tags()
} else {
r.add_msg_tags()
}
})
{
self.replace_event(event_id, rendered).await;
}
}
}
async fn handle_room_message(&self, event: &AnySyncMessageEvent) {
// If the event has a transaction id it's an event that we sent out
// ourselves, the content will be in the outgoing message queue and it
// may have been printed out as a local echo.
if let Some(id) = &event.unsigned().transaction_id {
if let Ok(id) = Uuid::parse_str(id) {
self.handle_outgoing_message(id, event.event_id()).await;