Debian Codegraph @

src/timeline/RoomlistModel.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "RoomlistModel.h"
6
7 #include <QClipboard>
8 #include <QGuiApplication>
9
10 #include "Cache.h"
11 #include "Cache_p.h"
12 #include "ChatPage.h"
13 #include "Logging.h"
14 #include "MainWindow.h"
15 #include "MatrixClient.h"
16 #include "MxcImageProvider.h"
17 #include "TimelineModel.h"
18 #include "TimelineViewManager.h"
19 #include "UserSettingsPage.h"
20 #include "Utils.h"
21 #include "voip/CallManager.h"
22
23 #ifdef NHEKO_DBUS_SYS
24 #include <QDBusConnection>
25 #endif
26
27 RoomlistModel::RoomlistModel(TimelineViewManager *parent)
28 : QAbstractListModel(parent)
29 , manager(parent)
30 {
31 connect(ChatPage::instance(), &ChatPage::decryptSidebarChanged, this, [this]() {
32 auto decrypt = ChatPage::instance()->userSettings()->decryptSidebar();
33 QHash<QString, QSharedPointer<TimelineModel>>::iterator i;
34 for (i = models.begin(); i != models.end(); ++i) {
35 auto ptr = i.value();
36
37 if (!ptr.isNull()) {
38 ptr->setDecryptDescription(decrypt);
39 ptr->updateLastMessage();
40 }
41 }
42 });
43
44 connect(this,
45 &RoomlistModel::totalUnreadMessageCountUpdated,
46 ChatPage::instance(),
47 &ChatPage::unreadMessages);
48
49 connect(
50 this,
51 &RoomlistModel::fetchedPreview,
52 this,
53 [this](QString roomid, RoomInfo info) {
54 if (this->previewedRooms.contains(roomid)) {
55 this->previewedRooms.insert(roomid, std::move(info));
56 auto idx = this->roomidToIndex(roomid);
57 emit dataChanged(index(idx),
58 index(idx),
59 {
60 Roles::RoomName,
61 Roles::AvatarUrl,
62 Roles::IsSpace,
63 Roles::IsPreviewFetched,
64 Qt::DisplayRole,
65 });
66 }
67 },
68 Qt::QueuedConnection);
69 }
70
71 QHash<int, QByteArray>
72 RoomlistModel::roleNames() const
73 {
74 return {
75 {AvatarUrl, "avatarUrl"},
76 {RoomName, "roomName"},
77 {RoomId, "roomId"},
78 {LastMessage, "lastMessage"},
79 {Time, "time"},
80 {Timestamp, "timestamp"},
81 {HasUnreadMessages, "hasUnreadMessages"},
82 {HasLoudNotification, "hasLoudNotification"},
83 {NotificationCount, "notificationCount"},
84 {IsInvite, "isInvite"},
85 {IsSpace, "isSpace"},
86 {Tags, "tags"},
87 {ParentSpaces, "parentSpaces"},
88 {IsDirect, "isDirect"},
89 {DirectChatOtherUserId, "directChatOtherUserId"},
90 };
91 }
92
93 QVariant
94 RoomlistModel::data(const QModelIndex &index, int role) const
95 {
96 if (index.row() >= 0 && static_cast<size_t>(index.row()) < roomids.size()) {
97 auto roomid = roomids.at(index.row());
98
99 if (role == Roles::ParentSpaces) {
100 auto parents = cache::client()->getParentRoomIds(roomid.toStdString());
101 QStringList list;
102 list.reserve(static_cast<int>(parents.size()));
103 for (const auto &t : parents)
104 list.push_back(QString::fromStdString(t));
105 return list;
106 } else if (role == Roles::RoomId) {
107 return roomid;
108 } else if (role == Roles::IsDirect) {
109 return directChatToUser.count(roomid) > 0;
110 } else if (role == Roles::DirectChatOtherUserId) {
111 return directChatToUser.count(roomid) ? directChatToUser.at(roomid).front()
112 : QLatin1String("");
113 }
114
115 if (models.contains(roomid)) {
116 auto room = models.value(roomid);
117 switch (role) {
118 case Roles::AvatarUrl:
119 return room->roomAvatarUrl();
120 case Roles::RoomName:
121 return room->plainRoomName();
122 case Roles::LastMessage:
123 return room->lastMessage().body;
124 case Roles::Time:
125 return room->lastMessage().descriptiveTime;
126 case Roles::Timestamp:
127 return QVariant{static_cast<quint64>(room->lastMessageTimestamp())};
128 case Roles::HasUnreadMessages:
129 return this->roomReadStatus.count(roomid) && this->roomReadStatus.at(roomid);
130 case Roles::HasLoudNotification:
131 return room->hasMentions();
132 case Roles::NotificationCount:
133 return room->notificationCount();
134 case Roles::IsInvite:
135 return false;
136 case Roles::IsSpace:
137 return room->isSpace();
138 case Roles::IsPreview:
139 return false;
140 case Roles::Tags: {
141 auto info = cache::singleRoomInfo(roomid.toStdString());
142 QStringList list;
143 list.reserve(static_cast<int>(info.tags.size()));
144 for (const auto &t : info.tags)
145 list.push_back(QString::fromStdString(t));
146 return list;
147 }
148 default:
149 return {};
150 }
151 } else if (invites.contains(roomid)) {
152 auto room = invites.value(roomid);
153 switch (role) {
154 case Roles::AvatarUrl:
155 return QString::fromStdString(room.avatar_url);
156 case Roles::RoomName:
157 return QString::fromStdString(room.name);
158 case Roles::LastMessage:
159 return tr("Pending invite.");
160 case Roles::Time:
161 return QString();
162 case Roles::Timestamp:
163 return QVariant{static_cast<quint64>(0)};
164 case Roles::HasUnreadMessages:
165 case Roles::HasLoudNotification:
166 return false;
167 case Roles::NotificationCount:
168 return 0;
169 case Roles::IsInvite:
170 return true;
171 case Roles::IsSpace:
172 return false;
173 case Roles::IsPreview:
174 return false;
175 case Roles::Tags:
176 return QStringList();
177 default:
178 return {};
179 }
180 } else if (previewedRooms.contains(roomid) && previewedRooms.value(roomid).has_value()) {
181 auto room = previewedRooms.value(roomid).value();
182 switch (role) {
183 case Roles::AvatarUrl:
184 return QString::fromStdString(room.avatar_url);
185 case Roles::RoomName:
186 return QString::fromStdString(room.name);
187 case Roles::LastMessage:
188 return tr("Previewing this room");
189 case Roles::Time:
190 return QString();
191 case Roles::Timestamp:
192 return QVariant{static_cast<quint64>(0)};
193 case Roles::HasUnreadMessages:
194 case Roles::HasLoudNotification:
195 return false;
196 case Roles::NotificationCount:
197 return 0;
198 case Roles::IsInvite:
199 return false;
200 case Roles::IsSpace:
201 return room.is_space;
202 case Roles::IsPreview:
203 return true;
204 case Roles::IsPreviewFetched:
205 return true;
206 case Roles::Tags:
207 return QStringList();
208 default:
209 return {};
210 }
211 } else {
212 if (role == Roles::IsPreview)
213 return true;
214 else if (role == Roles::IsPreviewFetched)
215 return false;
216
217 switch (role) {
218 case Roles::AvatarUrl:
219 return QString();
220 case Roles::RoomName:
221 return tr("No preview available");
222 case Roles::LastMessage:
223 return tr("This room is possibly inaccessible");
224 case Roles::Time:
225 return QString();
226 case Roles::Timestamp:
227 return QVariant(static_cast<quint64>(0));
228 case Roles::HasUnreadMessages:
229 case Roles::HasLoudNotification:
230 return false;
231 case Roles::NotificationCount:
232 return 0;
233 case Roles::IsInvite:
234 return false;
235 case Roles::IsSpace:
236 return false;
237 case Roles::Tags:
238 return QStringList();
239 default:
240 return {};
241 }
242 }
243 } else {
244 return {};
245 }
246 }
247
248 void
249 RoomlistModel::updateReadStatus(const std::map<QString, bool> &roomReadStatus_)
250 {
251 std::vector<int> roomsToUpdate;
252 roomsToUpdate.resize(roomReadStatus_.size());
253 for (const auto &[roomid, roomUnread] : roomReadStatus_) {
254 if (roomUnread != roomReadStatus[roomid]) {
255 roomsToUpdate.push_back(this->roomidToIndex(roomid));
256 }
257
258 this->roomReadStatus[roomid] = roomUnread;
259 }
260
261 for (auto idx : roomsToUpdate) {
262 emit dataChanged(index(idx),
263 index(idx),
264 {
265 Roles::HasUnreadMessages,
266 });
267 }
268 }
269 void
270 RoomlistModel::addRoom(const QString &room_id, bool suppressInsertNotification)
271 {
272 if (!models.contains(room_id)) {
273 // ensure we get read status updates and are only connected once
274 // WORKAROUND(Nico): This is not a lambda, but clazy on alpine currently doesn't
275 // believe us...
276 connect(cache::client(),
277 &Cache::roomReadStatus,
278 this,
279 &RoomlistModel::updateReadStatus,
280 Qt::UniqueConnection); // clazy:exclude=lambda-unique-connection
281
282 QSharedPointer<TimelineModel> newRoom(new TimelineModel(manager, room_id));
283 newRoom->setDecryptDescription(ChatPage::instance()->userSettings()->decryptSidebar());
284
285 connect(this,
286 &RoomlistModel::currentRoomChanged,
287 newRoom.data(),
288 &TimelineModel::updateLastReadId);
289 connect(MainWindow::instance(),
290 &MainWindow::activeChanged,
291 newRoom.data(),
292 &TimelineModel::lastReadIdOnWindowFocus);
293 connect(newRoom.data(),
294 &TimelineModel::newEncryptedImage,
295 MainWindow::instance()->imageProvider(),
296 &MxcImageProvider::addEncryptionInfo);
297 connect(newRoom.data(),
298 &TimelineModel::forwardToRoom,
299 manager,
300 &TimelineViewManager::forwardMessageToRoom);
301 connect(newRoom.data(), &TimelineModel::lastMessageChanged, this, [room_id, this]() {
302 auto idx = this->roomidToIndex(room_id);
303 emit dataChanged(index(idx),
304 index(idx),
305 {
306 Roles::HasLoudNotification,
307 Roles::LastMessage,
308 Roles::Time,
309 Roles::Timestamp,
310 Roles::NotificationCount,
311 Qt::DisplayRole,
312 });
313 });
314 connect(newRoom.data(), &TimelineModel::roomAvatarUrlChanged, this, [room_id, this]() {
315 auto idx = this->roomidToIndex(room_id);
316 emit dataChanged(index(idx),
317 index(idx),
318 {
319 Roles::AvatarUrl,
320 });
321 });
322 connect(newRoom.data(), &TimelineModel::roomNameChanged, this, [room_id, this]() {
323 auto idx = this->roomidToIndex(room_id);
324 emit dataChanged(index(idx),
325 index(idx),
326 {
327 Roles::RoomName,
328 });
329 });
330 connect(newRoom.data(), &TimelineModel::notificationsChanged, this, [room_id, this]() {
331 auto idx = this->roomidToIndex(room_id);
332 emit dataChanged(index(idx),
333 index(idx),
334 {
335 Roles::HasLoudNotification,
336 Roles::NotificationCount,
337 Qt::DisplayRole,
338 });
339
340 if (getRoomById(room_id)->isSpace())
341 return; // no need to update space notifications
342
343 int total_unread_msgs = 0;
344
345 for (const auto &room : std::as_const(models)) {
346 if (!room.isNull() && !room->isSpace())
347 total_unread_msgs += room->notificationCount();
348 }
349
350 emit totalUnreadMessageCountUpdated(total_unread_msgs);
351 });
352
353 // newRoom->updateLastMessage();
354
355 std::vector<QString> previewsToAdd;
356 if (newRoom->isSpace()) {
357 auto childs = cache::client()->getChildRoomIds(room_id.toStdString());
358 for (const auto &c : childs) {
359 auto id = QString::fromStdString(c);
360 if (!(models.contains(id) || invites.contains(id) || previewedRooms.contains(id))) {
361 previewsToAdd.push_back(std::move(id));
362 }
363 }
364 }
365
366 bool wasInvite = invites.contains(room_id);
367 bool wasPreview = previewedRooms.contains(room_id);
368 if (!suppressInsertNotification && ((!wasInvite && !wasPreview) || !previewedRooms.empty()))
369 // if the old room was already in the list, don't add it. Also add all
370 // previews at the same time.
371 beginInsertRows(
372 QModelIndex(),
373 (int)roomids.size(),
374 (int)(roomids.size() + previewsToAdd.size() - ((wasInvite || wasPreview) ? 1 : 0)));
375
376 models.insert(room_id, std::move(newRoom));
377 if (wasInvite) {
378 auto idx = roomidToIndex(room_id);
379 invites.remove(room_id);
380 emit dataChanged(index(idx), index(idx));
381 } else if (wasPreview) {
382 auto idx = roomidToIndex(room_id);
383 previewedRooms.remove(room_id);
384 emit dataChanged(index(idx), index(idx));
385 } else {
386 roomids.push_back(room_id);
387 }
388
389 if ((wasInvite || wasPreview) && currentRoomPreview_ &&
390 currentRoomPreview_->roomid() == room_id) {
391 currentRoom_ = models.value(room_id);
392 currentRoomPreview_.reset();
393 emit currentRoomChanged(room_id);
394 }
395
396 for (auto p : previewsToAdd) {
397 previewedRooms.insert(p, std::nullopt);
398 roomids.push_back(std::move(p));
399 }
400
401 if (!suppressInsertNotification && ((!wasInvite && !wasPreview) || !previewedRooms.empty()))
402 endInsertRows();
403
404 emit ChatPage::instance()->newRoom(room_id);
405 }
406 }
407
408 void
409 RoomlistModel::fetchPreviews(QString roomid_, const std::string &from)
410 {
411 auto roomid = roomid_.toStdString();
412 if (from.empty()) {
413 // check if we need to fetch anything
414 auto children = cache::client()->getChildRoomIds(roomid);
415 bool fetch = false;
416 for (const auto &c : children) {
417 auto id = QString::fromStdString(c);
418 if (invites.contains(id) || models.contains(id) ||
419 (previewedRooms.contains(id) && previewedRooms.value(id).has_value()))
420 continue;
421 else {
422 fetch = true;
423 break;
424 }
425 }
426 if (!fetch) {
427 nhlog::net()->info("Not feching previews for children of {}", roomid);
428 return;
429 }
430 }
431
432 nhlog::net()->info("Feching previews for children of {}", roomid);
433 http::client()->get_hierarchy(
434 roomid,
435 [this, roomid, roomid_](const mtx::responses::HierarchyRooms &h, mtx::http::RequestErr err) {
436 if (err) {
437 nhlog::net()->error("Failed to fetch previews for children of {}: {}", roomid, *err);
438 return;
439 }
440
441 nhlog::net()->info("Feched previews for children of {}: {}", roomid, h.rooms.size());
442
443 for (const auto &e : h.rooms) {
444 RoomInfo info{};
445 info.name = e.name;
446 info.is_space = e.room_type == mtx::events::state::room_type::space;
447 info.avatar_url = e.avatar_url;
448 info.topic = e.topic;
449 info.guest_access = e.guest_can_join;
450 info.join_rule = e.join_rule;
451 info.member_count = e.num_joined_members;
452
453 emit fetchedPreview(QString::fromStdString(e.room_id), info);
454 }
455
456 if (!h.next_batch.empty())
457 fetchPreviews(roomid_, h.next_batch);
458 },
459 from,
460 50,
461 1,
462 false);
463 }
464
465 std::set<QString>
466 RoomlistModel::updateDMs(mtx::events::AccountDataEvent<mtx::events::account_data::Direct> event)
467 {
468 std::set<QString> roomsToUpdate;
469 std::map<QString, std::vector<QString>> directChatToUserTemp;
470
471 for (const auto &[user, rooms] : event.content.user_to_rooms) {
472 QString u = QString::fromStdString(user);
473
474 for (const auto &r : rooms) {
475 directChatToUserTemp[QString::fromStdString(r)].push_back(u);
476 }
477 }
478
479 for (auto l = directChatToUser.begin(), r = directChatToUserTemp.begin();
480 l != directChatToUser.end() && r != directChatToUserTemp.end();) {
481 if (l == directChatToUser.end()) {
482 while (r != directChatToUserTemp.end()) {
483 roomsToUpdate.insert(r->first);
484 ++r;
485 }
486 } else if (r == directChatToUserTemp.end()) {
487 while (l != directChatToUser.end()) {
488 roomsToUpdate.insert(l->first);
489 ++l;
490 }
491 } else if (l->first == r->first) {
492 if (l->second != r->second)
493 roomsToUpdate.insert(l->first);
494
495 ++l;
496 ++r;
497 } else if (l->first < r->first) {
498 roomsToUpdate.insert(l->first);
499 ++l;
500 } else if (l->first > r->first) {
501 roomsToUpdate.insert(r->first);
502 ++r;
503 } else {
504 throw std::logic_error("Infinite loop when updating DMs!");
505 }
506 }
507
508 this->directChatToUser = directChatToUserTemp;
509
510 return roomsToUpdate;
511 }
512
513 void
514 RoomlistModel::sync(const mtx::responses::Sync &sync_)
515 {
516 for (const auto &e : sync_.account_data.events) {
517 if (auto event =
518 std::get_if<mtx::events::AccountDataEvent<mtx::events::account_data::Direct>>(&e)) {
519 auto updatedDMs = updateDMs(*event);
520 for (const auto &r : updatedDMs) {
521 if (auto idx = roomidToIndex(r); idx != -1)
522 emit dataChanged(index(idx), index(idx), {IsDirect, DirectChatOtherUserId});
523 }
524 }
525 }
526
527 for (const auto &[room_id, room] : sync_.rooms.join) {
528 auto qroomid = QString::fromStdString(room_id);
529
530 // addRoom will only add the room, if it doesn't exist
531 addRoom(qroomid);
532 const auto &room_model = models.value(qroomid);
533
534 // WORKAROUND(Nico): This is not a lambda, but clazy on alpine currently doesn't
535 // believe us
536 connect(room_model.data(),
537 &TimelineModel::newCallEvent,
538 ChatPage::instance()->callManager(),
539 &CallManager::syncEvent,
540 Qt::UniqueConnection); // clazy:exclude=lambda-unique-connection
541
542 room_model->sync(room);
543
544 if (ChatPage::instance()->userSettings()->typingNotifications()) {
545 for (const auto &ev : room.ephemeral.events) {
546 if (auto t =
547 std::get_if<mtx::events::EphemeralEvent<mtx::events::ephemeral::Typing>>(
548 &ev)) {
549 QStringList typing;
550 typing.reserve(t->content.user_ids.size());
551 for (const auto &user : t->content.user_ids) {
552 if (user != http::client()->user_id().to_string())
553 typing.push_back(QString::fromStdString(user));
554 }
555 room_model->updateTypingUsers(typing);
556 }
557 }
558 }
559 for (const auto &e : room.account_data.events) {
560 if (std::holds_alternative<
561 mtx::events::AccountDataEvent<mtx::events::account_data::Tags>>(e)) {
562 if (auto idx = roomidToIndex(qroomid); idx != -1)
563 emit dataChanged(index(idx), index(idx), {Tags});
564 }
565 }
566 }
567
568 for (const auto &[room_id, room] : sync_.rooms.leave) {
569 (void)room;
570 auto qroomid = QString::fromStdString(room_id);
571
572 if ((currentRoom_ && currentRoom_->roomId() == qroomid) ||
573 (currentRoomPreview_ && currentRoomPreview_->roomid() == qroomid))
574 resetCurrentRoom();
575
576 auto idx = this->roomidToIndex(qroomid);
577 if (idx != -1) {
578 beginRemoveRows(QModelIndex(), idx, idx);
579 roomids.erase(roomids.begin() + idx);
580 if (models.contains(qroomid))
581 models.remove(qroomid);
582 else if (invites.contains(qroomid))
583 invites.remove(qroomid);
584 endRemoveRows();
585 }
586 }
587
588 for (const auto &[room_id, room] : sync_.rooms.invite) {
589 (void)room;
590 auto qroomid = QString::fromStdString(room_id);
591
592 auto invite = cache::client()->invite(room_id);
593 if (!invite)
594 continue;
595
596 if (invites.contains(qroomid)) {
597 invites[qroomid] = *invite;
598 auto idx = roomidToIndex(qroomid);
599 emit dataChanged(index(idx), index(idx));
600 } else {
601 beginInsertRows(QModelIndex(), (int)roomids.size(), (int)roomids.size());
602 invites.insert(qroomid, *invite);
603 roomids.push_back(std::move(qroomid));
604 endInsertRows();
605 }
606 }
607 }
608
609 void
610 RoomlistModel::initializeRooms()
611 {
612 beginResetModel();
613 models.clear();
614 roomids.clear();
615 invites.clear();
616 currentRoom_ = nullptr;
617
618 auto e = cache::client()->getAccountData(mtx::events::EventType::Direct);
619 if (e) {
620 if (auto event =
621 std::get_if<mtx::events::AccountDataEvent<mtx::events::account_data::Direct>>(
622 &e.value())) {
623 updateDMs(*event);
624 }
625 }
626
627 invites = cache::client()->invites();
628 for (auto id = invites.keyBegin(); id != invites.keyEnd(); ++id) {
629 roomids.push_back(*id);
630 }
631
632 for (const auto &id : cache::client()->roomIds())
633 addRoom(id, true);
634
635 nhlog::db()->info("Restored {} rooms from cache", rowCount());
636
637 endResetModel();
638
639 #ifdef NHEKO_DBUS_SYS
640 if (MainWindow::instance()->dbusAvailable()) {
641 dbusInterface_ = new NhekoDBusBackend{this};
642 if (!QDBusConnection::sessionBus().registerObject(
643 "/", dbusInterface_, QDBusConnection::ExportScriptableSlots))
644 nhlog::ui()->warn("Failed to register rooms with D-Bus");
645 }
646 #endif
647 }
648
649 void
650 RoomlistModel::clear()
651 {
652 beginResetModel();
653 models.clear();
654 invites.clear();
655 roomids.clear();
656 currentRoom_ = nullptr;
657 emit currentRoomChanged("");
658 endResetModel();
659 }
660
661 void
662 RoomlistModel::joinPreview(const QString &roomid)
663 {
664 if (previewedRooms.contains(roomid)) {
665 ChatPage::instance()->joinRoomVia(
666 roomid.toStdString(), utils::roomVias(roomid.toStdString()), false);
667 }
668 }
669 void
670 RoomlistModel::acceptInvite(QString roomid)
671 {
672 if (invites.contains(roomid)) {
673 // Don't remove invite yet, so that we can switch to it
674 auto members = cache::getMembersFromInvite(roomid.toStdString(), 0, -1);
675 auto local = utils::localUser();
676 for (const auto &m : members) {
677 if (m.user_id == local && m.is_direct) {
678 nhlog::db()->info("marking {} as direct", roomid.toStdString());
679 utils::markRoomAsDirect(roomid, members);
680 break;
681 }
682 }
683
684 ChatPage::instance()->joinRoom(roomid);
685 }
686 }
687 void
688 RoomlistModel::declineInvite(QString roomid)
689 {
690 if (invites.contains(roomid)) {
691 auto idx = roomidToIndex(roomid);
692
693 if (idx != -1) {
694 beginRemoveRows(QModelIndex(), idx, idx);
695 roomids.erase(roomids.begin() + idx);
696 invites.remove(roomid);
697 endRemoveRows();
698 ChatPage::instance()->leaveRoom(roomid, "");
699 }
700 }
701 }
702 void
703 RoomlistModel::leave(QString roomid, QString reason)
704 {
705 // We want to leave in any case, even if this is an invite or similar.
706 ChatPage::instance()->leaveRoom(roomid, reason);
707 if (models.contains(roomid)) {
708 auto idx = roomidToIndex(roomid);
709
710 if (idx != -1) {
711 beginRemoveRows(QModelIndex(), idx, idx);
712 roomids.erase(roomids.begin() + idx);
713 models.remove(roomid);
714 endRemoveRows();
715 }
716 }
717 }
718
719 RoomPreview
720 RoomlistModel::getRoomPreviewById(QString roomid) const
721 {
722 RoomPreview preview{};
723
724 if (invites.contains(roomid) || previewedRooms.contains(roomid)) {
725 std::optional<RoomInfo> i;
726 if (invites.contains(roomid)) {
727 i = invites.value(roomid);
728 preview.isInvite_ = true;
729
730 auto member = cache::client()->getInviteMember(roomid.toStdString(),
731 http::client()->user_id().to_string());
732
733 if (member) {
734 preview.reason_ = QString::fromStdString(member->reason);
735 }
736 } else {
737 i = previewedRooms.value(roomid);
738 preview.isInvite_ = false;
739 }
740
741 if (i) {
742 preview.roomid_ = roomid;
743 preview.roomName_ = QString::fromStdString(i->name);
744 preview.roomTopic_ = QString::fromStdString(i->topic);
745 preview.roomAvatarUrl_ = QString::fromStdString(i->avatar_url);
746 } else {
747 preview.roomid_ = roomid;
748 }
749 }
750
751 return preview;
752 }
753
754 void
755 RoomlistModel::setCurrentRoom(const QString &roomid)
756 {
757 if ((currentRoom_ && currentRoom_->roomId() == roomid) ||
758 (currentRoomPreview_ && currentRoomPreview_->roomid() == roomid))
759 return;
760
761 if (roomid.isEmpty()) {
762 currentRoom_ = nullptr;
763 currentRoomPreview_ = {};
764 emit currentRoomChanged("");
765 }
766
767 nhlog::ui()->debug("Trying to switch to: {}", roomid.toStdString());
768 if (models.contains(roomid)) {
769 currentRoom_ = models.value(roomid);
770 currentRoomPreview_.reset();
771 emit currentRoomChanged(currentRoom_->roomId());
772 nhlog::ui()->debug("Switched to: {}", roomid.toStdString());
773
774 if (currentRoom_->isSpace()) {
775 emit spaceSelected(roomid);
776 }
777 } else if (invites.contains(roomid) || previewedRooms.contains(roomid)) {
778 currentRoom_ = nullptr;
779 std::optional<RoomInfo> i;
780
781 RoomPreview p;
782
783 if (invites.contains(roomid)) {
784 i = invites.value(roomid);
785 p.isInvite_ = true;
786
787 auto member = cache::client()->getInviteMember(roomid.toStdString(),
788 http::client()->user_id().to_string());
789
790 if (member) {
791 p.reason_ = QString::fromStdString(member->reason);
792 }
793 } else {
794 i = previewedRooms.value(roomid);
795 p.isInvite_ = false;
796 }
797
798 if (i) {
799 p.roomid_ = roomid;
800 p.roomName_ = QString::fromStdString(i->name);
801 p.roomTopic_ = QString::fromStdString(i->topic);
802 p.roomAvatarUrl_ = QString::fromStdString(i->avatar_url);
803 p.isFetched_ = true;
804 currentRoomPreview_ = std::move(p);
805 nhlog::ui()->debug("Switched to (preview): {}",
806 currentRoomPreview_->roomid_.toStdString());
807 } else {
808 p.roomid_ = roomid;
809 p.isFetched_ = false;
810 currentRoomPreview_ = p;
811 nhlog::ui()->debug("Switched to (empty): {}",
812 currentRoomPreview_->roomid_.toStdString());
813 }
814
815 emit currentRoomChanged("");
816 }
817 }
818
819 void
820 RoomlistModel::refetchOnlineKeyBackupKeys()
821 {
822 for (auto i = models.begin(); i != models.end(); ++i) {
823 auto ptr = i.value();
824
825 if (!ptr.isNull()) {
826 ptr->refetchOnlineKeyBackupKeys();
827 }
828 }
829 }
830
831 namespace {
832 enum NotificationImportance : short
833 {
834 NoPreview = -3,
835 Preview = -2,
836 ImportanceDisabled = -1,
837 AllEventsRead = 0,
838 NewMessage = 1,
839 NewMentions = 2,
840 Invite = 3,
841 SubSpace = 4,
842 CurrentSpace = 5,
843 };
844 }
845
846 short int
847 FilteredRoomlistModel::calculateImportance(const QModelIndex &idx) const
848 {
849 // Returns the degree of importance of the unread messages in the room.
850 // If sorting by importance is disabled in settings, this only ever
851 // returns ImportanceDisabled or Invite
852 if (sourceModel()->data(idx, RoomlistModel::IsSpace).toBool()) {
853 if (filterType == FilterBy::Space &&
854 filterStr == sourceModel()->data(idx, RoomlistModel::RoomId).toString())
855 return CurrentSpace;
856 else
857 return SubSpace;
858 } else if (sourceModel()->data(idx, RoomlistModel::IsPreview).toBool()) {
859 if (sourceModel()->data(idx, RoomlistModel::IsPreviewFetched).toBool())
860 return Preview;
861 else
862 return NoPreview;
863 } else if (sourceModel()->data(idx, RoomlistModel::IsInvite).toBool()) {
864 return Invite;
865 } else if (!this->sortByImportance) {
866 return ImportanceDisabled;
867 } else if (sourceModel()->data(idx, RoomlistModel::HasLoudNotification).toBool()) {
868 return NewMentions;
869 } else if (sourceModel()->data(idx, RoomlistModel::NotificationCount).toInt() > 0) {
870 return NewMessage;
871 } else {
872 return AllEventsRead;
873 }
874 }
875
876 bool
877 FilteredRoomlistModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
878 {
879 QModelIndex const left_idx = sourceModel()->index(left.row(), 0, QModelIndex());
880 QModelIndex const right_idx = sourceModel()->index(right.row(), 0, QModelIndex());
881
882 // Sort by "importance" (i.e. invites before mentions before
883 // notifs before new events before old events), then secondly
884 // by recency.
885
886 // Checking importance first
887 const auto a_importance = calculateImportance(left_idx);
888 const auto b_importance = calculateImportance(right_idx);
889 if (a_importance != b_importance) {
890 return a_importance > b_importance;
891 }
892
893 // Now sort by recency or room name
894 // Zero if empty, otherwise the time that the event occured
895
896 if (this->sortByAlphabet) {
897 QString a_order = sourceModel()->data(left_idx, RoomlistModel::RoomName).toString();
898 QString b_order = sourceModel()->data(right_idx, RoomlistModel::RoomName).toString();
899
900 auto comp = a_order.compare(b_order, Qt::CaseInsensitive);
901 if (comp != 0)
902 return comp < 0;
903 } else {
904 uint64_t a_order = sourceModel()->data(left_idx, RoomlistModel::Timestamp).toULongLong();
905 uint64_t b_order = sourceModel()->data(right_idx, RoomlistModel::Timestamp).toULongLong();
906
907 if (a_order != b_order)
908 return a_order > b_order;
909 }
910
911 return left.row() < right.row();
912 }
913
914 FilteredRoomlistModel::FilteredRoomlistModel(RoomlistModel *model, QObject *parent)
915 : QSortFilterProxyModel(parent)
916 , roomlistmodel(model)
917 {
918 instance_ = this;
919
920 this->sortByImportance = UserSettings::instance()->sortByImportance();
921 this->sortByAlphabet = UserSettings::instance()->sortByAlphabet();
922 setSourceModel(model);
923 setDynamicSortFilter(true);
924
925 QObject::connect(UserSettings::instance().get(),
926 &UserSettings::roomSortingChangedImportance,
927 this,
928 [this](bool sortByImportance_) {
929 this->sortByImportance = sortByImportance_;
930 invalidate();
931 });
932
933 QObject::connect(UserSettings::instance().get(),
934 &UserSettings::roomSortingChangedAlphabetical,
935 this,
936 [this](bool sortByAlphabet_) {
937 this->sortByAlphabet = sortByAlphabet_;
938 invalidate();
939 });
940
941 connect(roomlistmodel,
942 &RoomlistModel::currentRoomChanged,
943 this,
944 &FilteredRoomlistModel::currentRoomChanged);
945
946 sort(0);
947 }
948
949 FilteredRoomlistModel *
950 FilteredRoomlistModel::create(QQmlEngine *qmlEngine, QJSEngine *)
951 {
952 // The instance has to exist before it is used. We cannot replace it.
953 Q_ASSERT(instance_);
954
955 // The engine has to have the same thread affinity as the singleton.
956 Q_ASSERT(qmlEngine->thread() == instance_->thread());
957
958 // There can only be one engine accessing the singleton.
959 static QJSEngine *s_engine = nullptr;
960 if (s_engine)
961 Q_ASSERT(qmlEngine == s_engine);
962 else
963 s_engine = qmlEngine;
964
965 QJSEngine::setObjectOwnership(instance_, QJSEngine::CppOwnership);
966 return instance_;
967 }
968
969 TimelineModel *
970 FilteredRoomlistModel::getRoomById(const QString &id) const
971 {
972 auto r = roomlistmodel->getRoomById(id).data();
973 QQmlEngine::setObjectOwnership(r, QQmlEngine::CppOwnership);
974 return r;
975 }
976
977 void
978 FilteredRoomlistModel::updateHiddenTagsAndSpaces()
979 {
•980 #if QT_VERSION >= QT_VERSION_CHECK(6, 9, 0)
981 beginFilterChange();
982 #endif
983
984 hiddenTags.clear();
985 hiddenSpaces.clear();
986 hideDMs = false;
987
988 auto hidden = UserSettings::instance()->hiddenTags();
989 for (const auto &t : std::as_const(hidden)) {
990 if (t.startsWith(u"tag:"))
991 hiddenTags.push_back(t.mid(4));
992 else if (t.startsWith(u"space:"))
993 hiddenSpaces.push_back(t.mid(6));
994 else if (t == QLatin1String("dm"))
995 hideDMs = true;
996 }
997
•998 #if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0)
999 endFilterChange();
1000 #else
1001 invalidateFilter();
•1002 #endif
1003 }
1004
1005 bool
1006 FilteredRoomlistModel::filterAcceptsRow(int sourceRow, const QModelIndex &) const
1007 {
1008 if (filterType == FilterBy::Nothing) {
1009 if (sourceModel()
1010 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsPreview)
1011 .toBool()) {
1012 return false;
1013 }
1014
1015 if (sourceModel()
1016 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsSpace)
1017 .toBool()) {
1018 return false;
1019 }
1020
1021 if (!hiddenTags.empty()) {
1022 auto tags = sourceModel()
1023 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::Tags)
1024 .toStringList();
1025
1026 for (const auto &t : std::as_const(tags))
1027 if (hiddenTags.contains(t))
1028 return false;
1029 }
1030
1031 if (!hiddenSpaces.empty()) {
1032 auto parents = sourceModel()
1033 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::ParentSpaces)
1034 .toStringList();
1035 for (const auto &t : std::as_const(parents))
1036 if (hiddenSpaces.contains(t))
1037 return false;
1038 }
1039
1040 if (hideDMs) {
1041 return !sourceModel()
1042 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsDirect)
1043 .toBool();
1044 }
1045
1046 return true;
1047 } else if (filterType == FilterBy::DirectChats) {
1048 if (sourceModel()
1049 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsPreview)
1050 .toBool()) {
1051 return false;
1052 }
1053
1054 if (sourceModel()
1055 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsSpace)
1056 .toBool()) {
1057 return false;
1058 }
1059
1060 if (!hiddenTags.empty()) {
1061 auto tags = sourceModel()
1062 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::Tags)
1063 .toStringList();
1064
1065 for (const auto &t : std::as_const(tags))
1066 if (hiddenTags.contains(t))
1067 return false;
1068 }
1069
1070 if (!hiddenSpaces.empty()) {
1071 auto parents = sourceModel()
1072 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::ParentSpaces)
1073 .toStringList();
1074 for (const auto &t : std::as_const(parents))
1075 if (hiddenSpaces.contains(t))
1076 return false;
1077 }
1078
1079 return sourceModel()
1080 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsDirect)
1081 .toBool();
1082 } else if (filterType == FilterBy::Tag) {
1083 if (sourceModel()
1084 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsPreview)
1085 .toBool()) {
1086 return false;
1087 }
1088
1089 if (sourceModel()
1090 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsSpace)
1091 .toBool()) {
1092 return false;
1093 }
1094
1095 auto tags = sourceModel()
1096 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::Tags)
1097 .toStringList();
1098
1099 if (!tags.contains(filterStr))
1100 return false;
1101
1102 if (!hiddenTags.empty()) {
1103 for (const auto &t : std::as_const(tags))
1104 if (t != filterStr && hiddenTags.contains(t))
1105 return false;
1106 }
1107
1108 if (!hiddenSpaces.empty()) {
1109 auto parents = sourceModel()
1110 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::ParentSpaces)
1111 .toStringList();
1112 for (const auto &t : std::as_const(parents))
1113 if (hiddenSpaces.contains(t))
1114 return false;
1115 }
1116
1117 if (hideDMs) {
1118 return !sourceModel()
1119 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsDirect)
1120 .toBool();
1121 }
1122
1123 return true;
1124 } else if (filterType == FilterBy::Space) {
1125 if (filterStr == sourceModel()
1126 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::RoomId)
1127 .toString())
1128 return true;
1129
1130 auto parents = sourceModel()
1131 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::ParentSpaces)
1132 .toStringList();
1133
1134 if (!parents.contains(filterStr))
1135 return false;
1136
1137 if (!hiddenTags.empty()) {
1138 auto tags = sourceModel()
1139 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::Tags)
1140 .toStringList();
1141
1142 for (const auto &t : std::as_const(tags))
1143 if (hiddenTags.contains(t))
1144 return false;
1145 }
1146
1147 if (!hiddenSpaces.empty()) {
1148 for (const auto &t : std::as_const(parents))
1149 if (t != filterStr && hiddenSpaces.contains(t))
1150 return false;
1151 }
1152
1153 if (sourceModel()
1154 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsSpace)
1155 .toBool() &&
1156 !parents.contains(filterStr)) {
1157 return false;
1158 }
1159
1160 if (hideDMs) {
1161 return !sourceModel()
1162 ->data(sourceModel()->index(sourceRow, 0), RoomlistModel::IsDirect)
1163 .toBool();
1164 }
1165
1166 // If it is a preview but it can't be fetched, it is probably an inaccessible private room.
1167 // Hide it if the user isn't an admin.
1168 auto index = sourceModel()->index(sourceRow, 0);
1169 if (sourceModel()->data(index, RoomlistModel::IsPreview).toBool() &&
1170 !sourceModel()->data(index, RoomlistModel::IsPreviewFetched).toBool() &&
1171 !Permissions(filterStr).canChange(qml_mtx_events::SpaceChild)) {
1172 return false;
1173 }
1174
1175 return true;
1176 } else {
1177 return true;
1178 }
1179 }
1180
1181 void
1182 FilteredRoomlistModel::toggleTag(const QString &roomid, const QString &tag, bool on)
1183 {
1184 if (on) {
1185 http::client()->put_tag(
1186 roomid.toStdString(), tag.toStdString(), {}, [tag](mtx::http::RequestErr err) {
1187 if (err) {
1188 nhlog::ui()->error(
1189 "Failed to add tag: {}, {}", tag.toStdString(), err->matrix_error.error);
1190 }
1191 });
1192 } else {
1193 http::client()->delete_tag(
1194 roomid.toStdString(), tag.toStdString(), [tag](mtx::http::RequestErr err) {
1195 if (err) {
1196 nhlog::ui()->error(
1197 "Failed to delete tag: {}, {}", tag.toStdString(), err->matrix_error.error);
1198 }
1199 });
1200 }
1201 }
1202
1203 void
1204 FilteredRoomlistModel::copyLink(QString roomid)
1205 {
1206 auto link = QStringLiteral("%1?%2").arg(TimelineModel::getBareRoomLink(roomid),
1207 TimelineModel::getRoomVias(roomid));
1208 QGuiApplication::clipboard()->setText(link);
1209 }
1210
1211 void
1212 FilteredRoomlistModel::nextRoomWithActivity()
1213 {
1214 int roomWithMention = -1;
1215 int roomWithNotification = -1;
1216 int roomWithUnreadMessage = -1;
1217 auto r = currentRoom();
1218 int currentRoomIdx = r ? roomidToIndex(r->roomId()) : -1;
1219 // first look for mentions
1220 for (int i = 0; i < (int)roomlistmodel->roomids.size(); i++) {
1221 if (i == currentRoomIdx)
1222 continue;
1223 if (this->data(index(i, 0), RoomlistModel::HasLoudNotification).toBool()) {
1224 roomWithMention = i;
1225 break;
1226 }
1227 if (roomWithNotification == -1 &&
1228 this->data(index(i, 0), RoomlistModel::NotificationCount).toInt() > 0) {
1229 roomWithNotification = i;
1230 // don't break, we must continue looking for rooms with mentions
1231 }
1232 if (roomWithNotification == -1 && roomWithUnreadMessage == -1 &&
1233 this->data(index(i, 0), RoomlistModel::HasUnreadMessages).toBool()) {
1234 roomWithUnreadMessage = i;
1235 // don't break, we must continue looking for rooms with mentions
1236 }
1237 }
1238 QString targetRoomId = nullptr;
1239 if (roomWithMention != -1) {
1240 targetRoomId = this->data(index(roomWithMention, 0), RoomlistModel::RoomId).toString();
1241 nhlog::ui()->debug("choosing {} for mentions", targetRoomId.toStdString());
1242 } else if (roomWithNotification != -1) {
1243 targetRoomId = this->data(index(roomWithNotification, 0), RoomlistModel::RoomId).toString();
1244 nhlog::ui()->debug("choosing {} for notifications", targetRoomId.toStdString());
1245 } else if (roomWithUnreadMessage != -1) {
1246 targetRoomId =
1247 this->data(index(roomWithUnreadMessage, 0), RoomlistModel::RoomId).toString();
1248 nhlog::ui()->debug("choosing {} for unread messages", targetRoomId.toStdString());
1249 }
1250 if (targetRoomId != nullptr) {
1251 setCurrentRoom(targetRoomId);
1252 }
1253 }
1254
1255 void
1256 FilteredRoomlistModel::nextRoom()
1257 {
1258 auto r = currentRoom();
1259
1260 if (r) {
1261 int idx = roomidToIndex(r->roomId());
1262 idx++;
1263 if (idx < rowCount()) {
1264 setCurrentRoom(data(index(idx, 0), RoomlistModel::Roles::RoomId).toString());
1265 }
1266 }
1267 }
1268
1269 void
1270 FilteredRoomlistModel::previousRoom()
1271 {
1272 auto r = currentRoom();
1273
1274 if (r) {
1275 int idx = roomidToIndex(r->roomId());
1276 idx--;
1277 if (idx >= 0) {
1278 setCurrentRoom(data(index(idx, 0), RoomlistModel::Roles::RoomId).toString());
1279 }
1280 }
1281 }
1282
1283 QString
1284 RoomPreview::inviterAvatarUrl() const
1285 {
1286 if (isInvite_) {
1287 auto self = cache::client()->getInviteMember(roomid_.toStdString(),
1288 http::client()->user_id().to_string());
1289 if (self && !self->inviter.empty()) {
1290 auto other = cache::client()->getInviteMember(roomid_.toStdString(), self->inviter);
1291 if (other && other->avatar_url.starts_with("mxc://")) {
1292 return QString::fromStdString(other->avatar_url);
1293 }
1294 }
1295 }
1296
1297 return QString();
1298 }
1299 QString
1300 RoomPreview::inviterDisplayName() const
1301 {
1302 if (isInvite_) {
1303 auto self = cache::client()->getInviteMember(roomid_.toStdString(),
1304 http::client()->user_id().to_string());
1305 if (self && !self->inviter.empty()) {
1306 auto other = cache::client()->getInviteMember(roomid_.toStdString(), self->inviter);
1307 if (other) {
1308 return QString::fromStdString(other->name).toHtmlEscaped();
1309 }
1310 }
1311 }
1312
1313 return QString();
1314 }
1315 QString
1316 RoomPreview::inviterUserId() const
1317 {
1318 if (isInvite_) {
1319 auto self = cache::client()->getInviteMember(roomid_.toStdString(),
1320 http::client()->user_id().to_string());
1321 if (self && !self->inviter.empty()) {
1322 return QString::fromStdString(self->inviter);
1323 }
1324 }
1325
1326 return QString();
1327 }
1328
1329 #include "moc_RoomlistModel.cpp"