Debian Codegraph @

src/ui/UserProfile.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include <QFileDialog>
6 #include <QImageReader>
7 #include <QMimeDatabase>
8 #include <QStandardPaths>
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 "UserProfile.h"
17 #include "Utils.h"
18 #include "encryption/VerificationManager.h"
19 #include "timeline/RoomlistModel.h"
20 #include "timeline/TimelineModel.h"
21 #include "timeline/TimelineViewManager.h"
22 #include "ui/UIA.h"
23
24 UserProfile::UserProfile(const QString &roomid,
25 const QString &userid,
26 TimelineViewManager *manager_,
27 TimelineModel *parent)
28 : QObject(parent)
29 , roomid_(roomid)
30 , userid_(userid)
31 , globalAvatarUrl{QLatin1String("")}
32 , manager(manager_)
33 , model(parent)
34 {
35 connect(this,
36 &UserProfile::globalUsernameRetrieved,
37 this,
38 &UserProfile::setGlobalUsername,
39 Qt::QueuedConnection);
40 connect(this,
41 &UserProfile::verificationStatiChanged,
42 this,
43 &UserProfile::updateVerificationStatus,
44 Qt::QueuedConnection);
45
46 if (isGlobalUserProfile()) {
47 getGlobalProfileData();
48 }
49
50 if (!cache::client() || !cache::client()->isDatabaseReady() ||
51 !ChatPage::instance()->timelineManager())
52 return;
53
54 connect(
55 cache::client(), &Cache::verificationStatusChanged, this, [this](const std::string &user_id) {
56 if (user_id != this->userid_.toStdString())
57 return;
58
59 emit verificationStatiChanged();
60 });
61 fetchDeviceList(this->userid_);
62
63 if (userid != utils::localUser())
64 sharedRooms_ =
65 new RoomInfoModel(cache::client()->getCommonRooms(userid.toStdString()), this);
66 else
67 sharedRooms_ = new RoomInfoModel({}, this);
68
69 connect(ChatPage::instance(), &ChatPage::syncUI, this, [this](const mtx::responses::Sync &res) {
70 if (auto ignoreEv = std::ranges::find_if(
71 res.account_data.events,
72 [](const mtx::events::collections::RoomAccountDataEvents &e) {
73 return std::holds_alternative<
74 mtx::events::AccountDataEvent<mtx::events::account_data::IgnoredUsers>>(e);
75 });
76 ignoreEv != res.account_data.events.end()) {
77 // doesn't matter much if it was actually us
78 emit ignoredChanged();
79 }
80 });
81 }
82
83 QHash<int, QByteArray>
84 DeviceInfoModel::roleNames() const
85 {
86 return {
87 {DeviceId, "deviceId"},
88 {DeviceName, "deviceName"},
89 {VerificationStatus, "verificationStatus"},
90 {LastIp, "lastIp"},
91 {LastTs, "lastTs"},
92 };
93 }
94
95 QVariant
96 DeviceInfoModel::data(const QModelIndex &index, int role) const
97 {
98 if (!index.isValid() || index.row() >= (int)deviceList_.size() || index.row() < 0)
99 return {};
100
101 switch (role) {
102 case DeviceId:
103 return deviceList_[index.row()].device_id;
104 case DeviceName:
105 return deviceList_[index.row()].display_name;
106 case VerificationStatus:
107 return QVariant::fromValue(deviceList_[index.row()].verification_status);
108 case LastIp:
109 return deviceList_[index.row()].lastIp;
110 case LastTs:
111 return deviceList_[index.row()].lastTs;
112 default:
113 return {};
114 }
115 }
116
117 void
118 DeviceInfoModel::reset(const std::vector<DeviceInfo> &deviceList)
119 {
120 beginResetModel();
121 this->deviceList_ = std::move(deviceList);
122 endResetModel();
123 }
124
125 RoomInfoModel::RoomInfoModel(const std::map<std::string, RoomInfo> &raw, QObject *parent)
126 : QAbstractListModel(parent)
127 {
128 for (const auto &e : raw)
129 roomInfos_.push_back(e);
130 }
131
132 QHash<int, QByteArray>
133 RoomInfoModel::roleNames() const
134 {
135 return {
136 {RoomId, "roomId"},
137 {RoomName, "roomName"},
138 {AvatarUrl, "avatarUrl"},
139 };
140 }
141
142 QVariant
143 RoomInfoModel::data(const QModelIndex &index, int role) const
144 {
145 if (!index.isValid() || index.row() >= (int)roomInfos_.size() || index.row() < 0)
146 return {};
147
148 switch (role) {
149 case RoomId:
150 return QString::fromStdString(roomInfos_[index.row()].first);
151 case RoomName:
152 return QString::fromStdString(roomInfos_[index.row()].second.name);
153 case AvatarUrl:
154 return QString::fromStdString(roomInfos_[index.row()].second.avatar_url);
155 default:
156 return {};
157 }
158 }
159
160 DeviceInfoModel *
161 UserProfile::deviceList()
162 {
163 return &this->deviceList_;
164 }
165
166 RoomInfoModel *
167 UserProfile::sharedRooms()
168 {
169 return this->sharedRooms_;
170 }
171
172 QString
173 UserProfile::userid()
174 {
175 return this->userid_;
176 }
177
178 QString
179 UserProfile::displayName()
180 {
181 return isGlobalUserProfile() ? globalUsername : cache::displayName(roomid_, userid_);
182 }
183
184 QString
185 UserProfile::avatarUrl()
186 {
187 return isGlobalUserProfile() ? globalAvatarUrl : cache::avatarUrl(roomid_, userid_);
188 }
189
190 bool
191 UserProfile::isGlobalUserProfile() const
192 {
193 return roomid_ == QLatin1String("");
194 }
195
196 crypto::Trust
197 UserProfile::getUserStatus()
198 {
199 return isUserVerified;
200 }
201
202 bool
203 UserProfile::userVerificationEnabled() const
204 {
205 return hasMasterKey;
206 }
207 bool
208 UserProfile::isSelf() const
209 {
210 return this->userid_ == utils::localUser();
211 }
212
213 void
214 UserProfile::signOutDevice(const QString &deviceID)
215 {
216 http::client()->delete_device(
217 deviceID.toStdString(),
218 UIA::instance()->genericHandler(tr("Sign out device %1").arg(deviceID)),
219 [this, deviceID](mtx::http::RequestErr e) {
220 if (e) {
221 nhlog::ui()->critical("Failure when attempting to sign out device {}",
222 deviceID.toStdString());
223 return;
224 }
225 nhlog::ui()->info("Device {} successfully signed out!", deviceID.toStdString());
226 // This is us. Let's update the interface accordingly
227 if (isSelf() && deviceID.toStdString() == ::http::client()->device_id()) {
228 ChatPage::instance()->dropToLoginPageCb(tr("You signed out this device."));
229 }
230 refreshDevices();
231 });
232 }
233
234 void
235 UserProfile::refreshDevices()
236 {
237 cache::client()->markUserKeysOutOfDate({this->userid_.toStdString()});
238 fetchDeviceList(this->userid_);
239 }
240
241 bool
242 UserProfile::ignored() const
243 {
244 auto old = TimelineViewManager::instance()->getIgnoredUsers();
245 return old.contains(userid_);
246 }
247
248 void
249 UserProfile::setIgnored(bool ignore)
250 {
251 auto old = TimelineViewManager::instance()->getIgnoredUsers();
252 if (ignore) {
253 if (old.contains(userid_)) {
254 emit ignoredChanged();
255 return;
256 }
257 old.append(userid_);
258 } else {
259 if (!old.contains(userid_)) {
260 emit ignoredChanged();
261 return;
262 }
263 old.removeAll(userid_);
264 }
265
266 std::vector<mtx::events::account_data::IgnoredUser> content;
267 for (const QString &item : std::as_const(old)) {
268 content.push_back({item.toStdString()});
269 }
270
271 mtx::events::account_data::IgnoredUsers payload{.users{content}};
272
273 auto userid = userid_;
274
275 http::client()->put_account_data(payload, [userid](mtx::http::RequestErr e) {
276 if (e) {
277 MainWindow::instance()->showNotification(
278 tr("Failed to ignore \"%1\": %2")
279 .arg(userid, QString::fromStdString(e->matrix_error.error)));
280 }
281 });
282
283 if (ignore) {
284 const QHash<QString, RoomInfo> invites = cache::invites();
285 FilteredRoomlistModel *room_model = FilteredRoomlistModel::instance();
286
287 for (auto room = invites.keyBegin(), end = invites.keyEnd(); room != end; room++) {
288 if (room_model->getRoomPreviewById(*room).inviterUserId() == userid) {
289 room_model->declineInvite(*room);
290 }
291 }
292 }
293 }
294
295 void
296 UserProfile::fetchDeviceList(const QString &userID)
297 {
298 if (!cache::client() || !cache::client()->isDatabaseReady())
299 return;
300
301 cache::client()->query_keys(
302 userID.toStdString(),
303 [other_user_id = userID.toStdString(), this](const UserKeyCache &,
304 mtx::http::RequestErr err) {
305 if (err) {
306 nhlog::net()->warn("failed to query device keys: {}", *err);
307 }
308
309 // Ensure local key cache is up to date
310 cache::client()->query_keys(
311 utils::localUser().toStdString(),
312 [this](const UserKeyCache &, mtx::http::RequestErr err) {
313 using namespace mtx;
314 std::string local_user_id = utils::localUser().toStdString();
315
316 if (err) {
317 nhlog::net()->warn("failed to query device keys: {}", *err);
318 }
319
320 emit verificationStatiChanged();
321 });
322 });
323 }
324
325 void
326 UserProfile::updateVerificationStatus()
327 {
328 if (!cache::client() || !cache::client()->isDatabaseReady())
329 return;
330
331 auto user_keys = cache::client()->userKeys(userid_.toStdString());
332 if (!user_keys) {
333 this->hasMasterKey = false;
334 this->isUserVerified = crypto::Trust::Unverified;
335 this->deviceList_.reset({});
336 emit userStatusChanged();
337 return;
338 }
339
340 this->hasMasterKey = !user_keys->master_keys.keys.empty();
341
342 std::vector<DeviceInfo> deviceInfo;
343 auto devices = user_keys->device_keys;
344 auto verificationStatus = cache::client()->verificationStatus(userid_.toStdString());
345
346 this->isUserVerified = verificationStatus.user_verified;
347 emit userStatusChanged();
348
349 deviceInfo.reserve(devices.size());
350 for (const auto &d : devices) {
351 auto device = d.second;
352 verification::Status verified =
353 std::find(verificationStatus.verified_devices.begin(),
354 verificationStatus.verified_devices.end(),
355 device.device_id) == verificationStatus.verified_devices.end()
356 ? verification::UNVERIFIED
357 : verification::VERIFIED;
358
359 if (isSelf() && device.device_id == ::http::client()->device_id())
360 verified = verification::Status::SELF;
361
362 deviceInfo.emplace_back(QString::fromStdString(d.first),
363 QString::fromStdString(device.unsigned_info.device_display_name),
364 verified);
365 }
366
367 // For self, also query devices without keys
368 if (isSelf()) {
369 http::client()->query_devices(
370 [this, deviceInfo](const mtx::responses::QueryDevices &allDevs,
371 mtx::http::RequestErr err) mutable {
372 if (err) {
373 nhlog::net()->warn("failed to query device keys: {}", *err);
374 this->deviceList_.queueReset(std::move(deviceInfo));
375 emit devicesChanged();
376 return;
377 }
378 for (const auto &d : allDevs.devices) {
379 // First, check if we already have an entry for this device
380 bool found = false;
381 for (auto &e : deviceInfo) {
382 if (e.device_id.toStdString() == d.device_id) {
383 found = true;
384 // Gottem! Let's fill in the blanks
385 e.lastIp = QString::fromStdString(d.last_seen_ip);
386 e.lastTs = static_cast<qlonglong>(d.last_seen_ts);
387 break;
388 }
389 }
390 // No entry? Let's add one.
391 if (!found) {
392 deviceInfo.emplace_back(QString::fromStdString(d.device_id),
393 QString::fromStdString(d.display_name),
394 verification::NOT_APPLICABLE,
395 QString::fromStdString(d.last_seen_ip),
396 d.last_seen_ts);
397 }
398 }
399
400 this->deviceList_.queueReset(std::move(deviceInfo));
401 emit devicesChanged();
402 });
403 return;
404 }
405
406 this->deviceList_.queueReset(std::move(deviceInfo));
407 emit devicesChanged();
408 }
409
410 void
411 UserProfile::banUser()
412 {
413 ChatPage::instance()->banUser(roomid_, this->userid_, QLatin1String(""));
414 }
415
416 void
417 UserProfile::kickUser()
418 {
419 ChatPage::instance()->kickUser(roomid_, this->userid_, QLatin1String(""));
420 }
421
422 void
423 UserProfile::startChat(bool encryption)
424 {
425 ChatPage::instance()->startChat(this->userid_, encryption);
426 }
427
428 void
429 UserProfile::startChat()
430 {
431 ChatPage::instance()->startChat(this->userid_, std::nullopt);
432 }
433
434 void
435 UserProfile::changeUsername(const QString &username)
436 {
437 if (isGlobalUserProfile()) {
438 // change global
439 http::client()->set_displayname(username.toStdString(), [](mtx::http::RequestErr err) {
440 if (err) {
441 nhlog::net()->warn("could not change username: {}", *err);
442 return;
443 }
444 });
445 } else {
446 // change room username
447 mtx::events::state::Member member;
448 member.display_name = username.toStdString();
449 member.avatar_url =
450 cache::avatarUrl(roomid_, QString::fromStdString(http::client()->user_id().to_string()))
451 .toStdString();
452 member.membership = mtx::events::state::Membership::Join;
453
454 updateRoomMemberState(std::move(member));
455 }
456 }
457
458 void
459 UserProfile::changeDeviceName(const QString &deviceID, const QString &deviceName)
460 {
461 http::client()->set_device_name(
462 deviceID.toStdString(), deviceName.toStdString(), [this](mtx::http::RequestErr err) {
463 if (err) {
464 nhlog::net()->warn("could not change device name: {}", *err);
465 return;
466 }
467 refreshDevices();
468 });
469 }
470
471 void
472 UserProfile::verify(QString device)
473 {
474 if (!device.isEmpty())
475 manager->verificationManager()->verifyDevice(userid_, device);
476 else {
477 manager->verificationManager()->verifyUser(userid_);
478 }
479 }
480
481 void
482 UserProfile::unverify(const QString &device)
483 {
484 cache::markDeviceUnverified(userid_.toStdString(), device.toStdString());
485 }
486
487 void
488 UserProfile::setGlobalUsername(const QString &globalUser)
489 {
490 globalUsername = globalUser;
491 emit displayNameChanged();
492 }
493
494 void
495 UserProfile::changeAvatar()
496 {
497 const QString picturesFolder =
498 QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
499 const QString fileName = QFileDialog::getOpenFileName(
500 nullptr, tr("Select an avatar"), picturesFolder, tr("All Files (*)"));
501
502 if (fileName.isEmpty())
503 return;
504
505 QMimeDatabase db;
506 QMimeType mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent);
507
508 const auto format = mime.name().split(QStringLiteral("/"))[0];
509
510 QFile file{fileName, this};
511 if (format != QLatin1String("image")) {
512 emit displayError(tr("The selected file is not an image"));
513 return;
514 }
515
516 if (!file.open(QIODevice::ReadOnly)) {
517 emit displayError(tr("Error while reading file: %1").arg(file.errorString()));
518 return;
519 }
520
521 const auto bin = file.peek(file.size());
522 const auto payload = std::string(bin.data(), bin.size());
523
524 isLoading_ = true;
525 emit loadingChanged();
526
527 // First we need to create a new mxc URI
528 // (i.e upload media to the Matrix content repository) for the new avatar.
529 http::client()->upload(
530 payload,
531 mime.name().toStdString(),
532 QFileInfo(fileName).fileName().toStdString(),
533 [this,
534 payload,
535 mimetype = mime.name().toStdString(),
536 size = payload.size(),
537 room_id = roomid_.toStdString(),
538 content = std::move(bin)](const mtx::responses::ContentURI &res, mtx::http::RequestErr err) {
539 if (err) {
540 nhlog::ui()->error("Failed to upload image: {}", *err);
541 return;
542 }
543
544 if (isGlobalUserProfile()) {
545 http::client()->set_avatar_url(res.content_uri, [this](mtx::http::RequestErr err) {
546 if (err) {
547 nhlog::ui()->error("Failed to set user avatar url: {}", *err);
548 }
549
550 isLoading_ = false;
551 emit loadingChanged();
552 getGlobalProfileData();
553 });
554 } else {
555 // change room username
556 mtx::events::state::Member member;
557 member.display_name = cache::displayName(roomid_, userid_).toStdString();
558 member.avatar_url = res.content_uri;
559 member.membership = mtx::events::state::Membership::Join;
560
561 updateRoomMemberState(std::move(member));
562 }
563 });
564 }
565
566 void
567 UserProfile::updateRoomMemberState(mtx::events::state::Member member)
568 {
569 http::client()->send_state_event(roomid_.toStdString(),
570 http::client()->user_id().to_string(),
571 member,
572 [](mtx::responses::EventId, mtx::http::RequestErr err) {
573 if (err)
574 nhlog::net()->error(
575 "Failed to update room member state: {}", *err);
576 });
577 }
578
579 void
580 UserProfile::updateAvatarUrl()
581 {
582 isLoading_ = false;
583 emit loadingChanged();
584
585 emit avatarUrlChanged();
586 }
587
588 bool
589 UserProfile::isLoading() const
590 {
591 return isLoading_;
592 }
593
594 void
595 UserProfile::getGlobalProfileData()
596 {
597 auto profProx = std::make_shared<UserProfileFetchProxy>();
598 connect(profProx.get(),
599 &UserProfileFetchProxy::profileFetched,
600 this,
601 [this](const mtx::responses::Profile &res) {
602 emit globalUsernameRetrieved(QString::fromStdString(res.display_name));
603 globalAvatarUrl = QString::fromStdString(res.avatar_url);
604 emit avatarUrlChanged();
605 });
606
607 connect(profProx.get(),
608 &UserProfileFetchProxy::failedToFetchProfile,
609 this,
610 &UserProfile::failedToFetchProfile);
611
612 http::client()->get_profile(userid_.toStdString(),
613 [prox = std::move(profProx), user = userid_.toStdString()](
614 const mtx::responses::Profile &res, mtx::http::RequestErr err) {
615 if (err) {
616 nhlog::net()->warn("failed to retrieve profile info for {}",
617 user);
618 emit prox->failedToFetchProfile();
619 return;
620 }
621
622 emit prox->profileFetched(res);
623 });
624 }
625
626 void
627 UserProfile::openGlobalProfile()
628 {
629 emit manager->openGlobalUserProfile(userid_);
630 }
631
632 #include "moc_UserProfile.cpp"