Debian Codegraph @

src/timeline/TimelineViewManager.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "TimelineViewManager.h"
6
7 #include <QApplication>
8 #include <QClipboard>
9 #include <QFileDialog>
10 #include <QMimeData>
11 #include <QQuickItem>
12 #include <QQuickTextDocument>
13 #include <QStandardPaths>
14 #include <QString>
15
16 #include "Cache.h"
17 #include "Cache_p.h"
18 #include "ChatPage.h"
19 #include "CombinedImagePackModel.h"
20 #include "CommandCompleter.h"
21 #include "CompletionProxyModel.h"
22 #include "EventAccessors.h"
23 #include "GridImagePackModel.h"
24 #include "ImagePackListModel.h"
25 #include "InviteesModel.h"
26 #include "Logging.h"
27 #include "MainWindow.h"
28 #include "MatrixClient.h"
29 #include "MemberList.h"
30 #include "RoomsModel.h"
31 #include "TimelineModel.h"
32 #include "UserSettingsPage.h"
33 #include "UsersModel.h"
34 #include "Utils.h"
35 #include "encryption/VerificationManager.h"
36 #include "timeline/CommunitiesModel.h"
37 #include "timeline/PresenceEmitter.h"
38 #include "timeline/RoomlistModel.h"
39 #include "ui/RoomSettings.h"
40 #include "ui/UserProfile.h"
41 #include "voip/CallManager.h"
42 #include "voip/WebRTCSession.h"
43
44 namespace {
45 struct nonesuch
46 {
47 ~nonesuch() = delete;
48 nonesuch(nonesuch const &) = delete;
49 void operator=(nonesuch const &) = delete;
50 };
51
52 namespace detail {
53 template<class Default, class AlwaysVoid, template<class...> class Op, class... Args>
54 struct detector
55 {
56 using value_t = std::false_type;
57 using type = Default;
58 };
59
60 template<class Default, template<class...> class Op, class... Args>
61 struct detector<Default, std::void_t<Op<Args...>>, Op, Args...>
62 {
63 using value_t = std::true_type;
64 using type = Op<Args...>;
65 };
66
67 } // namespace detail
68
69 template<template<class...> class Op, class... Args>
70 using is_detected = typename detail::detector<nonesuch, void, Op, Args...>::value_t;
71
72 template<class Content>
73 using file_t = decltype(Content::file);
74
75 template<class Content>
76 using url_t = decltype(Content::url);
77
78 template<class Content>
79 using body_t = decltype(Content::body);
80
81 template<class Content>
82 using formatted_body_t = decltype(Content::formatted_body);
83
84 template<typename T>
85 static constexpr bool
86 messageWithFileAndUrl(const mtx::events::Event<T> &)
87 {
88 return is_detected<file_t, T>::value && is_detected<url_t, T>::value;
89 }
90
91 template<typename T>
92 static constexpr void
93 removeReplyFallback(mtx::events::Event<T> &e)
94 {
95 if constexpr (is_detected<body_t, T>::value) {
96 if constexpr (std::is_same_v<std::optional<std::string>,
97 std::remove_cv_t<decltype(e.content.body)>>) {
98 if (e.content.body) {
99 e.content.body = utils::stripReplyFromBody(e.content.body);
100 }
101 } else if constexpr (std::is_same_v<std::string,
102 std::remove_cv_t<decltype(e.content.body)>>) {
103 e.content.body = utils::stripReplyFromBody(e.content.body);
104 }
105 }
106
107 if constexpr (is_detected<formatted_body_t, T>::value) {
108 if (e.content.format == "org.matrix.custom.html") {
109 e.content.formatted_body = utils::stripReplyFromFormattedBody(e.content.formatted_body);
110 }
111 }
112 }
113 }
114
115 void
116 TimelineViewManager::updateColorPalette()
117 {
118 userColors.clear();
119 }
120
121 QColor
122 TimelineViewManager::userColor(QString id, QColor background)
123 {
124 std::pair<QString, quint64> idx{id, background.rgba64()};
125 if (!userColors.contains(idx))
126 userColors.insert(idx, QColor(utils::generateContrastingHexColor(id, background)));
127 return userColors.value(idx);
128 }
129
130 TimelineViewManager::TimelineViewManager(CallManager *, ChatPage *parent)
131 : QObject(parent)
132 , rooms_(new RoomlistModel(this))
133 , frooms_(new FilteredRoomlistModel(this->rooms_))
134 , communities_(new CommunitiesModel(this))
135 , verificationManager_(new VerificationManager(this))
136 , presenceEmitter(new PresenceEmitter(this))
137 {
138 instance_ = this;
139
140 connect(this->communities_,
141 &CommunitiesModel::currentTagIdChanged,
142 frooms_,
143 &FilteredRoomlistModel::updateFilterTag);
144 connect(this->communities_,
145 &CommunitiesModel::hiddenTagsChanged,
146 frooms_,
147 &FilteredRoomlistModel::updateHiddenTagsAndSpaces);
148
149 updateColorPalette();
150
151 connect(UserSettings::instance().get(),
152 &UserSettings::themeChanged,
153 this,
154 &TimelineViewManager::updateColorPalette);
155 connect(parent,
156 &ChatPage::receivedRoomDeviceVerificationRequest,
157 verificationManager_,
158 &VerificationManager::receivedRoomDeviceVerificationRequest);
159 connect(parent,
160 &ChatPage::receivedDeviceVerificationRequest,
161 verificationManager_,
162 &VerificationManager::receivedDeviceVerificationRequest);
163 connect(parent,
164 &ChatPage::receivedDeviceVerificationStart,
165 verificationManager_,
166 &VerificationManager::receivedDeviceVerificationStart);
167 connect(parent, &ChatPage::loggedOut, this, [this]() {
168 isInitialSync_ = true;
169 emit initialSyncChanged(true);
170 });
171 connect(parent, &ChatPage::connectionLost, this, [this] {
172 isConnected_ = false;
173 emit isConnectedChanged(false);
174 });
175 connect(parent, &ChatPage::connectionRestored, this, [this] {
176 isConnected_ = true;
177 emit isConnectedChanged(true);
178 });
179 connect(rooms_, &RoomlistModel::spaceSelected, communities_, [this](QString roomId) {
180 communities_->setCurrentTagId("space:" + roomId);
181 });
182 }
183
184 TimelineViewManager *
185 TimelineViewManager::create(QQmlEngine *qmlEngine, QJSEngine *)
186 {
187 // The instance has to exist before it is used. We cannot replace it.
188 Q_ASSERT(instance_);
189
190 // The engine has to have the same thread affinity as the singleton.
191 Q_ASSERT(qmlEngine->thread() == instance_->thread());
192
193 // There can only be one engine accessing the singleton.
194 static QJSEngine *s_engine = nullptr;
195 if (s_engine)
196 Q_ASSERT(qmlEngine == s_engine);
197 else
198 s_engine = qmlEngine;
199
200 QJSEngine::setObjectOwnership(instance_, QJSEngine::CppOwnership);
201 return instance_;
202 }
203
204 void
205 TimelineViewManager::clearAll()
206 {
207 rooms_->clear();
208 }
209
210 void
211 TimelineViewManager::openRoomMembers(TimelineModel *room)
212 {
213 if (!room)
214 return;
215 MemberList *memberList = new MemberList(room->roomId());
216 QQmlEngine::setObjectOwnership(memberList, QQmlEngine::JavaScriptOwnership);
217 emit openRoomMembersDialog(memberList, room);
218 }
219
220 void
221 TimelineViewManager::openRoomSettings(QString room_id)
222 {
223 RoomSettings *settings = new RoomSettings(room_id);
224 connect(rooms_->getRoomById(room_id).data(),
225 &TimelineModel::roomAvatarUrlChanged,
226 settings,
227 &RoomSettings::avatarChanged);
228 QQmlEngine::setObjectOwnership(settings, QQmlEngine::JavaScriptOwnership);
229 emit openRoomSettingsDialog(settings);
230 }
231
232 void
233 TimelineViewManager::openInviteUsers(QString roomId)
234 {
235 if (!roomId.startsWith('!'))
236 return;
237
238 InviteesModel *model = new InviteesModel{rooms_->getRoomById(roomId).data()};
239 connect(model, &InviteesModel::accept, this, [this, model, roomId]() {
240 emit inviteUsers(roomId, model->mxids());
241 });
242 QQmlEngine::setObjectOwnership(model, QQmlEngine::JavaScriptOwnership);
243 emit openInviteUsersDialog(model);
244 }
245
246 void
247 TimelineViewManager::openGlobalUserProfile(QString userId)
248 {
249 if (!userId.startsWith('@'))
250 return;
251
252 UserProfile *profile = new UserProfile{QString{}, userId, this};
253 QQmlEngine::setObjectOwnership(profile, QQmlEngine::JavaScriptOwnership);
254 emit openProfile(profile);
255 }
256
257 UserProfile *
258 TimelineViewManager::getGlobalUserProfile(QString userId)
259 {
260 UserProfile *profile = new UserProfile{QString{}, userId, this};
261 QQmlEngine::setObjectOwnership(profile, QQmlEngine::JavaScriptOwnership);
262 return (profile);
263 }
264
265 void
266 TimelineViewManager::setVideoCallItem()
267 {
268 WebRTCSession::instance().setVideoItem(
269 MainWindow::instance()->rootObject()->findChild<QQuickItem *>(
270 QStringLiteral("videoCallItem")));
271 }
272
273 void
274 TimelineViewManager::sync(const mtx::responses::Sync &sync_)
275 {
276 this->rooms_->sync(sync_);
277 this->communities_->sync(sync_);
278 this->presenceEmitter->sync(sync_.presence);
279 this->processIgnoredUsers(sync_.account_data);
280
281 if (isInitialSync_) {
282 this->isInitialSync_ = false;
283 emit initialSyncChanged(false);
284 }
285 }
286
287 void
288 TimelineViewManager::showEvent(const QString &room_id, const QString &event_id)
289 {
290 if (auto room = rooms_->getRoomById(room_id)) {
291 auto exWin = MainWindow::instance()->windowForRoom(room_id);
292 if (exWin) {
293 exWin->setVisible(true);
294 exWin->raise();
295 exWin->requestActivate();
296 } else {
297 rooms_->setCurrentRoom(room_id);
298 MainWindow::instance()->setVisible(true);
299 MainWindow::instance()->raise();
300 MainWindow::instance()->requestActivate();
301 nhlog::ui()->info("Activated room {}", room_id.toStdString());
302 }
303
304 room->showEvent(event_id);
305 }
306 }
307
308 QString
309 TimelineViewManager::escapeEmoji(QString str) const
310 {
311 return utils::replaceEmoji(str);
312 }
313
314 void
315 TimelineViewManager::openImageOverlay(TimelineModel *room,
316 const QString &mxcUrl,
317 const QString &eventId,
318 double originalWidth,
319 double proportionalHeight)
320 {
321 if (mxcUrl.isEmpty()) {
322 return;
323 }
324
325 emit showImageOverlay(room, eventId, mxcUrl, originalWidth, proportionalHeight);
326 }
327
328 void
329 TimelineViewManager::openImagePackSettings(QString roomid)
330 {
331 auto room = rooms_->getRoomById(roomid).get();
332 auto model = new ImagePackListModel(roomid.toStdString());
333 QQmlEngine::setObjectOwnership(model, QQmlEngine::JavaScriptOwnership);
334 emit showImagePackSettings(room, model);
335 }
336
337 void
338 TimelineViewManager::saveMedia(QString mxcUrl)
339 {
340 const QString downloadsFolder =
341 QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
342 const QString openLocation = downloadsFolder + "/" + mxcUrl.split(u'/').constLast();
343
344 const QString filename = QFileDialog::getSaveFileName(nullptr, {}, openLocation);
345
346 if (filename.isEmpty())
347 return;
348
349 const auto url = mxcUrl.toStdString();
350
351 http::client()->download(url,
352 [filename, url](const std::string &data,
353 const std::string &,
354 const std::string &,
355 mtx::http::RequestErr err) {
356 if (err) {
357 nhlog::net()->warn("failed to retrieve image {}: {} {}",
358 url,
359 err->matrix_error.error,
360 static_cast<int>(err->status_code));
361 return;
362 }
363
364 try {
365 QFile file(filename);
366
367 if (!file.open(QIODevice::WriteOnly))
368 return;
369
370 file.write(QByteArray(data.data(), (int)data.size()));
371 file.close();
372 utils::markFileAsFromWeb(filename);
373
374 return;
375 } catch (const std::exception &e) {
376 nhlog::ui()->warn("Error while saving file to: {}", e.what());
377 }
378 });
379 }
380
381 void
382 TimelineViewManager::copyImage(const QString &mxcUrl) const
383 {
384 const auto url = mxcUrl.toStdString();
385 QString mimeType;
386
387 http::client()->download(
388 url,
389 [url, mimeType](const std::string &data,
390 const std::string &,
391 const std::string &,
392 mtx::http::RequestErr err) {
393 if (err) {
394 nhlog::net()->warn("failed to retrieve media {}: {} {}",
395 url,
396 err->matrix_error.error,
397 static_cast<int>(err->status_code));
398 return;
399 }
400
401 try {
402 auto img = utils::readImage(QByteArray(data.data(), (qsizetype)data.size()));
403 QGuiApplication::clipboard()->setImage(img);
404
405 return;
406 } catch (const std::exception &e) {
407 nhlog::ui()->warn("Error while copying file to clipboard: {}", e.what());
408 }
409 });
410 }
411
412 void
413 TimelineViewManager::updateReadReceipts(const QString &room_id,
414 const std::vector<QString> &event_ids)
415 {
416 if (auto room = rooms_->getRoomById(room_id)) {
417 room->markEventsAsRead(event_ids);
418 }
419 }
420
421 void
422 TimelineViewManager::receivedSessionKey(const std::string &room_id, const std::string &session_id)
423 {
424 if (auto room = rooms_->getRoomById(QString::fromStdString(room_id))) {
425 room->receivedSessionKey(session_id);
426 }
427 }
428
429 void
430 TimelineViewManager::initializeRoomlist()
431 {
432 rooms_->initializeRooms();
433 communities_->initializeSidebar();
434 }
435
436 void
437 TimelineViewManager::queueReply(const QString &roomid,
438 const QString &repliedToEvent,
439 const QString &replyBody)
440 {
441 if (auto room = rooms_->getRoomById(roomid)) {
442 room->setReply(repliedToEvent);
443 room->input()->message(replyBody);
444 }
445 }
446
447 void
448 TimelineViewManager::queueCallMessage(const QString &roomid,
449 const mtx::events::voip::CallInvite &callInvite)
450 {
451 if (auto room = rooms_->getRoomById(roomid))
452 room->sendMessageEvent(callInvite, mtx::events::EventType::CallInvite);
453 }
454
455 void
456 TimelineViewManager::queueCallMessage(const QString &roomid,
457 const mtx::events::voip::CallCandidates &callCandidates)
458 {
459 if (auto room = rooms_->getRoomById(roomid))
460 room->sendMessageEvent(callCandidates, mtx::events::EventType::CallCandidates);
461 }
462
463 void
464 TimelineViewManager::queueCallMessage(const QString &roomid,
465 const mtx::events::voip::CallAnswer &callAnswer)
466 {
467 if (auto room = rooms_->getRoomById(roomid))
468 room->sendMessageEvent(callAnswer, mtx::events::EventType::CallAnswer);
469 }
470
471 void
472 TimelineViewManager::queueCallMessage(const QString &roomid,
473 const mtx::events::voip::CallHangUp &callHangUp)
474 {
475 if (auto room = rooms_->getRoomById(roomid))
476 room->sendMessageEvent(callHangUp, mtx::events::EventType::CallHangUp);
477 }
478
479 void
480 TimelineViewManager::queueCallMessage(const QString &roomid,
481 const mtx::events::voip::CallSelectAnswer &callSelectAnswer)
482 {
483 if (auto room = rooms_->getRoomById(roomid))
484 room->sendMessageEvent(callSelectAnswer, mtx::events::EventType::CallSelectAnswer);
485 }
486 void
487 TimelineViewManager::queueCallMessage(const QString &roomid,
488 const mtx::events::voip::CallReject &callReject)
489 {
490 if (auto room = rooms_->getRoomById(roomid))
491 room->sendMessageEvent(callReject, mtx::events::EventType::CallReject);
492 }
493 void
494 TimelineViewManager::queueCallMessage(const QString &roomid,
495 const mtx::events::voip::CallNegotiate &callNegotiate)
496 {
497 if (auto room = rooms_->getRoomById(roomid))
498 room->sendMessageEvent(callNegotiate, mtx::events::EventType::CallNegotiate);
499 }
500
501 void
502 TimelineViewManager::focusMessageInput()
503 {
504 emit focusInput();
505 }
506
507 QAbstractItemModel *
508 TimelineViewManager::completerFor(const QString &completerName, const QString &roomId)
509 {
510 if (completerName == QLatin1String("user")) {
511 auto userModel = new UsersModel(roomId.toStdString());
512 auto proxy = new CompletionProxyModel(userModel);
513 userModel->setParent(proxy);
514 return proxy;
515 } else if (completerName == QLatin1String("emoji")) {
516 auto emojiModel = new CombinedImagePackModel(roomId.toStdString());
517 auto proxy = new CompletionProxyModel(emojiModel);
518 emojiModel->setParent(proxy);
519 return proxy;
520 } else if (completerName == QLatin1String("room")) {
521 auto roomModel = new RoomsModel(false);
522 auto proxy = new CompletionProxyModel(roomModel, 4);
523 roomModel->setParent(proxy);
524 return proxy;
525 } else if (completerName == QLatin1String("roomAliases")) {
526 auto roomModel = new RoomsModel(true);
527 auto proxy = new CompletionProxyModel(roomModel);
528 roomModel->setParent(proxy);
529 return proxy;
530 } else if (completerName == QLatin1String("emojigrid")) {
531 auto stickerModel = new GridImagePackModel(roomId.toStdString(), false);
532 return stickerModel;
533 } else if (completerName == QLatin1String("stickergrid")) {
534 auto stickerModel = new GridImagePackModel(roomId.toStdString(), true);
535 return stickerModel;
536 } else if (completerName == QLatin1String("command")) {
537 auto commandCompleter = new CommandCompleter();
538 auto proxy = new CompletionProxyModel(commandCompleter);
539 commandCompleter->setParent(proxy);
540 return proxy;
541 }
542 return nullptr;
543 }
544
545 void
546 TimelineViewManager::forwardMessageToRoom(mtx::events::collections::TimelineEvents const *e,
547 QString roomId)
548 {
549 auto room = rooms_->getRoomById(roomId);
550 auto content = mtx::accessors::url(*e);
551 std::optional<mtx::crypto::EncryptedFile> encryptionInfo = mtx::accessors::file(*e);
552
553 if (encryptionInfo && !cache::isRoomEncrypted(roomId.toStdString())) {
554 http::client()->download(
555 content,
556 [this, roomId, e, encryptionInfo](const std::string &res,
557 const std::string &content_type,
558 const std::string &originalFilename,
559 mtx::http::RequestErr err) {
560 if (err)
561 return;
562
563 auto data =
564 mtx::crypto::to_string(mtx::crypto::decrypt_file(res, encryptionInfo.value()));
565
566 http::client()->upload(
567 data,
568 content_type,
569 originalFilename,
570 [this, roomId, e](const mtx::responses::ContentURI &res,
571 mtx::http::RequestErr err) mutable {
572 if (err) {
573 nhlog::net()->warn("failed to upload media: {} {} ({})",
574 err->matrix_error.error,
575 to_string(err->matrix_error.errcode),
576 static_cast<int>(err->status_code));
577 return;
578 }
579
580 std::visit(
581 [this, roomId, url = res.content_uri](auto ev) {
582 using namespace mtx::events;
583 if constexpr (EventType::RoomMessage ==
584 message_content_to_type<decltype(ev.content)> ||
585 EventType::Sticker ==
586 message_content_to_type<decltype(ev.content)>) {
587 if constexpr (messageWithFileAndUrl(ev)) {
588 ev.content.relations.relations.clear();
589 ev.content.file.reset();
590 ev.content.url = url;
591 }
592
593 if (auto room = rooms_->getRoomById(roomId)) {
594 removeReplyFallback(ev);
595 ev.content.relations.relations.clear();
596 room->sendMessageEvent(ev.content,
597 mtx::events::EventType::RoomMessage);
598 }
599 }
600 },
601 *e);
602 });
603
604 return;
605 });
606
607 return;
608 }
609
610 std::visit(
611 [room](auto e) {
612 constexpr auto type = mtx::events::message_content_to_type<decltype(e.content)>;
613 if constexpr (type == mtx::events::EventType::RoomMessage ||
614 type == mtx::events::EventType::Sticker) {
615 e.content.relations.relations.clear();
616 removeReplyFallback(e);
617 room->sendMessageEvent(e.content, type);
618 }
619 },
620 *e);
621 }
622
623 //! WORKAROUND(Nico): for https://bugreports.qt.io/browse/QTBUG-93281
624 void
625 TimelineViewManager::fixImageRendering([[maybe_unused]] QQuickTextDocument *t,
626 [[maybe_unused]] QQuickItem *i)
627 {
628 #if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
629 if (t) {
630 QObject::connect(t->textDocument(), SIGNAL(imagesLoaded()), i, SLOT(updateWholeDocument()));
631 }
632 #endif
633 }
634
635 using IgnoredUsers = mtx::events::EphemeralEvent<mtx::events::account_data::IgnoredUsers>;
636
637 static QVector<QString>
638 convertIgnoredToQt(const IgnoredUsers &ev)
639 {
640 QVector<QString> users;
641 for (const mtx::events::account_data::IgnoredUser &user : ev.content.users) {
642 users.push_back(QString::fromStdString(user.id));
643 }
644
645 return users;
646 }
647
648 QVector<QString>
649 TimelineViewManager::getIgnoredUsers()
650 {
651 const auto cache = cache::client()->getAccountData(mtx::events::EventType::IgnoredUsers);
652 if (!cache) {
653 return {};
654 }
655
656 return convertIgnoredToQt(std::get<IgnoredUsers>(*cache));
657 }
658
659 void
660 TimelineViewManager::processIgnoredUsers(const mtx::responses::AccountData &data)
661 {
662 for (const mtx::events::collections::RoomAccountDataEvents::variant &ev : data.events) {
663 if (!std::holds_alternative<IgnoredUsers>(ev)) {
664 continue;
665 }
666 const auto &ignoredEv = std::get<IgnoredUsers>(ev);
667
668 emit this->ignoredUsersChanged(convertIgnoredToQt(ignoredEv));
669 break;
670 }
671 }
672 #include "moc_TimelineViewManager.cpp"