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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
|
#include "TimelineModel.h"
#include <algorithm>
#include <thread>
#include <type_traits>
#include <QCache>
#include <QDesktopServices>
#include <QFileDialog>
#include <QMimeDatabase>
#include <QRegularExpression>
#include <QSettings>
#include <QStandardPaths>
#include "ChatPage.h"
#include "EventAccessors.h"
#include "Logging.h"
#include "MainWindow.h"
#include "MatrixClient.h"
#include "MxcImageProvider.h"
#include "Olm.h"
#include "TimelineViewManager.h"
#include "Utils.h"
#include "dialogs/RawMessage.h"
Q_DECLARE_METATYPE(QModelIndex)
namespace std {
inline uint
qHash(const std::string &key, uint seed = 0)
{
return qHash(QByteArray::fromRawData(key.data(), (int)key.length()), seed);
}
}
namespace {
struct RoomEventType
{
template<class T>
qml_mtx_events::EventType operator()(const mtx::events::Event<T> &e)
{
using mtx::events::EventType;
switch (e.type) {
case EventType::RoomKeyRequest:
return qml_mtx_events::EventType::KeyRequest;
case EventType::Reaction:
return qml_mtx_events::EventType::Reaction;
case EventType::RoomAliases:
return qml_mtx_events::EventType::Aliases;
case EventType::RoomAvatar:
return qml_mtx_events::EventType::Avatar;
case EventType::RoomCanonicalAlias:
return qml_mtx_events::EventType::CanonicalAlias;
case EventType::RoomCreate:
return qml_mtx_events::EventType::RoomCreate;
case EventType::RoomEncrypted:
return qml_mtx_events::EventType::Encrypted;
case EventType::RoomEncryption:
return qml_mtx_events::EventType::Encryption;
case EventType::RoomGuestAccess:
return qml_mtx_events::EventType::RoomGuestAccess;
case EventType::RoomHistoryVisibility:
return qml_mtx_events::EventType::RoomHistoryVisibility;
case EventType::RoomJoinRules:
return qml_mtx_events::EventType::RoomJoinRules;
case EventType::RoomMember:
return qml_mtx_events::EventType::Member;
case EventType::RoomMessage:
return qml_mtx_events::EventType::UnknownMessage;
case EventType::RoomName:
return qml_mtx_events::EventType::Name;
case EventType::RoomPowerLevels:
return qml_mtx_events::EventType::PowerLevels;
case EventType::RoomTopic:
return qml_mtx_events::EventType::Topic;
case EventType::RoomTombstone:
return qml_mtx_events::EventType::Tombstone;
case EventType::RoomRedaction:
return qml_mtx_events::EventType::Redaction;
case EventType::RoomPinnedEvents:
return qml_mtx_events::EventType::PinnedEvents;
case EventType::Sticker:
return qml_mtx_events::EventType::Sticker;
case EventType::Tag:
return qml_mtx_events::EventType::Tag;
case EventType::Unsupported:
return qml_mtx_events::EventType::Unsupported;
default:
return qml_mtx_events::EventType::UnknownMessage;
}
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Audio> &)
{
return qml_mtx_events::EventType::AudioMessage;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Emote> &)
{
return qml_mtx_events::EventType::EmoteMessage;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::File> &)
{
return qml_mtx_events::EventType::FileMessage;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Image> &)
{
return qml_mtx_events::EventType::ImageMessage;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Notice> &)
{
return qml_mtx_events::EventType::NoticeMessage;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Text> &)
{
return qml_mtx_events::EventType::TextMessage;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Video> &)
{
return qml_mtx_events::EventType::VideoMessage;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationRequest> &)
{
return qml_mtx_events::EventType::KeyVerificationRequest;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationStart> &)
{
return qml_mtx_events::EventType::KeyVerificationStart;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationMac> &)
{
return qml_mtx_events::EventType::KeyVerificationMac;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationAccept> &)
{
return qml_mtx_events::EventType::KeyVerificationAccept;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationReady> &)
{
return qml_mtx_events::EventType::KeyVerificationReady;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationCancel> &)
{
return qml_mtx_events::EventType::KeyVerificationCancel;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationKey> &)
{
return qml_mtx_events::EventType::KeyVerificationKey;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::KeyVerificationDone> &)
{
return qml_mtx_events::EventType::KeyVerificationDone;
}
qml_mtx_events::EventType operator()(const mtx::events::Event<mtx::events::msg::Redacted> &)
{
return qml_mtx_events::EventType::Redacted;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::CallInvite> &)
{
return qml_mtx_events::EventType::CallInvite;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::CallAnswer> &)
{
return qml_mtx_events::EventType::CallAnswer;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::CallHangUp> &)
{
return qml_mtx_events::EventType::CallHangUp;
}
qml_mtx_events::EventType operator()(
const mtx::events::Event<mtx::events::msg::CallCandidates> &)
{
return qml_mtx_events::EventType::CallCandidates;
}
// ::EventType::Type operator()(const Event<mtx::events::msg::Location> &e) { return
// ::EventType::LocationMessage; }
};
}
qml_mtx_events::EventType
toRoomEventType(const mtx::events::collections::TimelineEvents &event)
{
return std::visit(RoomEventType{}, event);
}
QString
toRoomEventTypeString(const mtx::events::collections::TimelineEvents &event)
{
return std::visit([](const auto &e) { return QString::fromStdString(to_string(e.type)); },
event);
}
TimelineModel::TimelineModel(TimelineViewManager *manager, QString room_id, QObject *parent)
: QAbstractListModel(parent)
, events(room_id.toStdString(), this)
, room_id_(room_id)
, manager_(manager)
{
connect(
this,
&TimelineModel::redactionFailed,
this,
[](const QString &msg) { emit ChatPage::instance()->showNotification(msg); },
Qt::QueuedConnection);
connect(this,
&TimelineModel::newMessageToSend,
this,
&TimelineModel::addPendingMessage,
Qt::QueuedConnection);
connect(this, &TimelineModel::addPendingMessageToStore, &events, &EventStore::addPending);
connect(
&events,
&EventStore::dataChanged,
this,
[this](int from, int to) {
nhlog::ui()->debug(
"data changed {} to {}", events.size() - to - 1, events.size() - from - 1);
emit dataChanged(index(events.size() - to - 1, 0),
index(events.size() - from - 1, 0));
},
Qt::QueuedConnection);
connect(&events, &EventStore::beginInsertRows, this, [this](int from, int to) {
int first = events.size() - to;
int last = events.size() - from;
if (from >= events.size()) {
int batch_size = to - from;
first += batch_size;
last += batch_size;
} else {
first -= 1;
last -= 1;
}
nhlog::ui()->debug("begin insert from {} to {}", first, last);
beginInsertRows(QModelIndex(), first, last);
});
connect(&events, &EventStore::endInsertRows, this, [this]() { endInsertRows(); });
connect(&events, &EventStore::beginResetModel, this, [this]() { beginResetModel(); });
connect(&events, &EventStore::endResetModel, this, [this]() { endResetModel(); });
connect(&events, &EventStore::newEncryptedImage, this, &TimelineModel::newEncryptedImage);
connect(
&events, &EventStore::fetchedMore, this, [this]() { setPaginationInProgress(false); });
connect(&events,
&EventStore::startDMVerification,
this,
[this](mtx::events::RoomEvent<mtx::events::msg::KeyVerificationRequest> msg) {
ChatPage::instance()->receivedRoomDeviceVerificationRequest(msg, this);
});
connect(&events, &EventStore::updateFlowEventId, this, [this](std::string event_id) {
this->updateFlowEventId(event_id);
});
}
QHash<int, QByteArray>
TimelineModel::roleNames() const
{
return {
{Type, "type"},
{TypeString, "typeString"},
{IsOnlyEmoji, "isOnlyEmoji"},
{Body, "body"},
{FormattedBody, "formattedBody"},
{PreviousMessageUserId, "previousMessageUserId"},
{UserId, "userId"},
{UserName, "userName"},
{PreviousMessageDay, "previousMessageDay"},
{Day, "day"},
{Timestamp, "timestamp"},
{Url, "url"},
{ThumbnailUrl, "thumbnailUrl"},
{Blurhash, "blurhash"},
{Filename, "filename"},
{Filesize, "filesize"},
{MimeType, "mimetype"},
{Height, "height"},
{Width, "width"},
{ProportionalHeight, "proportionalHeight"},
{Id, "id"},
{State, "state"},
{IsEdited, "isEdited"},
{IsEditable, "isEditable"},
{IsEncrypted, "isEncrypted"},
{IsRoomEncrypted, "isRoomEncrypted"},
{ReplyTo, "replyTo"},
{Reactions, "reactions"},
{RoomId, "roomId"},
{RoomName, "roomName"},
{RoomTopic, "roomTopic"},
{CallType, "callType"},
{Dump, "dump"},
};
}
int
TimelineModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return this->events.size();
}
QVariantMap
TimelineModel::getDump(QString eventId, QString relatedTo) const
{
if (auto event = events.get(eventId.toStdString(), relatedTo.toStdString()))
return data(*event, Dump).toMap();
return {};
}
QVariant
TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int role) const
{
using namespace mtx::accessors;
namespace acc = mtx::accessors;
switch (role) {
case UserId:
return QVariant(QString::fromStdString(acc::sender(event)));
case UserName:
return QVariant(displayName(QString::fromStdString(acc::sender(event))));
case Day: {
QDateTime prevDate = origin_server_ts(event);
prevDate.setTime(QTime());
return QVariant(prevDate.toMSecsSinceEpoch());
}
case Timestamp:
return QVariant(origin_server_ts(event));
case Type:
return QVariant(toRoomEventType(event));
case TypeString:
return QVariant(toRoomEventTypeString(event));
case IsOnlyEmoji: {
QString qBody = QString::fromStdString(body(event));
QVector<uint> utf32_string = qBody.toUcs4();
int emojiCount = 0;
for (auto &code : utf32_string) {
if (utils::codepointIsEmoji(code)) {
emojiCount++;
} else {
return QVariant(0);
}
}
return QVariant(emojiCount);
}
case Body:
return QVariant(
utils::replaceEmoji(QString::fromStdString(body(event)).toHtmlEscaped()));
case FormattedBody: {
const static QRegularExpression replyFallback(
"<mx-reply>.*</mx-reply>", QRegularExpression::DotMatchesEverythingOption);
bool isReply = relations(event).reply_to().has_value();
auto formattedBody_ = QString::fromStdString(formatted_body(event));
if (formattedBody_.isEmpty()) {
auto body_ = QString::fromStdString(body(event));
if (isReply) {
while (body_.startsWith("> "))
body_ = body_.right(body_.size() - body_.indexOf('\n') - 1);
if (body_.startsWith('\n'))
body_ = body_.right(body_.size() - 1);
}
formattedBody_ = body_.toHtmlEscaped().replace('\n', "<br>");
} else {
if (isReply)
formattedBody_ = formattedBody_.remove(replyFallback);
}
formattedBody_.replace("<img src=\"mxc://", "<img src=\"image://mxcImage/");
formattedBody_.replace("<img src=\"mxc://", "<img src=\"image://mxcImage/");
return QVariant(utils::replaceEmoji(
utils::linkifyMessage(utils::escapeBlacklistedHtml(formattedBody_))));
}
case Url:
return QVariant(QString::fromStdString(url(event)));
case ThumbnailUrl:
return QVariant(QString::fromStdString(thumbnail_url(event)));
case Blurhash:
return QVariant(QString::fromStdString(blurhash(event)));
case Filename:
return QVariant(QString::fromStdString(filename(event)));
case Filesize:
return QVariant(utils::humanReadableFileSize(filesize(event)));
case MimeType:
return QVariant(QString::fromStdString(mimetype(event)));
case Height:
return QVariant(qulonglong{media_height(event)});
case Width:
return QVariant(qulonglong{media_width(event)});
case ProportionalHeight: {
auto w = media_width(event);
if (w == 0)
w = 1;
double prop = media_height(event) / (double)w;
return QVariant(prop > 0 ? prop : 1.);
}
case Id: {
if (auto replaces = relations(event).replaces())
return QVariant(QString::fromStdString(replaces.value()));
else
return QVariant(QString::fromStdString(event_id(event)));
}
case State: {
auto id = QString::fromStdString(event_id(event));
auto containsOthers = [](const auto &vec) {
for (const auto &e : vec)
if (e.second != http::client()->user_id().to_string())
return true;
return false;
};
// only show read receipts for messages not from us
if (acc::sender(event) != http::client()->user_id().to_string())
return qml_mtx_events::Empty;
else if (!id.isEmpty() && id[0] == "m")
return qml_mtx_events::Sent;
else if (read.contains(id) || containsOthers(cache::readReceipts(id, room_id_)))
return qml_mtx_events::Read;
else
return qml_mtx_events::Received;
}
case IsEdited:
return QVariant(relations(event).replaces().has_value());
case IsEditable:
return QVariant(!is_state_event(event) && mtx::accessors::sender(event) ==
http::client()->user_id().to_string());
case IsEncrypted: {
auto id = event_id(event);
auto encrypted_event = events.get(id, id, false);
return encrypted_event &&
std::holds_alternative<
mtx::events::EncryptedEvent<mtx::events::msg::Encrypted>>(
*encrypted_event);
}
case IsRoomEncrypted: {
return cache::isRoomEncrypted(room_id_.toStdString());
}
case ReplyTo:
return QVariant(QString::fromStdString(relations(event).reply_to().value_or("")));
case Reactions: {
auto id = relations(event).replaces().value_or(event_id(event));
return QVariant::fromValue(events.reactions(id));
}
case RoomId:
return QVariant(room_id_);
case RoomName:
return QVariant(QString::fromStdString(room_name(event)));
case RoomTopic:
return QVariant(QString::fromStdString(room_topic(event)));
case CallType:
return QVariant(QString::fromStdString(call_type(event)));
case Dump: {
QVariantMap m;
auto names = roleNames();
m.insert(names[Type], data(event, static_cast<int>(Type)));
m.insert(names[TypeString], data(event, static_cast<int>(TypeString)));
m.insert(names[IsOnlyEmoji], data(event, static_cast<int>(IsOnlyEmoji)));
m.insert(names[Body], data(event, static_cast<int>(Body)));
m.insert(names[FormattedBody], data(event, static_cast<int>(FormattedBody)));
m.insert(names[UserId], data(event, static_cast<int>(UserId)));
m.insert(names[UserName], data(event, static_cast<int>(UserName)));
m.insert(names[Day], data(event, static_cast<int>(Day)));
m.insert(names[Timestamp], data(event, static_cast<int>(Timestamp)));
m.insert(names[Url], data(event, static_cast<int>(Url)));
m.insert(names[ThumbnailUrl], data(event, static_cast<int>(ThumbnailUrl)));
m.insert(names[Blurhash], data(event, static_cast<int>(Blurhash)));
m.insert(names[Filename], data(event, static_cast<int>(Filename)));
m.insert(names[Filesize], data(event, static_cast<int>(Filesize)));
m.insert(names[MimeType], data(event, static_cast<int>(MimeType)));
m.insert(names[Height], data(event, static_cast<int>(Height)));
m.insert(names[Width], data(event, static_cast<int>(Width)));
m.insert(names[ProportionalHeight],
data(event, static_cast<int>(ProportionalHeight)));
m.insert(names[Id], data(event, static_cast<int>(Id)));
m.insert(names[State], data(event, static_cast<int>(State)));
m.insert(names[IsEncrypted], data(event, static_cast<int>(IsEncrypted)));
m.insert(names[IsRoomEncrypted], data(event, static_cast<int>(IsRoomEncrypted)));
m.insert(names[ReplyTo], data(event, static_cast<int>(ReplyTo)));
m.insert(names[RoomName], data(event, static_cast<int>(RoomName)));
m.insert(names[RoomTopic], data(event, static_cast<int>(RoomTopic)));
m.insert(names[CallType], data(event, static_cast<int>(CallType)));
return QVariant(m);
}
default:
return QVariant();
}
}
QVariant
TimelineModel::data(const QModelIndex &index, int role) const
{
using namespace mtx::accessors;
namespace acc = mtx::accessors;
if (index.row() < 0 && index.row() >= rowCount())
return QVariant();
auto event = events.get(rowCount() - index.row() - 1);
if (!event)
return "";
if (role == PreviousMessageDay || role == PreviousMessageUserId) {
int prevIdx = rowCount() - index.row() - 2;
if (prevIdx < 0)
return QVariant();
auto tempEv = events.get(prevIdx);
if (!tempEv)
return QVariant();
if (role == PreviousMessageUserId)
return data(*tempEv, UserId);
else
return data(*tempEv, Day);
}
return data(*event, role);
}
bool
TimelineModel::canFetchMore(const QModelIndex &) const
{
if (!events.size())
return true;
if (auto first = events.get(0);
first &&
!std::holds_alternative<mtx::events::StateEvent<mtx::events::state::Create>>(*first))
return true;
else
return false;
}
void
TimelineModel::setPaginationInProgress(const bool paginationInProgress)
{
if (m_paginationInProgress == paginationInProgress) {
return;
}
m_paginationInProgress = paginationInProgress;
emit paginationInProgressChanged(m_paginationInProgress);
}
void
TimelineModel::fetchMore(const QModelIndex &)
{
if (m_paginationInProgress) {
nhlog::ui()->warn("Already loading older messages");
return;
}
setPaginationInProgress(true);
events.fetchMore();
}
void
TimelineModel::syncState(const mtx::responses::State &s)
{
using namespace mtx::events;
for (const auto &e : s.events) {
if (std::holds_alternative<StateEvent<state::Avatar>>(e))
emit roomAvatarUrlChanged();
else if (std::holds_alternative<StateEvent<state::Name>>(e))
emit roomNameChanged();
else if (std::holds_alternative<StateEvent<state::Topic>>(e))
emit roomTopicChanged();
else if (std::holds_alternative<StateEvent<state::Member>>(e)) {
emit roomAvatarUrlChanged();
emit roomNameChanged();
}
}
}
void
TimelineModel::addEvents(const mtx::responses::Timeline &timeline)
{
if (timeline.events.empty())
return;
events.handleSync(timeline);
using namespace mtx::events;
for (auto e : timeline.events) {
if (auto encryptedEvent = std::get_if<EncryptedEvent<msg::Encrypted>>(&e)) {
MegolmSessionIndex index;
index.room_id = room_id_.toStdString();
index.session_id = encryptedEvent->content.session_id;
index.sender_key = encryptedEvent->content.sender_key;
auto result = olm::decryptEvent(index, *encryptedEvent);
if (result.event)
e = result.event.value();
}
if (std::holds_alternative<RoomEvent<msg::CallCandidates>>(e) ||
std::holds_alternative<RoomEvent<msg::CallInvite>>(e) ||
std::holds_alternative<RoomEvent<msg::CallAnswer>>(e) ||
std::holds_alternative<RoomEvent<msg::CallHangUp>>(e))
std::visit(
[this](auto &event) {
event.room_id = room_id_.toStdString();
if constexpr (std::is_same_v<std::decay_t<decltype(event)>,
RoomEvent<msg::CallAnswer>> ||
std::is_same_v<std::decay_t<decltype(event)>,
RoomEvent<msg::CallHangUp>>)
emit newCallEvent(event);
else {
if (event.sender != http::client()->user_id().to_string())
emit newCallEvent(event);
}
},
e);
else if (std::holds_alternative<StateEvent<state::Avatar>>(e))
emit roomAvatarUrlChanged();
else if (std::holds_alternative<StateEvent<state::Name>>(e))
emit roomNameChanged();
else if (std::holds_alternative<StateEvent<state::Topic>>(e))
emit roomTopicChanged();
else if (std::holds_alternative<StateEvent<state::Member>>(e)) {
emit roomAvatarUrlChanged();
emit roomNameChanged();
}
}
updateLastMessage();
}
template<typename T>
auto
isMessage(const mtx::events::RoomEvent<T> &e)
-> std::enable_if_t<std::is_same<decltype(e.content.msgtype), std::string>::value, bool>
{
return true;
}
template<typename T>
auto
isMessage(const mtx::events::Event<T> &)
{
return false;
}
template<typename T>
auto
isMessage(const mtx::events::EncryptedEvent<T> &)
{
return true;
}
auto
isMessage(const mtx::events::RoomEvent<mtx::events::msg::CallInvite> &)
{
return true;
}
auto
isMessage(const mtx::events::RoomEvent<mtx::events::msg::CallAnswer> &)
{
return true;
}
auto
isMessage(const mtx::events::RoomEvent<mtx::events::msg::CallHangUp> &)
{
return true;
}
// Workaround. We also want to see a room at the top, if we just joined it
auto
isYourJoin(const mtx::events::StateEvent<mtx::events::state::Member> &e)
{
return e.content.membership == mtx::events::state::Membership::Join &&
e.state_key == http::client()->user_id().to_string();
}
template<typename T>
auto
isYourJoin(const mtx::events::Event<T> &)
{
return false;
}
void
TimelineModel::updateLastMessage()
{
for (auto it = events.size() - 1; it >= 0; --it) {
auto event = events.get(it, decryptDescription);
if (!event)
continue;
if (std::visit([](const auto &e) -> bool { return isYourJoin(e); }, *event)) {
auto time = mtx::accessors::origin_server_ts(*event);
uint64_t ts = time.toMSecsSinceEpoch();
emit manager_->updateRoomsLastMessage(
room_id_,
DescInfo{QString::fromStdString(mtx::accessors::event_id(*event)),
QString::fromStdString(http::client()->user_id().to_string()),
tr("You joined this room."),
utils::descriptiveTime(time),
ts,
time});
return;
}
if (!std::visit([](const auto &e) -> bool { return isMessage(e); }, *event))
continue;
auto description = utils::getMessageDescription(
*event,
QString::fromStdString(http::client()->user_id().to_string()),
cache::displayName(room_id_,
QString::fromStdString(mtx::accessors::sender(*event))));
emit manager_->updateRoomsLastMessage(room_id_, description);
return;
}
}
void
TimelineModel::setCurrentIndex(int index)
{
if (!ChatPage::instance()->isActiveWindow())
return;
auto oldIndex = idToIndex(currentId);
currentId = indexToId(index);
if (index != oldIndex)
emit currentIndexChanged(index);
if (!currentId.startsWith("m")) {
auto oldReadIndex =
cache::getEventIndex(roomId().toStdString(), currentReadId.toStdString());
auto nextEventIndexAndId =
cache::lastInvisibleEventAfter(roomId().toStdString(), currentId.toStdString());
if (nextEventIndexAndId &&
(!oldReadIndex || *oldReadIndex < nextEventIndexAndId->first)) {
readEvent(nextEventIndexAndId->second);
currentReadId = QString::fromStdString(nextEventIndexAndId->second);
nhlog::net()->info("Marked as read {}, index {}, oldReadIndex {}",
nextEventIndexAndId->second,
nextEventIndexAndId->first,
*oldReadIndex);
}
}
}
void
TimelineModel::readEvent(const std::string &id)
{
http::client()->read_event(room_id_.toStdString(), id, [this](mtx::http::RequestErr err) {
if (err) {
nhlog::net()->warn("failed to read_event ({}, {})",
room_id_.toStdString(),
currentId.toStdString());
}
});
}
QString
TimelineModel::displayName(QString id) const
{
return cache::displayName(room_id_, id).toHtmlEscaped();
}
QString
TimelineModel::avatarUrl(QString id) const
{
return cache::avatarUrl(room_id_, id);
}
QString
TimelineModel::formatDateSeparator(QDate date) const
{
auto now = QDateTime::currentDateTime();
QString fmt = QLocale::system().dateFormat(QLocale::LongFormat);
if (now.date().year() == date.year()) {
QRegularExpression rx("[^a-zA-Z]*y+[^a-zA-Z]*");
fmt = fmt.remove(rx);
}
return date.toString(fmt);
}
void
TimelineModel::viewRawMessage(QString id) const
{
auto e = events.get(id.toStdString(), "", false);
if (!e)
return;
std::string ev = mtx::accessors::serialize_event(*e).dump(4);
auto dialog = new dialogs::RawMessage(QString::fromStdString(ev));
Q_UNUSED(dialog);
}
void
TimelineModel::viewDecryptedRawMessage(QString id) const
{
auto e = events.get(id.toStdString(), "");
if (!e)
return;
std::string ev = mtx::accessors::serialize_event(*e).dump(4);
auto dialog = new dialogs::RawMessage(QString::fromStdString(ev));
Q_UNUSED(dialog);
}
void
TimelineModel::openUserProfile(QString userid, bool global)
{
UserProfile *userProfile = new UserProfile(global ? "" : room_id_, userid, manager_, this);
connect(
this, &TimelineModel::roomAvatarUrlChanged, userProfile, &UserProfile::updateAvatarUrl);
emit openProfile(userProfile);
}
void
TimelineModel::replyAction(QString id)
{
setReply(id);
}
void
TimelineModel::editAction(QString id)
{
setEdit(id);
}
RelatedInfo
TimelineModel::relatedInfo(QString id)
{
auto event = events.get(id.toStdString(), "");
if (!event)
return {};
RelatedInfo related = {};
related.quoted_user = QString::fromStdString(mtx::accessors::sender(*event));
related.related_event = mtx::accessors::event_id(*event);
related.type = mtx::accessors::msg_type(*event);
// get body, strip reply fallback, then transform the event to text, if it is a media event
// etc
related.quoted_body = QString::fromStdString(mtx::accessors::body(*event));
QRegularExpression plainQuote("^>.*?$\n?", QRegularExpression::MultilineOption);
while (related.quoted_body.startsWith(">"))
related.quoted_body.remove(plainQuote);
if (related.quoted_body.startsWith("\n"))
related.quoted_body.remove(0, 1);
related.quoted_body = utils::getQuoteBody(related);
// get quoted body and strip reply fallback
related.quoted_formatted_body = mtx::accessors::formattedBodyWithFallback(*event);
related.quoted_formatted_body.remove(QRegularExpression(
"<mx-reply>.*</mx-reply>", QRegularExpression::DotMatchesEverythingOption));
related.room = room_id_;
return related;
}
void
TimelineModel::readReceiptsAction(QString id) const
{
MainWindow::instance()->openReadReceiptsDialog(id);
}
void
TimelineModel::redactEvent(QString id)
{
if (!id.isEmpty())
http::client()->redact_event(
room_id_.toStdString(),
id.toStdString(),
[this, id](const mtx::responses::EventId &, mtx::http::RequestErr err) {
if (err) {
emit redactionFailed(
tr("Message redaction failed: %1")
.arg(QString::fromStdString(err->matrix_error.error)));
return;
}
emit eventRedacted(id);
});
}
int
TimelineModel::idToIndex(QString id) const
{
if (id.isEmpty())
return -1;
auto idx = events.idToIndex(id.toStdString());
if (idx)
return events.size() - *idx - 1;
else
return -1;
}
QString
TimelineModel::indexToId(int index) const
{
auto id = events.indexToId(events.size() - index - 1);
return id ? QString::fromStdString(*id) : "";
}
// Note: this will only be called for our messages
void
TimelineModel::markEventsAsRead(const std::vector<QString> &event_ids)
{
for (const auto &id : event_ids) {
read.insert(id);
int idx = idToIndex(id);
if (idx < 0) {
return;
}
emit dataChanged(index(idx, 0), index(idx, 0));
}
}
template<typename T>
void
TimelineModel::sendEncryptedMessage(mtx::events::RoomEvent<T> msg, mtx::events::EventType eventType)
{
const auto room_id = room_id_.toStdString();
using namespace mtx::events;
using namespace mtx::identifiers;
json doc = {{"type", mtx::events::to_string(eventType)},
{"content", json(msg.content)},
{"room_id", room_id}};
try {
mtx::events::EncryptedEvent<mtx::events::msg::Encrypted> event;
event.content =
olm::encrypt_group_message(room_id, http::client()->device_id(), doc);
event.event_id = msg.event_id;
event.room_id = room_id;
event.sender = http::client()->user_id().to_string();
event.type = mtx::events::EventType::RoomEncrypted;
event.origin_server_ts = QDateTime::currentMSecsSinceEpoch();
emit this->addPendingMessageToStore(event);
// TODO: Let the user know about the errors.
} catch (const lmdb::error &e) {
nhlog::db()->critical(
"failed to open outbound megolm session ({}): {}", room_id, e.what());
emit ChatPage::instance()->showNotification(
tr("Failed to encrypt event, sending aborted!"));
} catch (const mtx::crypto::olm_exception &e) {
nhlog::crypto()->critical(
"failed to open outbound megolm session ({}): {}", room_id, e.what());
emit ChatPage::instance()->showNotification(
tr("Failed to encrypt event, sending aborted!"));
}
}
struct SendMessageVisitor
{
explicit SendMessageVisitor(TimelineModel *model)
: model_(model)
{}
template<typename T, mtx::events::EventType Event>
void sendRoomEvent(mtx::events::RoomEvent<T> msg)
{
if (cache::isRoomEncrypted(model_->room_id_.toStdString())) {
auto encInfo = mtx::accessors::file(msg);
if (encInfo)
emit model_->newEncryptedImage(encInfo.value());
model_->sendEncryptedMessage(msg, Event);
} else {
msg.type = Event;
emit model_->addPendingMessageToStore(msg);
}
}
// Do-nothing operator for all unhandled events
template<typename T>
void operator()(const mtx::events::Event<T> &)
{}
// Operator for m.room.message events that contain a msgtype in their content
template<typename T,
std::enable_if_t<std::is_same<decltype(T::msgtype), std::string>::value, int> = 0>
void operator()(mtx::events::RoomEvent<T> msg)
{
sendRoomEvent<T, mtx::events::EventType::RoomMessage>(msg);
}
// Special operator for reactions, which are a type of m.room.message, but need to be
// handled distinctly for their differences from normal room messages. Specifically,
// reactions need to have the relation outside of ciphertext, or synapse / the homeserver
// cannot handle it correctly. See the MSC for more details:
// https://github.com/matrix-org/matrix-doc/blob/matthew/msc1849/proposals/1849-aggregations.md#end-to-end-encryption
void operator()(mtx::events::RoomEvent<mtx::events::msg::Reaction> msg)
{
msg.type = mtx::events::EventType::Reaction;
emit model_->addPendingMessageToStore(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::CallInvite> &event)
{
sendRoomEvent<mtx::events::msg::CallInvite, mtx::events::EventType::CallInvite>(
event);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::CallCandidates> &event)
{
sendRoomEvent<mtx::events::msg::CallCandidates,
mtx::events::EventType::CallCandidates>(event);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::CallAnswer> &event)
{
sendRoomEvent<mtx::events::msg::CallAnswer, mtx::events::EventType::CallAnswer>(
event);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::CallHangUp> &event)
{
sendRoomEvent<mtx::events::msg::CallHangUp, mtx::events::EventType::CallHangUp>(
event);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationRequest> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationRequest,
mtx::events::EventType::RoomMessage>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationReady> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationReady,
mtx::events::EventType::KeyVerificationReady>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationStart> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationStart,
mtx::events::EventType::KeyVerificationStart>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationAccept> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationAccept,
mtx::events::EventType::KeyVerificationAccept>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationMac> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationMac,
mtx::events::EventType::KeyVerificationMac>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationKey> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationKey,
mtx::events::EventType::KeyVerificationKey>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationDone> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationDone,
mtx::events::EventType::KeyVerificationDone>(msg);
}
void operator()(const mtx::events::RoomEvent<mtx::events::msg::KeyVerificationCancel> &msg)
{
sendRoomEvent<mtx::events::msg::KeyVerificationCancel,
mtx::events::EventType::KeyVerificationCancel>(msg);
}
TimelineModel *model_;
};
void
TimelineModel::addPendingMessage(mtx::events::collections::TimelineEvents event)
{
std::visit(
[](auto &msg) {
msg.type = mtx::events::EventType::RoomMessage;
msg.event_id = "m" + http::client()->generate_txn_id();
msg.sender = http::client()->user_id().to_string();
msg.origin_server_ts = QDateTime::currentMSecsSinceEpoch();
},
event);
std::visit(SendMessageVisitor{this}, event);
}
void
TimelineModel::openMedia(QString eventId)
{
cacheMedia(eventId, [](QString filename) {
QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
});
}
bool
TimelineModel::saveMedia(QString eventId) const
{
mtx::events::collections::TimelineEvents *event = events.get(eventId.toStdString(), "");
if (!event)
return false;
QString mxcUrl = QString::fromStdString(mtx::accessors::url(*event));
QString originalFilename = QString::fromStdString(mtx::accessors::filename(*event));
QString mimeType = QString::fromStdString(mtx::accessors::mimetype(*event));
auto encryptionInfo = mtx::accessors::file(*event);
qml_mtx_events::EventType eventType = toRoomEventType(*event);
QString dialogTitle;
if (eventType == qml_mtx_events::EventType::ImageMessage) {
dialogTitle = tr("Save image");
} else if (eventType == qml_mtx_events::EventType::VideoMessage) {
dialogTitle = tr("Save video");
} else if (eventType == qml_mtx_events::EventType::AudioMessage) {
dialogTitle = tr("Save audio");
} else {
dialogTitle = tr("Save file");
}
const QString filterString = QMimeDatabase().mimeTypeForName(mimeType).filterString();
const QString downloadsFolder =
QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
const QString openLocation = downloadsFolder + "/" + originalFilename;
const QString filename = QFileDialog::getSaveFileName(
manager_->getWidget(), dialogTitle, openLocation, filterString);
if (filename.isEmpty())
return false;
const auto url = mxcUrl.toStdString();
http::client()->download(
url,
[filename, url, encryptionInfo](const std::string &data,
const std::string &,
const std::string &,
mtx::http::RequestErr err) {
if (err) {
nhlog::net()->warn("failed to retrieve image {}: {} {}",
url,
err->matrix_error.error,
static_cast<int>(err->status_code));
return;
}
try {
auto temp = data;
if (encryptionInfo)
temp = mtx::crypto::to_string(
mtx::crypto::decrypt_file(temp, encryptionInfo.value()));
QFile file(filename);
if (!file.open(QIODevice::WriteOnly))
return;
file.write(QByteArray(temp.data(), (int)temp.size()));
file.close();
return;
} catch (const std::exception &e) {
nhlog::ui()->warn("Error while saving file to: {}", e.what());
}
});
return true;
}
void
TimelineModel::cacheMedia(QString eventId, std::function<void(const QString)> callback)
{
mtx::events::collections::TimelineEvents *event = events.get(eventId.toStdString(), "");
if (!event)
return;
QString mxcUrl = QString::fromStdString(mtx::accessors::url(*event));
QString originalFilename = QString::fromStdString(mtx::accessors::filename(*event));
QString mimeType = QString::fromStdString(mtx::accessors::mimetype(*event));
auto encryptionInfo = mtx::accessors::file(*event);
// If the message is a link to a non mxcUrl, don't download it
if (!mxcUrl.startsWith("mxc://")) {
emit mediaCached(mxcUrl, mxcUrl);
return;
}
QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix();
const auto url = mxcUrl.toStdString();
const auto name = QString(mxcUrl).remove("mxc://");
QFileInfo filename(QString("%1/media_cache/%2.%3")
.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
.arg(name)
.arg(suffix));
if (QDir::cleanPath(name) != name) {
nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url);
return;
}
QDir().mkpath(filename.path());
if (filename.isReadable()) {
emit mediaCached(mxcUrl, filename.filePath());
if (callback) {
callback(filename.filePath());
}
return;
}
http::client()->download(
url,
[this, callback, mxcUrl, filename, url, encryptionInfo](const std::string &data,
const std::string &,
const std::string &,
mtx::http::RequestErr err) {
if (err) {
nhlog::net()->warn("failed to retrieve image {}: {} {}",
url,
err->matrix_error.error,
static_cast<int>(err->status_code));
return;
}
try {
auto temp = data;
if (encryptionInfo)
temp = mtx::crypto::to_string(
mtx::crypto::decrypt_file(temp, encryptionInfo.value()));
QFile file(filename.filePath());
if (!file.open(QIODevice::WriteOnly))
return;
file.write(QByteArray(temp.data(), (int)temp.size()));
file.close();
if (callback) {
callback(filename.filePath());
}
} catch (const std::exception &e) {
nhlog::ui()->warn("Error while saving file to: {}", e.what());
}
emit mediaCached(mxcUrl, filename.filePath());
});
}
void
TimelineModel::cacheMedia(QString eventId)
{
cacheMedia(eventId, NULL);
}
QString
TimelineModel::formatTypingUsers(const std::vector<QString> &users, QColor bg)
{
QString temp =
tr("%1 and %2 are typing.",
"Multiple users are typing. First argument is a comma separated list of potentially "
"multiple users. Second argument is the last user of that list. (If only one user is "
"typing, %1 is empty. You should still use it in your string though to silence Qt "
"warnings.)",
(int)users.size());
if (users.empty()) {
return "";
}
QStringList uidWithoutLast;
auto formatUser = [this, bg](const QString &user_id) -> QString {
auto uncoloredUsername = utils::replaceEmoji(displayName(user_id));
QString prefix =
QString("<font color=\"%1\">").arg(manager_->userColor(user_id, bg).name());
// color only parts that don't have a font already specified
QString coloredUsername;
int index = 0;
do {
auto startIndex = uncoloredUsername.indexOf("<font", index);
if (startIndex - index != 0)
coloredUsername +=
prefix +
uncoloredUsername.midRef(
index, startIndex > 0 ? startIndex - index : -1) +
"</font>";
auto endIndex = uncoloredUsername.indexOf("</font>", startIndex);
if (endIndex > 0)
endIndex += sizeof("</font>") - 1;
if (endIndex - startIndex != 0)
coloredUsername +=
uncoloredUsername.midRef(startIndex, endIndex - startIndex);
index = endIndex;
} while (index > 0 && index < uncoloredUsername.size());
return coloredUsername;
};
for (size_t i = 0; i + 1 < users.size(); i++) {
uidWithoutLast.append(formatUser(users[i]));
}
return temp.arg(uidWithoutLast.join(", ")).arg(formatUser(users.back()));
}
QString
TimelineModel::formatJoinRuleEvent(QString id)
{
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e)
return "";
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::JoinRules>>(e);
if (!event)
return "";
QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user));
switch (event->content.join_rule) {
case mtx::events::state::JoinRule::Public:
return tr("%1 opened the room to the public.").arg(name);
case mtx::events::state::JoinRule::Invite:
return tr("%1 made this room require and invitation to join.").arg(name);
default:
// Currently, knock and private are reserved keywords and not implemented in Matrix.
return "";
}
}
QString
TimelineModel::formatGuestAccessEvent(QString id)
{
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e)
return "";
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::GuestAccess>>(e);
if (!event)
return "";
QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user));
switch (event->content.guest_access) {
case mtx::events::state::AccessState::CanJoin:
return tr("%1 made the room open to guests.").arg(name);
case mtx::events::state::AccessState::Forbidden:
return tr("%1 has closed the room to guest access.").arg(name);
default:
return "";
}
}
QString
TimelineModel::formatHistoryVisibilityEvent(QString id)
{
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e)
return "";
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::HistoryVisibility>>(e);
if (!event)
return "";
QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user));
switch (event->content.history_visibility) {
case mtx::events::state::Visibility::WorldReadable:
return tr("%1 made the room history world readable. Events may be now read by "
"non-joined people.")
.arg(name);
case mtx::events::state::Visibility::Shared:
return tr("%1 set the room history visible to members from this point on.")
.arg(name);
case mtx::events::state::Visibility::Invited:
return tr("%1 set the room history visible to members since they were invited.")
.arg(name);
case mtx::events::state::Visibility::Joined:
return tr("%1 set the room history visible to members since they joined the room.")
.arg(name);
default:
return "";
}
}
QString
TimelineModel::formatPowerLevelEvent(QString id)
{
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e)
return "";
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::PowerLevels>>(e);
if (!event)
return "";
QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user));
// TODO: power levels rendering is actually a bit complex. work on this later.
return tr("%1 has changed the room's permissions.").arg(name);
}
QString
TimelineModel::formatMemberEvent(QString id)
{
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e)
return "";
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::Member>>(e);
if (!event)
return "";
mtx::events::StateEvent<mtx::events::state::Member> *prevEvent = nullptr;
if (!event->unsigned_data.replaces_state.empty()) {
auto tempPrevEvent =
events.get(event->unsigned_data.replaces_state, event->event_id);
if (tempPrevEvent) {
prevEvent =
std::get_if<mtx::events::StateEvent<mtx::events::state::Member>>(
tempPrevEvent);
}
}
QString user = QString::fromStdString(event->state_key);
QString name = utils::replaceEmoji(displayName(user));
QString rendered;
// see table https://matrix.org/docs/spec/client_server/latest#m-room-member
using namespace mtx::events::state;
switch (event->content.membership) {
case Membership::Invite:
rendered = tr("%1 was invited.").arg(name);
break;
case Membership::Join:
if (prevEvent && prevEvent->content.membership == Membership::Join) {
bool displayNameChanged =
prevEvent->content.display_name != event->content.display_name;
bool avatarChanged =
prevEvent->content.avatar_url != event->content.avatar_url;
if (displayNameChanged && avatarChanged)
rendered =
tr("%1 changed their display name and avatar.").arg(name);
else if (displayNameChanged)
rendered = tr("%1 changed their display name.").arg(name);
else if (avatarChanged)
rendered = tr("%1 changed their avatar.").arg(name);
else
rendered = tr("%1 changed some profile info.").arg(name);
// the case of nothing changed but join follows join shouldn't happen, so
// just show it as join
} else {
rendered = tr("%1 joined.").arg(name);
}
break;
case Membership::Leave:
if (!prevEvent) // Should only ever happen temporarily
return "";
if (prevEvent->content.membership == Membership::Invite) {
if (event->state_key == event->sender)
rendered = tr("%1 rejected their invite.").arg(name);
else
rendered = tr("Revoked the invite to %1.").arg(name);
} else if (prevEvent->content.membership == Membership::Join) {
if (event->state_key == event->sender)
rendered = tr("%1 left the room.").arg(name);
else
rendered = tr("Kicked %1.").arg(name);
} else if (prevEvent->content.membership == Membership::Ban) {
rendered = tr("Unbanned %1.").arg(name);
} else if (prevEvent->content.membership == Membership::Knock) {
if (event->state_key == event->sender)
rendered = tr("%1 redacted their knock.").arg(name);
else
rendered = tr("Rejected the knock from %1.").arg(name);
} else
return tr("%1 left after having already left!",
"This is a leave event after the user already left and shouldn't "
"happen apart from state resets")
.arg(name);
break;
case Membership::Ban:
rendered = tr("%1 was banned.").arg(name);
break;
case Membership::Knock:
rendered = tr("%1 knocked.").arg(name);
break;
}
if (event->content.reason != "") {
rendered += tr(" Reason: %1").arg(QString::fromStdString(event->content.reason));
}
return rendered;
}
void
TimelineModel::setEdit(QString newEdit)
{
if (edit_ != newEdit) {
auto ev = events.get(newEdit.toStdString(), "");
if (ev && mtx::accessors::sender(*ev) == http::client()->user_id().to_string()) {
edit_ = newEdit;
emit editChanged(edit_);
setReply(QString::fromStdString(
mtx::accessors::relations(*ev).reply_to().value_or("")));
auto msgType = mtx::accessors::msg_type(*ev);
if (msgType == mtx::events::MessageType::Text ||
msgType == mtx::events::MessageType::Notice) {
input()->setText(relatedInfo(newEdit).quoted_body);
} else if (msgType == mtx::events::MessageType::Emote) {
input()->setText("/me " + relatedInfo(newEdit).quoted_body);
} else {
input()->setText("");
}
} else {
edit_ = "";
emit editChanged(edit_);
input()->setText("");
}
}
}
void
TimelineModel::resetEdit()
{
if (!edit_.isEmpty()) {
edit_ = "";
emit editChanged(edit_);
input()->setText("");
resetReply();
}
}
QString
TimelineModel::roomName() const
{
auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_))
return "";
else
return QString::fromStdString(info[room_id_].name);
}
QString
TimelineModel::roomAvatarUrl() const
{
auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_))
return "";
else
return QString::fromStdString(info[room_id_].avatar_url);
}
QString
TimelineModel::roomTopic() const
{
auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_))
return "";
else
return utils::replaceEmoji(utils::linkifyMessage(
utils::escapeBlacklistedHtml(QString::fromStdString(info[room_id_].topic))));
}
|