| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include <QApplication> |
| 6 | #include <QInputDialog> |
| 7 | #include <QMessageBox> |
| 8 | |
| 9 | #include <algorithm> |
| 10 | #include <unordered_set> |
| 11 | |
| 12 | #include <nlohmann/json.hpp> |
| 13 | |
| 14 | #include <mtx/responses.hpp> |
| 15 | |
| 16 | #include "AvatarProvider.h" |
| 17 | #include "Cache.h" |
| 18 | #include "Cache_p.h" |
| 19 | #include "ChatPage.h" |
| 20 | #include "EventAccessors.h" |
| 21 | #include "Logging.h" |
| 22 | #include "MainWindow.h" |
| 23 | #include "MatrixClient.h" |
| 24 | #include "UserSettingsPage.h" |
| 25 | #include "Utils.h" |
| 26 | #include "encryption/DeviceVerificationFlow.h" |
| 27 | #include "encryption/Olm.h" |
| 28 | #include "ui/RoomSummary.h" |
| 29 | #include "ui/UserProfile.h" |
| 30 | #include "voip/CallManager.h" |
| 31 | |
| 32 | #include "notifications/Manager.h" |
| 33 | |
| 34 | #include "timeline/RoomlistModel.h" |
| 35 | #include "timeline/TimelineModel.h" |
| 36 | #include "timeline/TimelineViewManager.h" |
| 37 | |
| 38 | ChatPage *ChatPage::instance_ = nullptr; |
| 39 | static constexpr int CHECK_CONNECTIVITY_INTERVAL = 15'000; |
| 40 | static constexpr int RETRY_TIMEOUT = 5'000; |
| 41 | static constexpr size_t MAX_ONETIME_KEYS = 50; |
| 42 | |
| 43 | ChatPage::ChatPage(QSharedPointer<UserSettings> userSettings, QObject *parent) |
| 44 | : QObject(parent) |
| 45 | , isConnected_(true) |
| 46 | , userSettings_{userSettings} |
| 47 | , notificationsManager(new NotificationsManager(this)) |
| 48 | , callManager_(new CallManager(this)) |
| 49 | { |
| 50 | setObjectName(QStringLiteral("chatPage")); |
| 51 | |
| 52 | instance_ = this; |
| 53 | |
| 54 | view_manager_ = new TimelineViewManager(callManager_, this); |
| 55 | |
| 56 | connect(this, |
| 57 | &ChatPage::downloadedSecrets, |
| 58 | this, |
| 59 | &ChatPage::decryptDownloadedSecrets, |
| 60 | Qt::QueuedConnection); |
| 61 | |
| 62 | connect(this, &ChatPage::connectionLost, this, [this]() { |
| 63 | nhlog::net()->info("connectivity lost"); |
| 64 | isConnected_ = false; |
| 65 | http::client()->shutdown(); |
| 66 | }); |
| 67 | connect(this, &ChatPage::connectionRestored, this, [this]() { |
| 68 | nhlog::net()->info("trying to re-connect"); |
| 69 | isConnected_ = true; |
| 70 | |
| 71 | // Drop all pending connections. |
| 72 | http::client()->shutdown(); |
| 73 | trySync(); |
| 74 | }); |
| 75 | |
| 76 | connectivityTimer_.setInterval(CHECK_CONNECTIVITY_INTERVAL); |
| 77 | connect(&connectivityTimer_, &QTimer::timeout, this, [this]() { |
| 78 | if (http::client()->access_token().empty()) { |
| 79 | connectivityTimer_.stop(); |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | http::client()->versions( |
| 84 | [this](const mtx::responses::Versions &, mtx::http::RequestErr err) { |
| 85 | if (err) { |
| 86 | emit connectionLost(); |
| 87 | return; |
| 88 | } |
| 89 | |
| 90 | // only update spaces every 20 minutes |
| 91 | if (lastSpacesUpdate < QDateTime::currentDateTime().addSecs(-20 * 60)) { |
| 92 | lastSpacesUpdate = QDateTime::currentDateTime(); |
| 93 | utils::updateSpaceVias(); |
| 94 | utils::removeExpiredEvents(); |
| 95 | } |
| 96 | |
| 97 | if (!isConnected_) |
| 98 | emit connectionRestored(); |
| 99 | }); |
| 100 | }); |
| 101 | |
| 102 | connect(this, &ChatPage::loggedOut, this, &ChatPage::logout); |
| 103 | |
| 104 | connect( |
| 105 | view_manager_, |
| 106 | &TimelineViewManager::inviteUsers, |
| 107 | this, |
| 108 | [this](QString roomId, QStringList users) { |
| 109 | for (int ii = 0; ii < users.size(); ++ii) { |
| 110 | QTimer::singleShot(ii * 500, this, [this, roomId, ii, users]() { |
| 111 | const auto user = users.at(ii); |
| 112 | |
| 113 | http::client()->invite_user( |
| 114 | roomId.toStdString(), |
| 115 | user.toStdString(), |
| 116 | [this, user](const mtx::responses::RoomInvite &, mtx::http::RequestErr err) { |
| 117 | if (err) { |
| 118 | emit showNotification(tr("Failed to invite user: %1").arg(user)); |
| 119 | return; |
| 120 | } |
| 121 | |
| 122 | emit showNotification(tr("Invited user: %1").arg(user)); |
| 123 | }); |
| 124 | }); |
| 125 | } |
| 126 | }); |
| 127 | |
| 128 | connect(this, |
| 129 | &ChatPage::internalKnock, |
| 130 | this, |
| 131 | qOverload<const QString &, const std::vector<std::string> &, QString, bool, bool>( |
| 132 | &ChatPage::knockRoom), |
| 133 | Qt::QueuedConnection); |
| 134 | connect(this, &ChatPage::leftRoom, this, &ChatPage::removeRoom); |
| 135 | connect(this, &ChatPage::changeToRoom, this, &ChatPage::changeRoom, Qt::QueuedConnection); |
| 136 | connect(notificationsManager, |
| 137 | &NotificationsManager::notificationClicked, |
| 138 | this, |
| 139 | [this](const QString &roomid, const QString &eventid) { |
| 140 | Q_UNUSED(eventid) |
| 141 | auto exWin = MainWindow::instance()->windowForRoom(roomid); |
| 142 | if (exWin) { |
| 143 | exWin->setVisible(true); |
| 144 | exWin->raise(); |
| 145 | exWin->requestActivate(); |
| 146 | } else { |
| 147 | view_manager_->rooms()->setCurrentRoom(roomid); |
| 148 | MainWindow::instance()->setVisible(true); |
| 149 | MainWindow::instance()->raise(); |
| 150 | MainWindow::instance()->requestActivate(); |
| 151 | } |
| 152 | }); |
| 153 | connect(notificationsManager, |
| 154 | &NotificationsManager::sendNotificationReply, |
| 155 | this, |
| 156 | &ChatPage::sendNotificationReply); |
| 157 | |
| 158 | connect( |
| 159 | this, |
| 160 | &ChatPage::initializeViews, |
| 161 | view_manager_, |
| 162 | [this](const mtx::responses::Sync &sync) { view_manager_->sync(sync); }, |
| 163 | Qt::QueuedConnection); |
| 164 | connect(this, |
| 165 | &ChatPage::initializeEmptyViews, |
| 166 | view_manager_, |
| 167 | &TimelineViewManager::initializeRoomlist); |
| 168 | connect(this, &ChatPage::syncUI, this, [this](const mtx::responses::Sync &sync) { |
| 169 | view_manager_->sync(sync); |
| 170 | |
| 171 | static unsigned int prevNotificationCount = 0; |
| 172 | unsigned int notificationCount = 0; |
| 173 | for (const auto &room : sync.rooms.join) { |
| 174 | notificationCount += |
| 175 | static_cast<unsigned int>(room.second.unread_notifications.notification_count); |
| 176 | } |
| 177 | |
| 178 | // HACK: If we had less notifications last time we checked, send an alert if the |
| 179 | // user wanted one. Technically, this may cause an alert to be missed if new ones |
| 180 | // come in while you are reading old ones. Since the window is almost certainly open |
| 181 | // in this edge case, that's probably a non-issue. |
| 182 | // TODO: Replace this once we have proper pushrules support. This is a horrible hack |
| 183 | if (prevNotificationCount < notificationCount) { |
| 184 | if (userSettings_->hasAlertOnNotification()) |
| 185 | MainWindow::instance()->alert(0); |
| 186 | } |
| 187 | prevNotificationCount = notificationCount; |
| 188 | |
| 189 | // No need to check amounts for this section, as this function internally checks for |
| 190 | // duplicates. |
| 191 | if (notificationCount && userSettings_->hasNotifications()) |
| 192 | for (const auto &e : sync.account_data.events) { |
| 193 | if (auto newRules = |
| 194 | std::get_if<mtx::events::AccountDataEvent<mtx::pushrules::GlobalRuleset>>(&e)) |
| 195 | pushrules = |
| 196 | std::make_unique<mtx::pushrules::PushRuleEvaluator>(newRules->content.global); |
| 197 | } |
| 198 | if (!pushrules) { |
| 199 | auto eventInDb = cache::client()->getAccountData(mtx::events::EventType::PushRules); |
| 200 | if (eventInDb) { |
| 201 | if (auto newRules = |
| 202 | std::get_if<mtx::events::AccountDataEvent<mtx::pushrules::GlobalRuleset>>( |
| 203 | &*eventInDb)) { |
| 204 | pushrules = |
| 205 | std::make_unique<mtx::pushrules::PushRuleEvaluator>(newRules->content.global); |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | if (pushrules) { |
| 210 | const auto local_user = utils::localUser().toStdString(); |
| 211 | |
| 212 | // Desktop notifications to be sent |
| 213 | std::vector<std::tuple<QSharedPointer<TimelineModel>, |
| 214 | mtx::events::collections::TimelineEvents, |
| 215 | std::string, |
| 216 | std::vector<mtx::pushrules::actions::Action>>> |
| 217 | notifications; |
| 218 | for (const auto &[room_id, room] : sync.rooms.join) { |
| 219 | // clear old notifications |
| 220 | for (const auto &e : room.ephemeral.events) { |
| 221 | if (auto receiptsEv = |
| 222 | std::get_if<mtx::events::EphemeralEvent<mtx::events::ephemeral::Receipt>>( |
| 223 | &e)) { |
| 224 | std::vector<QString> receipts; |
| 225 | |
| 226 | for (const auto &[event_id, userReceipts] : receiptsEv->content.receipts) { |
| 227 | if (auto r = userReceipts.find(mtx::events::ephemeral::Receipt::Read); |
| 228 | r != userReceipts.end()) { |
| 229 | for (const auto &[user_id, receipt] : r->second.users) { |
| 230 | (void)receipt; |
| 231 | |
| 232 | if (user_id == local_user) { |
| 233 | receipts.push_back(QString::fromStdString(event_id)); |
| 234 | break; |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | if (auto r = |
| 239 | userReceipts.find(mtx::events::ephemeral::Receipt::ReadPrivate); |
| 240 | r != userReceipts.end()) { |
| 241 | for (const auto &[user_id, receipt] : r->second.users) { |
| 242 | (void)receipt; |
| 243 | |
| 244 | if (user_id == local_user) { |
| 245 | receipts.push_back(QString::fromStdString(event_id)); |
| 246 | break; |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | if (!receipts.empty()) |
| 252 | notificationsManager->removeNotifications( |
| 253 | QString::fromStdString(room_id), receipts); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // calculate new notifications |
| 258 | if (!room.timeline.events.empty() && |
| 259 | (room.unread_notifications.notification_count || |
| 260 | room.unread_notifications.highlight_count)) { |
| 261 | auto roomModel = |
| 262 | view_manager_->rooms()->getRoomById(QString::fromStdString(room_id)); |
| 263 | |
| 264 | if (!roomModel) { |
| 265 | continue; |
| 266 | } |
| 267 | |
| 268 | auto currentReadMarker = |
| 269 | cache::getEventIndex(room_id, cache::client()->getFullyReadEventId(room_id)); |
| 270 | |
| 271 | auto ctx = roomModel->pushrulesRoomContext(); |
| 272 | std::vector< |
| 273 | std::pair<mtx::common::Relation, mtx::events::collections::TimelineEvents>> |
| 274 | relatedEvents; |
| 275 | |
| 276 | for (const auto &event : room.timeline.events) { |
| 277 | auto event_id = mtx::accessors::event_id(event); |
| 278 | |
| 279 | // skip already read events |
| 280 | if (currentReadMarker && |
| 281 | currentReadMarker > cache::getEventIndex(room_id, event_id)) |
| 282 | continue; |
| 283 | |
| 284 | // skip our messages |
| 285 | auto sender = mtx::accessors::sender(event); |
| 286 | if (sender == http::client()->user_id().to_string()) |
| 287 | continue; |
| 288 | |
| 289 | mtx::events::collections::TimelineEvents te{event}; |
| 290 | std::visit( |
| 291 | [room_id_ = room_id](auto &event_) { event_.room_id = room_id_; }, te); |
| 292 | |
| 293 | if (auto encryptedEvent = |
| 294 | std::get_if<mtx::events::EncryptedEvent<mtx::events::msg::Encrypted>>( |
| 295 | &event); |
| 296 | encryptedEvent && userSettings_->decryptNotifications()) { |
| 297 | MegolmSessionIndex index(room_id, encryptedEvent->content); |
| 298 | |
| 299 | auto result = olm::decryptEvent(index, *encryptedEvent); |
| 300 | if (result.event) |
| 301 | te = std::move(result.event).value(); |
| 302 | } |
| 303 | |
| 304 | relatedEvents.clear(); |
| 305 | for (const auto &r : mtx::accessors::relations(te).relations) { |
| 306 | auto related = cache::client()->getEvent(room_id, r.event_id); |
| 307 | if (related) { |
| 308 | relatedEvents.emplace_back(r, *related); |
| 309 | if (auto encryptedEvent = std::get_if< |
| 310 | mtx::events::EncryptedEvent<mtx::events::msg::Encrypted>>( |
| 311 | &related.value()); |
| 312 | encryptedEvent && userSettings_->decryptNotifications()) { |
| 313 | MegolmSessionIndex index(room_id, encryptedEvent->content); |
| 314 | |
| 315 | auto result = olm::decryptEvent(index, *encryptedEvent); |
| 316 | if (result.event) |
| 317 | relatedEvents.back().second = |
| 318 | std::move(result.event).value(); |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | auto actions = pushrules->evaluate(te, ctx, relatedEvents); |
| 324 | if (std::find(actions.begin(), |
| 325 | actions.end(), |
| 326 | mtx::pushrules::actions::Action{ |
| 327 | mtx::pushrules::actions::notify{}}) != actions.end()) { |
| 328 | if (!cache::isNotificationSent(event_id)) { |
| 329 | // We should only send one notification per event. |
| 330 | cache::markSentNotification(event_id); |
| 331 | |
| 332 | // Don't send a notification when the current room is opened. |
| 333 | if (isRoomActive(roomModel->roomId())) |
| 334 | continue; |
| 335 | |
| 336 | if (userSettings_->hasDesktopNotifications()) { |
| 337 | notifications.emplace_back(roomModel, te, room_id, actions); |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | if (notifications.size() <= 5) { |
| 345 | for (const auto &[roomModel, te, room_id, actions] : notifications) { |
| 346 | AvatarProvider::resolve( |
| 347 | roomModel->roomAvatarUrl(), |
| 348 | 96, |
| 349 | this, |
| 350 | [this, te_ = te, room_id_ = room_id, actions_ = actions](QPixmap image) { |
| 351 | notificationsManager->postNotification( |
| 352 | mtx::responses::Notification{ |
| 353 | .actions = actions_, |
| 354 | .event = std::move(te_), |
| 355 | .read = false, |
| 356 | .profile_tag = "", |
| 357 | .room_id = room_id_, |
| 358 | .ts = 0, |
| 359 | }, |
| 360 | image.toImage()); |
| 361 | }); |
| 362 | } |
| 363 | } else if (!notifications.empty()) { |
| 364 | std::map<QSharedPointer<TimelineModel>, std::size_t> missedEvents; |
| 365 | for (const auto &[roomModel, te, room_id, actions] : notifications) { |
| 366 | missedEvents[roomModel]++; |
| 367 | } |
| 368 | QString body; |
| 369 | for (const auto &[roomModel, nbNotifs] : missedEvents) { |
| 370 | body += tr("%n unread message(s) in room %1\n", nullptr, nbNotifs) |
| 371 | .arg(roomModel->roomName()); |
| 372 | } |
| 373 | emit notificationsManager->systemPostNotificationCb( |
| 374 | "", "", "New messages while away", body, QImage()); |
| 375 | } |
| 376 | } |
| 377 | }); |
| 378 | |
| 379 | connect( |
| 380 | this, &ChatPage::tryInitialSyncCb, this, &ChatPage::tryInitialSync, Qt::QueuedConnection); |
| 381 | connect(this, &ChatPage::trySyncCb, this, &ChatPage::trySync, Qt::QueuedConnection); |
| 382 | connect( |
| 383 | this, |
| 384 | &ChatPage::tryDelayedSyncCb, |
| 385 | this, |
| 386 | [this]() { QTimer::singleShot(RETRY_TIMEOUT, this, &ChatPage::trySync); }, |
| 387 | Qt::QueuedConnection); |
| 388 | |
| 389 | connect( |
| 390 | this, &ChatPage::newSyncResponse, this, &ChatPage::handleSyncResponse, Qt::QueuedConnection); |
| 391 | |
| 392 | connect(this, &ChatPage::dropToLoginPageCb, this, &ChatPage::dropToLoginPage); |
| 393 | |
| 394 | connect( |
| 395 | this, |
| 396 | &ChatPage::startRemoveFallbackKeyTimer, |
| 397 | this, |
| 398 | [this]() { |
| 399 | QTimer::singleShot(std::chrono::minutes(5), this, &ChatPage::removeOldFallbackKey); |
| 400 | disconnect( |
| 401 | this, &ChatPage::newSyncResponse, this, &ChatPage::startRemoveFallbackKeyTimer); |
| 402 | }, |
| 403 | Qt::QueuedConnection); |
| 404 | |
| 405 | connect( |
| 406 | this, |
| 407 | &ChatPage::callFunctionOnGuiThread, |
| 408 | this, |
| 409 | [](std::function<void()> f) { f(); }, |
| 410 | Qt::QueuedConnection); |
| 411 | |
| 412 | connect(qobject_cast<QGuiApplication *>(QGuiApplication::instance()), |
| 413 | &QGuiApplication::focusWindowChanged, |
| 414 | this, |
| 415 | [this](QWindow *activeWindow) { |
| 416 | if (activeWindow) { |
| 417 | nhlog::ui()->debug("Stopping inactive timer."); |
| 418 | lastWindowActive = QDateTime(); |
| 419 | } else { |
| 420 | nhlog::ui()->debug("Starting inactive timer."); |
| 421 | lastWindowActive = QDateTime::currentDateTime(); |
| 422 | } |
| 423 | }); |
| 424 | |
| 425 | connectCallMessage<mtx::events::voip::CallInvite>(); |
| 426 | connectCallMessage<mtx::events::voip::CallCandidates>(); |
| 427 | connectCallMessage<mtx::events::voip::CallAnswer>(); |
| 428 | connectCallMessage<mtx::events::voip::CallHangUp>(); |
| 429 | connectCallMessage<mtx::events::voip::CallSelectAnswer>(); |
| 430 | connectCallMessage<mtx::events::voip::CallReject>(); |
| 431 | connectCallMessage<mtx::events::voip::CallNegotiate>(); |
| 432 | } |
| 433 | |
| 434 | void |
| 435 | ChatPage::logout() |
| 436 | { |
| 437 | resetUI(); |
| 438 | deleteConfigs(); |
| 439 | |
| 440 | emit closing(); |
| 441 | connectivityTimer_.stop(); |
| 442 | } |
| 443 | |
| 444 | void |
| 445 | ChatPage::dropToLoginPage(const QString &msg) |
| 446 | { |
| 447 | nhlog::ui()->info("dropping to the login page: {}", msg.toStdString()); |
| 448 | |
| 449 | http::client()->shutdown(); |
| 450 | connectivityTimer_.stop(); |
| 451 | |
| 452 | auto btn = QMessageBox::warning( |
| 453 | nullptr, |
| 454 | tr("Confirm logout"), |
| 455 | tr("Because of the following reason Nheko wants to drop you to the login page:\n%1\nIf you " |
| 456 | "think this is a mistake, you can close Nheko instead to possibly recover your encryption " |
| 457 | "keys. After you have been dropped to the login page, you can sign in again using your " |
| 458 | "usual methods.") |
| 459 | .arg(msg), |
| 460 | QMessageBox::StandardButton::Close | QMessageBox::StandardButton::Ok, |
| 461 | QMessageBox::StandardButton::Ok); |
| 462 | if (btn == QMessageBox::StandardButton::Close) { |
| 463 | QCoreApplication::exit(1); |
| 464 | exit(1); |
| 465 | } |
| 466 | |
| 467 | resetUI(); |
| 468 | deleteConfigs(); |
| 469 | |
| 470 | emit showLoginPage(msg); |
| 471 | } |
| 472 | |
| 473 | void |
| 474 | ChatPage::resetUI() |
| 475 | { |
| 476 | view_manager_->clearAll(); |
| 477 | |
| 478 | emit unreadMessages(0); |
| 479 | } |
| 480 | |
| 481 | void |
| 482 | ChatPage::deleteConfigs() |
| 483 | { |
| 484 | auto settings = UserSettings::instance()->qsettings(); |
| 485 | |
| 486 | if (UserSettings::instance()->profile() != QLatin1String("")) { |
| 487 | settings->beginGroup(QStringLiteral("profile")); |
| 488 | settings->beginGroup(UserSettings::instance()->profile()); |
| 489 | } |
| 490 | settings->beginGroup(QStringLiteral("auth")); |
| 491 | settings->remove(QLatin1String("")); |
| 492 | settings->endGroup(); // auth |
| 493 | if (UserSettings::instance()->profile() != QLatin1String("")) { |
| 494 | settings->endGroup(); // profilename |
| 495 | settings->endGroup(); // profile |
| 496 | } |
| 497 | |
| 498 | http::client()->shutdown(); |
| 499 | cache::deleteData(); |
| 500 | } |
| 501 | |
| 502 | void |
| 503 | ChatPage::bootstrap(QString userid, QString homeserver, QString token) |
| 504 | { |
| 505 | using namespace mtx::identifiers; |
| 506 | |
| 507 | try { |
| 508 | http::client()->set_user(parse<User>(userid.toStdString())); |
| 509 | } catch (const std::invalid_argument &) { |
| 510 | nhlog::ui()->critical("bootstrapped with invalid user_id: {}", userid.toStdString()); |
| 511 | } |
| 512 | |
| 513 | http::client()->set_server(homeserver.toStdString()); |
| 514 | http::client()->set_access_token(token.toStdString()); |
| 515 | http::client()->verify_certificates(!UserSettings::instance()->disableCertificateValidation()); |
| 516 | |
| 517 | // The Olm client needs the user_id & device_id that will be included |
| 518 | // in the generated payloads & keys. |
| 519 | olm::client()->set_user_id(http::client()->user_id().to_string()); |
| 520 | olm::client()->set_device_id(http::client()->device_id()); |
| 521 | |
| 522 | try { |
| 523 | cache::init(userid); |
| 524 | |
| 525 | connect(cache::client(), &Cache::databaseReady, this, [this]() { |
| 526 | nhlog::db()->info("database ready"); |
| 527 | |
| 528 | const bool isInitialized = cache::isInitialized(); |
| 529 | const auto cacheVersion = cache::formatVersion(); |
| 530 | |
| 531 | try { |
| 532 | if (!isInitialized) { |
| 533 | cache::setCurrentFormat(); |
| 534 | } else { |
| 535 | if (cacheVersion == cache::CacheVersion::Current) { |
| 536 | loadStateFromCache(); |
| 537 | return; |
| 538 | } else if (cacheVersion == cache::CacheVersion::Older) { |
| 539 | if (!cache::runMigrations()) { |
| 540 | QMessageBox::critical( |
| 541 | nullptr, |
| 542 | tr("Cache migration failed!"), |
| 543 | tr("Migrating the cache to the current version failed. " |
| 544 | "This can have different reasons. Please open an " |
| 545 | "issue at https://github.com/Nheko-Reborn/nheko and try to use an " |
| 546 | "older version in the meantime. Alternatively you can try " |
| 547 | "deleting the cache manually.")); |
| 548 | QCoreApplication::quit(); |
| 549 | } |
| 550 | loadStateFromCache(); |
| 551 | return; |
| 552 | } else if (cacheVersion == cache::CacheVersion::Newer) { |
| 553 | QMessageBox::critical( |
| 554 | nullptr, |
| 555 | tr("Incompatible cache version"), |
| 556 | tr("The cache on your disk is newer than this version of Nheko " |
| 557 | "supports. Please update Nheko or clear your cache.")); |
| 558 | QCoreApplication::quit(); |
| 559 | return; |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | // It's the first time syncing with this device |
| 564 | // There isn't a saved olm account to restore. |
| 565 | nhlog::crypto()->info("creating new olm account"); |
| 566 | olm::client()->create_new_account(); |
| 567 | cache::saveOlmAccount(olm::client()->save(cache::client()->pickleSecret())); |
| 568 | } catch (const lmdb::error &e) { |
| 569 | nhlog::crypto()->critical("failed to save olm account {}", e.what()); |
| 570 | emit dropToLoginPageCb(QString::fromStdString(e.what())); |
| 571 | return; |
| 572 | } catch (const mtx::crypto::olm_exception &e) { |
| 573 | nhlog::crypto()->critical("failed to create new olm account {}", e.what()); |
| 574 | emit dropToLoginPageCb(QString::fromStdString(e.what())); |
| 575 | return; |
| 576 | } |
| 577 | |
| 578 | getProfileInfo(); |
| 579 | getBackupVersion(); |
| 580 | tryInitialSync(); |
| 581 | callManager_->refreshTurnServer(); |
| 582 | emit MainWindow::instance()->reload(); |
| 583 | }); |
| 584 | |
| 585 | connect(cache::client(), |
| 586 | &Cache::newReadReceipts, |
| 587 | view_manager_, |
| 588 | &TimelineViewManager::updateReadReceipts); |
| 589 | |
| 590 | connect(cache::client(), &Cache::secretChanged, this, [this](const std::string &secret) { |
| 591 | if (secret == mtx::secret_storage::secrets::megolm_backup_v1) { |
| 592 | getBackupVersion(); |
| 593 | } |
| 594 | }); |
| 595 | } catch (const lmdb::error &e) { |
| 596 | nhlog::db()->critical("failure during boot: {}", e.what()); |
| 597 | emit dropToLoginPageCb(tr("Failed to open database, logging out!")); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | void |
| 602 | ChatPage::loadStateFromCache() |
| 603 | { |
| 604 | nhlog::db()->info("restoring state from cache"); |
| 605 | |
| 606 | try { |
| 607 | olm::client()->load(cache::restoreOlmAccount(), cache::client()->pickleSecret()); |
| 608 | |
| 609 | nhlog::db()->info("Removing old cached messages"); |
| 610 | cache::deleteOldData(); |
| 611 | nhlog::db()->info("Message removal done"); |
| 612 | |
| 613 | emit initializeEmptyViews(); |
| 614 | |
| 615 | cache::calculateRoomReadStatus(); |
| 616 | |
| 617 | } catch (const mtx::crypto::olm_exception &e) { |
| 618 | nhlog::crypto()->critical("failed to restore olm account: {}", e.what()); |
| 619 | emit dropToLoginPageCb(tr("Failed to restore OLM account. Please login again.")); |
| 620 | return; |
| 621 | } catch (const lmdb::error &e) { |
| 622 | nhlog::db()->critical("failed to restore cache: {}", e.what()); |
| 623 | emit dropToLoginPageCb(tr("Failed to restore save data. Please login again.")); |
| 624 | return; |
| 625 | } catch (const nlohmann::json::exception &e) { |
| 626 | nhlog::db()->critical("failed to parse cache data: {}", e.what()); |
| 627 | emit dropToLoginPageCb(tr("Failed to restore save data. Please login again.")); |
| 628 | return; |
| 629 | } catch (const std::exception &e) { |
| 630 | nhlog::db()->critical("failed to load cache data: {}", e.what()); |
| 631 | emit dropToLoginPageCb(tr("Failed to restore save data. Please login again.")); |
| 632 | return; |
| 633 | } |
| 634 | |
| 635 | nhlog::crypto()->info("ed25519 : {}", olm::client()->identity_keys().ed25519); |
| 636 | nhlog::crypto()->info("curve25519: {}", olm::client()->identity_keys().curve25519); |
| 637 | |
| 638 | getProfileInfo(); |
| 639 | getBackupVersion(); |
| 640 | verifyOneTimeKeyCountAfterStartup(); |
| 641 | callManager_->refreshTurnServer(); |
| 642 | |
| 643 | emit contentLoaded(); |
| 644 | |
| 645 | // Start receiving events. |
| 646 | connect(this, &ChatPage::newSyncResponse, &ChatPage::startRemoveFallbackKeyTimer); |
| 647 | emit trySyncCb(); |
| 648 | } |
| 649 | |
| 650 | void |
| 651 | ChatPage::removeRoom(const QString &room_id) |
| 652 | { |
| 653 | try { |
| 654 | cache::removeRoom(room_id); |
| 655 | cache::removeInvite(room_id.toStdString()); |
| 656 | } catch (const lmdb::error &e) { |
| 657 | nhlog::db()->critical("failure while removing room: {}", e.what()); |
| 658 | // TODO: Notify the user. |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | void |
| 663 | ChatPage::tryInitialSync() |
| 664 | { |
| 665 | nhlog::crypto()->info("ed25519 : {}", olm::client()->identity_keys().ed25519); |
| 666 | nhlog::crypto()->info("curve25519: {}", olm::client()->identity_keys().curve25519); |
| 667 | |
| 668 | // Upload one time keys for the device. |
| 669 | nhlog::crypto()->info("generating one time keys"); |
| 670 | olm::client()->generate_one_time_keys(MAX_ONETIME_KEYS, true); |
| 671 | |
| 672 | http::client()->upload_keys( |
| 673 | olm::client()->create_upload_keys_request(), |
| 674 | [this](const mtx::responses::UploadKeys &res, mtx::http::RequestErr err) { |
| 675 | if (err) { |
| 676 | const int status_code = static_cast<int>(err->status_code); |
| 677 | |
| 678 | if (status_code == 404) { |
| 679 | nhlog::net()->warn("skipping key uploading. server doesn't provide /keys/upload"); |
| 680 | return startInitialSync(); |
| 681 | } |
| 682 | |
| 683 | nhlog::crypto()->critical("failed to upload one time keys: {}", err); |
| 684 | |
| 685 | QString errorMsg(tr("Failed to setup encryption keys. Server response: " |
| 686 | "%1 %2. Please try again later.") |
| 687 | .arg(QString::fromStdString(err->matrix_error.error)) |
| 688 | .arg(status_code)); |
| 689 | |
| 690 | emit dropToLoginPageCb(errorMsg); |
| 691 | return; |
| 692 | } |
| 693 | |
| 694 | olm::client()->forget_old_fallback_key(); |
| 695 | olm::mark_keys_as_published(); |
| 696 | |
| 697 | for (const auto &entry : res.one_time_key_counts) |
| 698 | nhlog::net()->info("uploaded {} {} one-time keys", entry.second, entry.first); |
| 699 | |
| 700 | cache::client()->markUserKeysOutOfDate({http::client()->user_id().to_string()}); |
| 701 | |
| 702 | startInitialSync(); |
| 703 | }); |
| 704 | } |
| 705 | |
| 706 | void |
| 707 | ChatPage::startInitialSync() |
| 708 | { |
| 709 | nhlog::net()->info("trying initial sync"); |
| 710 | |
| 711 | mtx::http::SyncOpts opts; |
| 712 | opts.timeout = 0; |
| 713 | opts.set_presence = currentPresence(); |
| 714 | |
| 715 | http::client()->sync(opts, [this](const mtx::responses::Sync &res, mtx::http::RequestErr err) { |
| 716 | // TODO: Initial Sync should include mentions as well... |
| 717 | |
| 718 | if (err) { |
| 719 | const auto error = QString::fromStdString(err->matrix_error.error); |
| 720 | const auto msg = tr("Please try to login again: %1").arg(error); |
| 721 | const auto err_code = mtx::errors::to_string(err->matrix_error.errcode); |
| 722 | const int status_code = static_cast<int>(err->status_code); |
| 723 | |
| 724 | nhlog::net()->error("initial sync error: {}", err); |
| 725 | |
| 726 | // non http related errors |
| 727 | if (status_code <= 0 || status_code >= 600) { |
| 728 | startInitialSync(); |
| 729 | return; |
| 730 | } |
| 731 | |
| 732 | switch (status_code) { |
| 733 | case 502: |
| 734 | case 504: |
| 735 | case 524: { |
| 736 | startInitialSync(); |
| 737 | return; |
| 738 | } |
| 739 | default: { |
| 740 | emit dropToLoginPageCb(msg); |
| 741 | return; |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | QTimer::singleShot(0, this, [this, res] { |
| 747 | nhlog::net()->info("initial sync completed"); |
| 748 | try { |
| 749 | cache::client()->saveState(res); |
| 750 | |
| 751 | olm::handle_to_device_messages(res.to_device.events); |
| 752 | |
| 753 | emit initializeViews(std::move(res)); |
| 754 | |
| 755 | cache::calculateRoomReadStatus(); |
| 756 | } catch (const lmdb::error &e) { |
| 757 | nhlog::db()->error("failed to save state after initial sync: {}", e.what()); |
| 758 | startInitialSync(); |
| 759 | return; |
| 760 | } |
| 761 | |
| 762 | emit trySyncCb(); |
| 763 | emit contentLoaded(); |
| 764 | }); |
| 765 | }); |
| 766 | } |
| 767 | |
| 768 | void |
| 769 | ChatPage::handleSyncResponse(const mtx::responses::Sync &res, const std::string &prev_batch_token) |
| 770 | { |
| 771 | try { |
| 772 | if (prev_batch_token != cache::nextBatchToken()) { |
| 773 | nhlog::net()->warn("Duplicate sync, dropping"); |
| 774 | return; |
| 775 | } |
| 776 | } catch (const lmdb::error &) { |
| 777 | nhlog::db()->warn("Logged out in the mean time, dropping sync"); |
| 778 | return; |
| 779 | } |
| 780 | |
| 781 | nhlog::net()->debug("sync completed: {}", res.next_batch); |
| 782 | |
| 783 | // Ensure that we have enough one-time keys available. |
| 784 | std::map<std::string_view, std::uint16_t> counts{res.device_one_time_keys_count.begin(), |
| 785 | res.device_one_time_keys_count.end()}; |
| 786 | ensureOneTimeKeyCount(counts, res.device_unused_fallback_key_types); |
| 787 | |
| 788 | std::optional<mtx::events::account_data::IgnoredUsers> oldIgnoredUsers; |
| 789 | if (auto ignoreEv = std::ranges::find_if( |
| 790 | res.account_data.events, |
| 791 | [](const mtx::events::collections::RoomAccountDataEvents &e) { |
| 792 | return std::holds_alternative< |
| 793 | mtx::events::AccountDataEvent<mtx::events::account_data::IgnoredUsers>>(e); |
| 794 | }); |
| 795 | ignoreEv != res.account_data.events.end()) { |
| 796 | if (auto oldEv = cache::client()->getAccountData(mtx::events::EventType::IgnoredUsers)) |
| 797 | oldIgnoredUsers = |
| 798 | std::get<mtx::events::AccountDataEvent<mtx::events::account_data::IgnoredUsers>>( |
| 799 | *oldEv) |
| 800 | .content; |
| 801 | else |
| 802 | oldIgnoredUsers = mtx::events::account_data::IgnoredUsers{}; |
| 803 | } |
| 804 | |
| 805 | // TODO: fine grained error handling |
| 806 | try { |
| 807 | cache::client()->saveState(res); |
| 808 | olm::handle_to_device_messages(res.to_device.events); |
| 809 | |
| 810 | // reject forbidden invites |
| 811 | if (!res.rooms.invite.empty()) { |
| 812 | if (auto ev = |
| 813 | cache::client()->getAccountData(mtx::events::EventType::NhekoInvitePermissions)) { |
| 814 | const auto &invitePerms = std::get<mtx::events::AccountDataEvent< |
| 815 | mtx::events::account_data::nheko_extensions::InvitePermissions>>(*ev) |
| 816 | .content; |
| 817 | |
| 818 | for (const auto &[roomid, invite] : res.rooms.invite) { |
| 819 | std::string_view inviter = ""; |
| 820 | for (const auto &memberEv : invite.invite_state) { |
| 821 | if (auto member = |
| 822 | std::get_if<mtx::events::StrippedEvent<mtx::events::state::Member>>( |
| 823 | &memberEv)) { |
| 824 | if (member->content.membership == |
| 825 | mtx::events::state::Membership::Invite && |
| 826 | member->state_key == http::client()->user_id().to_string()) { |
| 827 | inviter = member->sender; |
| 828 | break; |
| 829 | } |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | if (!invitePerms.invite_allowed(roomid, inviter)) { |
| 834 | leaveRoom(QString::fromStdString(roomid), ""); |
| 835 | } |
| 836 | } |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | emit syncUI(std::move(res)); |
| 841 | |
| 842 | // if the ignored users changed, clear timeline of all affected rooms. |
| 843 | if (oldIgnoredUsers) { |
| 844 | if (auto newEv = |
| 845 | cache::client()->getAccountData(mtx::events::EventType::IgnoredUsers)) { |
| 846 | std::vector<mtx::events::account_data::IgnoredUser> changedUsers{}; |
| 847 | std::ranges::set_symmetric_difference( |
| 848 | oldIgnoredUsers->users, |
| 849 | std::get<mtx::events::AccountDataEvent<mtx::events::account_data::IgnoredUsers>>( |
| 850 | *newEv) |
| 851 | .content.users, |
| 852 | std::back_inserter(changedUsers), |
| 853 | {}, |
| 854 | &mtx::events::account_data::IgnoredUser::id, |
| 855 | &mtx::events::account_data::IgnoredUser::id); |
| 856 | |
| 857 | std::unordered_set<std::string> roomsToReload; |
| 858 | for (const auto &user : changedUsers) { |
| 859 | auto commonRooms = cache::client()->getCommonRooms(user.id); |
| 860 | for (const auto &room : commonRooms) |
| 861 | roomsToReload.insert(room.first); |
| 862 | } |
| 863 | |
| 864 | for (const auto &room : roomsToReload) { |
| 865 | if (auto model = |
| 866 | view_manager_->rooms()->getRoomById(QString::fromStdString(room))) |
| 867 | model->clearTimeline(); |
| 868 | } |
| 869 | } |
| 870 | } |
| 871 | } catch (const lmdb::map_full_error &e) { |
| 872 | nhlog::db()->error("lmdb is full: {}", e.what()); |
| 873 | cache::deleteOldData(); |
| 874 | } catch (const lmdb::error &e) { |
| 875 | nhlog::db()->error("saving sync response: {}", e.what()); |
| 876 | } |
| 877 | |
| 878 | if (shouldThrottleSync()) |
| 879 | QTimer::singleShot(1000, this, &ChatPage::trySyncCb); |
| 880 | else |
| 881 | emit trySyncCb(); |
| 882 | } |
| 883 | |
| 884 | void |
| 885 | ChatPage::trySync() |
| 886 | { |
| 887 | mtx::http::SyncOpts opts; |
| 888 | opts.set_presence = currentPresence(); |
| 889 | |
| 890 | if (!connectivityTimer_.isActive()) |
| 891 | connectivityTimer_.start(); |
| 892 | |
| 893 | try { |
| 894 | opts.since = cache::nextBatchToken(); |
| 895 | } catch (const lmdb::error &e) { |
| 896 | nhlog::db()->error("failed to retrieve next batch token: {}", e.what()); |
| 897 | return; |
| 898 | } |
| 899 | |
| 900 | http::client()->sync( |
| 901 | opts, [this, since = opts.since](const mtx::responses::Sync &res, mtx::http::RequestErr err) { |
| 902 | if (err) { |
| 903 | const auto error = QString::fromStdString(err->matrix_error.error); |
| 904 | const auto msg = tr("Please try to login again: %1").arg(error); |
| 905 | |
| 906 | if ((http::is_logged_in() && |
| 907 | (err->matrix_error.errcode == mtx::errors::ErrorCode::M_UNKNOWN_TOKEN || |
| 908 | err->matrix_error.errcode == mtx::errors::ErrorCode::M_MISSING_TOKEN)) || |
| 909 | !http::is_logged_in()) { |
| 910 | emit dropToLoginPageCb(msg); |
| 911 | return; |
| 912 | } |
| 913 | |
| 914 | nhlog::net()->error("sync error: {}", *err); |
| 915 | emit tryDelayedSyncCb(); |
| 916 | return; |
| 917 | } |
| 918 | |
| 919 | emit newSyncResponse(res, since); |
| 920 | }); |
| 921 | } |
| 922 | |
| 923 | void |
| 924 | ChatPage::knockRoom(const QString &room, |
| 925 | const std::vector<std::string> &via, |
| 926 | QString reason, |
| 927 | bool failedJoin, |
| 928 | bool promptForConfirmation) |
| 929 | { |
| 930 | const auto room_id = room.toStdString(); |
| 931 | bool confirmed = false; |
| 932 | if (promptForConfirmation) { |
| 933 | reason = QInputDialog::getText( |
| 934 | nullptr, |
| 935 | tr("Knock on room"), |
| 936 | // clang-format off |
| 937 | failedJoin |
| 938 | ? tr("You failed to join %1. You can try to knock so that others can invite you in. Do you want to do so?\nYou may optionally provide a reason for others to accept your knock:").arg(room) |
| 939 | : tr("Do you really want to knock on %1? You may optionally provide a reason for others to accept your knock:").arg(room), |
| 940 | // clang-format on |
| 941 | QLineEdit::Normal, |
| 942 | reason, |
| 943 | &confirmed); |
| 944 | if (!confirmed) { |
| 945 | return; |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | http::client()->knock_room( |
| 950 | room_id, |
| 951 | via, |
| 952 | [this, room_id](const mtx::responses::RoomId &, mtx::http::RequestErr err) { |
| 953 | if (err) { |
| 954 | emit showNotification(tr("Failed to knock room: %1") |
| 955 | .arg(QString::fromStdString(err->matrix_error.error))); |
| 956 | return; |
| 957 | } |
| 958 | }, |
| 959 | reason.toStdString()); |
| 960 | } |
| 961 | |
| 962 | void |
| 963 | ChatPage::joinRoom(const QString &room, const QString &reason) |
| 964 | { |
| 965 | const auto room_id = room.toStdString(); |
| 966 | joinRoomVia(room_id, {}, false, reason); |
| 967 | } |
| 968 | |
| 969 | void |
| 970 | ChatPage::joinRoomVia(const std::string &room_id, |
| 971 | const std::vector<std::string> &via, |
| 972 | bool promptForConfirmation, |
| 973 | const QString &reason) |
| 974 | { |
| 975 | if (promptForConfirmation) { |
| 976 | auto prompt = new RoomSummary(room_id, via, reason); |
| 977 | QQmlEngine::setObjectOwnership(prompt, QQmlEngine::JavaScriptOwnership); |
| 978 | emit showRoomJoinPrompt(prompt); |
| 979 | return; |
| 980 | } |
| 981 | |
| 982 | http::client()->join_room( |
| 983 | room_id, |
| 984 | via, |
| 985 | [this, room_id, reason, via](const mtx::responses::RoomId &, mtx::http::RequestErr err) { |
| 986 | if (err) { |
| 987 | if (err->matrix_error.errcode == mtx::errors::ErrorCode::M_FORBIDDEN) |
| 988 | emit internalKnock(QString::fromStdString(room_id), via, reason, true, true); |
| 989 | else |
| 990 | emit showNotification(tr("Failed to join room: %1") |
| 991 | .arg(QString::fromStdString(err->matrix_error.error))); |
| 992 | return; |
| 993 | } |
| 994 | |
| 995 | // We remove any invites with the same room_id. |
| 996 | try { |
| 997 | cache::removeInvite(room_id); |
| 998 | } catch (const lmdb::error &e) { |
| 999 | emit showNotification(tr("Failed to remove invite: %1").arg(e.what())); |
| 1000 | } |
| 1001 | |
| 1002 | view_manager_->rooms()->setCurrentRoom(QString::fromStdString(room_id)); |
| 1003 | }, |
| 1004 | reason.toStdString()); |
| 1005 | } |
| 1006 | |
| 1007 | void |
| 1008 | ChatPage::createRoom(const mtx::requests::CreateRoom &req) |
| 1009 | { |
| 1010 | if (req.room_alias_name.find(":") != std::string::npos || |
| 1011 | req.room_alias_name.find("#") != std::string::npos) { |
| 1012 | nhlog::net()->warn("Failed to create room: Some characters are not allowed in alias"); |
| 1013 | emit this->showNotification(tr("Room creation failed: Bad Alias")); |
| 1014 | return; |
| 1015 | } |
| 1016 | |
| 1017 | bool direct = req.is_direct; |
| 1018 | std::string direct_user; |
| 1019 | if (direct && !req.invite.empty()) |
| 1020 | direct_user = req.invite.front(); |
| 1021 | |
| 1022 | http::client()->create_room( |
| 1023 | req, |
| 1024 | [this, direct, direct_user](const mtx::responses::CreateRoom &res, |
| 1025 | mtx::http::RequestErr err) { |
| 1026 | if (err) { |
| 1027 | const auto err_code = mtx::errors::to_string(err->matrix_error.errcode); |
| 1028 | const auto error = err->matrix_error.error; |
| 1029 | |
| 1030 | nhlog::net()->warn("failed to create room: {})", err); |
| 1031 | |
| 1032 | emit showNotification( |
| 1033 | tr("Room creation failed: %1").arg(QString::fromStdString(error))); |
| 1034 | return; |
| 1035 | } |
| 1036 | |
| 1037 | QString newRoomId = QString::fromStdString(res.room_id.to_string()); |
| 1038 | |
| 1039 | if (direct && !direct_user.empty()) { |
| 1040 | utils::markRoomAsDirect(newRoomId, |
| 1041 | {RoomMember{ |
| 1042 | .user_id = QString::fromStdString(direct_user), |
| 1043 | .display_name = "", |
| 1044 | .avatar_url = "", |
| 1045 | }}); |
| 1046 | } |
| 1047 | |
| 1048 | emit showNotification(tr("Room %1 created.").arg(newRoomId)); |
| 1049 | emit newRoom(newRoomId); |
| 1050 | emit changeToRoom(newRoomId); |
| 1051 | }); |
| 1052 | } |
| 1053 | |
| 1054 | void |
| 1055 | ChatPage::leaveRoom(const QString &room_id, const QString &reason) |
| 1056 | { |
| 1057 | http::client()->leave_room( |
| 1058 | room_id.toStdString(), |
| 1059 | [this, room_id](const mtx::responses::Empty &, mtx::http::RequestErr err) { |
| 1060 | if (err) { |
| 1061 | emit showNotification(tr("Failed to leave room: %1") |
| 1062 | .arg(QString::fromStdString(err->matrix_error.error))); |
| 1063 | nhlog::net()->error("Failed to leave room '{}': {}", room_id.toStdString(), err); |
| 1064 | |
| 1065 | if (err->status_code == 404 && |
| 1066 | err->matrix_error.errcode == mtx::errors::ErrorCode::M_UNKNOWN) { |
| 1067 | nhlog::db()->debug( |
| 1068 | "Removing invite and room for {}, even though we couldn't leave.", |
| 1069 | room_id.toStdString()); |
| 1070 | cache::client()->removeInvite(room_id.toStdString()); |
| 1071 | cache::client()->removeRoom(room_id.toStdString()); |
| 1072 | } |
| 1073 | return; |
| 1074 | } |
| 1075 | |
| 1076 | emit leftRoom(room_id); |
| 1077 | }, |
| 1078 | reason.toStdString()); |
| 1079 | } |
| 1080 | |
| 1081 | void |
| 1082 | ChatPage::changeRoom(const QString &room_id) |
| 1083 | { |
| 1084 | view_manager_->rooms()->setCurrentRoom(room_id); |
| 1085 | } |
| 1086 | |
| 1087 | void |
| 1088 | ChatPage::inviteUser(const QString &room, QString userid, QString reason) |
| 1089 | { |
| 1090 | if (QMessageBox::question(nullptr, |
| 1091 | tr("Confirm invite"), |
| 1092 | tr("Do you really want to invite %1 (%2)?") |
| 1093 | .arg(cache::displayName(room, userid), userid)) != QMessageBox::Yes) |
| 1094 | return; |
| 1095 | |
| 1096 | http::client()->invite_user( |
| 1097 | room.toStdString(), |
| 1098 | userid.toStdString(), |
| 1099 | [this, userid, room](const mtx::responses::Empty &, mtx::http::RequestErr err) { |
| 1100 | if (err) { |
| 1101 | nhlog::net()->error( |
| 1102 | "Failed to invite {} to {}: {}", userid.toStdString(), room.toStdString(), *err); |
| 1103 | emit showNotification( |
| 1104 | tr("Failed to invite %1 to %2: %3") |
| 1105 | .arg(userid, room, QString::fromStdString(err->matrix_error.error))); |
| 1106 | } else |
| 1107 | emit showNotification(tr("Invited user: %1").arg(userid)); |
| 1108 | }, |
| 1109 | reason.trimmed().toStdString()); |
| 1110 | } |
| 1111 | void |
| 1112 | ChatPage::kickUser(const QString &room, QString userid, QString reason) |
| 1113 | { |
| 1114 | bool confirmed; |
| 1115 | reason = QInputDialog::getText( |
| 1116 | nullptr, |
| 1117 | tr("Reason for the kick"), |
| 1118 | tr("Enter reason for kicking %1 (%2) or hit enter for no reason:") |
| 1119 | .arg(cache::displayName(room, userid).toHtmlEscaped(), userid.toHtmlEscaped()), |
| 1120 | QLineEdit::Normal, |
| 1121 | reason, |
| 1122 | &confirmed); |
| 1123 | if (!confirmed) { |
| 1124 | return; |
| 1125 | } |
| 1126 | |
| 1127 | http::client()->kick_user( |
| 1128 | room.toStdString(), |
| 1129 | userid.toStdString(), |
| 1130 | [this, userid, room](const mtx::responses::Empty &, mtx::http::RequestErr err) { |
| 1131 | if (err) { |
| 1132 | emit showNotification( |
| 1133 | tr("Failed to kick %1 from %2: %3") |
| 1134 | .arg(userid, room, QString::fromStdString(err->matrix_error.error))); |
| 1135 | } else |
| 1136 | emit showNotification(tr("Kicked user: %1").arg(userid)); |
| 1137 | }, |
| 1138 | reason.trimmed().toStdString()); |
| 1139 | } |
| 1140 | void |
| 1141 | ChatPage::banUser(const QString &room, QString userid, QString reason) |
| 1142 | { |
| 1143 | bool confirmed; |
| 1144 | reason = QInputDialog::getText( |
| 1145 | nullptr, |
| 1146 | tr("Reason for the ban"), |
| 1147 | tr("Enter reason for banning %1 (%2) or hit enter for no reason:") |
| 1148 | .arg(cache::displayName(room, userid).toHtmlEscaped(), userid.toHtmlEscaped()), |
| 1149 | QLineEdit::Normal, |
| 1150 | reason, |
| 1151 | &confirmed); |
| 1152 | if (!confirmed) { |
| 1153 | return; |
| 1154 | } |
| 1155 | |
| 1156 | http::client()->ban_user( |
| 1157 | room.toStdString(), |
| 1158 | userid.toStdString(), |
| 1159 | [this, userid, room](const mtx::responses::Empty &, mtx::http::RequestErr err) { |
| 1160 | if (err) { |
| 1161 | emit showNotification( |
| 1162 | tr("Failed to ban %1 in %2: %3") |
| 1163 | .arg(userid, room, QString::fromStdString(err->matrix_error.error))); |
| 1164 | } else |
| 1165 | emit showNotification(tr("Banned user: %1").arg(userid)); |
| 1166 | }, |
| 1167 | reason.trimmed().toStdString()); |
| 1168 | } |
| 1169 | void |
| 1170 | ChatPage::unbanUser(const QString &room, QString userid, QString reason) |
| 1171 | { |
| 1172 | if (QMessageBox::question(nullptr, |
| 1173 | tr("Confirm unban"), |
| 1174 | tr("Do you really want to unban %1 (%2)?") |
| 1175 | .arg(cache::displayName(room, userid).toHtmlEscaped(), |
| 1176 | userid.toHtmlEscaped())) != QMessageBox::Yes) |
| 1177 | return; |
| 1178 | |
| 1179 | http::client()->unban_user( |
| 1180 | room.toStdString(), |
| 1181 | userid.toStdString(), |
| 1182 | [this, userid, room](const mtx::responses::Empty &, mtx::http::RequestErr err) { |
| 1183 | if (err) { |
| 1184 | emit showNotification( |
| 1185 | tr("Failed to unban %1 in %2: %3") |
| 1186 | .arg(userid, room, QString::fromStdString(err->matrix_error.error))); |
| 1187 | } else |
| 1188 | emit showNotification(tr("Unbanned user: %1").arg(userid)); |
| 1189 | }, |
| 1190 | reason.trimmed().toStdString()); |
| 1191 | } |
| 1192 | |
| 1193 | void |
| 1194 | ChatPage::receivedSessionKey(const std::string &room_id, const std::string &session_id) |
| 1195 | { |
| 1196 | view_manager_->receivedSessionKey(room_id, session_id); |
| 1197 | } |
| 1198 | |
| 1199 | QString |
| 1200 | ChatPage::status() const |
| 1201 | { |
| 1202 | return QString::fromStdString(cache::presence(utils::localUser().toStdString()).status_msg); |
| 1203 | } |
| 1204 | |
| 1205 | void |
| 1206 | ChatPage::setStatus(const QString &status) |
| 1207 | { |
| 1208 | http::client()->put_presence_status( |
| 1209 | currentPresence(), status.toStdString(), [](mtx::http::RequestErr err) { |
| 1210 | if (err) { |
| 1211 | nhlog::net()->warn("failed to set presence status_msg: {}", err->matrix_error.error); |
| 1212 | } |
| 1213 | }); |
| 1214 | } |
| 1215 | |
| 1216 | bool |
| 1217 | ChatPage::shouldBeUnavailable() const |
| 1218 | { |
| 1219 | return lastWindowActive.isValid() && |
| 1220 | lastWindowActive.addSecs(60 * 5) < QDateTime::currentDateTime(); |
| 1221 | } |
| 1222 | |
| 1223 | bool |
| 1224 | ChatPage::shouldThrottleSync() const |
| 1225 | { |
| 1226 | return lastWindowActive.isValid() && |
| 1227 | lastWindowActive.addSecs(6 * 5) < QDateTime::currentDateTime(); |
| 1228 | } |
| 1229 | |
| 1230 | mtx::presence::PresenceState |
| 1231 | ChatPage::currentPresence() const |
| 1232 | { |
| 1233 | switch (userSettings_->presence()) { |
| 1234 | case UserSettings::Presence::Online: |
| 1235 | return mtx::presence::online; |
| 1236 | case UserSettings::Presence::Unavailable: |
| 1237 | return mtx::presence::unavailable; |
| 1238 | case UserSettings::Presence::Offline: |
| 1239 | return mtx::presence::offline; |
| 1240 | case UserSettings::Presence::AutomaticPresence: |
| 1241 | if (shouldBeUnavailable()) |
| 1242 | return mtx::presence::unavailable; |
| 1243 | else |
| 1244 | return mtx::presence::online; |
| 1245 | |
| 1246 | default: |
| 1247 | return mtx::presence::online; |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | void |
| 1252 | ChatPage::verifyOneTimeKeyCountAfterStartup() |
| 1253 | { |
| 1254 | http::client()->upload_keys( |
| 1255 | olm::client()->create_upload_keys_request(), |
| 1256 | [this](const mtx::responses::UploadKeys &res, mtx::http::RequestErr err) { |
| 1257 | if (err) { |
| 1258 | nhlog::crypto()->warn("failed to update one-time keys: {}", err); |
| 1259 | |
| 1260 | if (err->status_code < 400 || err->status_code >= 500) |
| 1261 | return; |
| 1262 | } |
| 1263 | |
| 1264 | std::map<std::string_view, uint16_t> key_counts; |
| 1265 | std::uint64_t count = 0; |
| 1266 | if (auto c = res.one_time_key_counts.find(mtx::crypto::SIGNED_CURVE25519); |
| 1267 | c == res.one_time_key_counts.end()) { |
| 1268 | key_counts[mtx::crypto::SIGNED_CURVE25519] = 0; |
| 1269 | } else { |
| 1270 | key_counts[mtx::crypto::SIGNED_CURVE25519] = |
| 1271 | c->second > std::numeric_limits<std::uint16_t>::max() |
| 1272 | ? std::numeric_limits<std::uint16_t>::max() |
| 1273 | : static_cast<std::uint16_t>(c->second); |
| 1274 | count = c->second; |
| 1275 | } |
| 1276 | |
| 1277 | nhlog::crypto()->info( |
| 1278 | "Fetched server key count {} {}", count, mtx::crypto::SIGNED_CURVE25519); |
| 1279 | |
| 1280 | ensureOneTimeKeyCount(key_counts, std::nullopt); |
| 1281 | }); |
| 1282 | } |
| 1283 | |
| 1284 | void |
| 1285 | ChatPage::ensureOneTimeKeyCount(const std::map<std::string_view, uint16_t> &counts, |
| 1286 | const std::optional<std::vector<std::string>> &unused_fallback_keys) |
| 1287 | { |
| 1288 | if (auto count = counts.find(mtx::crypto::SIGNED_CURVE25519); count != counts.end()) { |
| 1289 | bool replace_fallback_key = false; |
| 1290 | if (unused_fallback_keys && |
| 1291 | std::find(unused_fallback_keys->begin(), |
| 1292 | unused_fallback_keys->end(), |
| 1293 | mtx::crypto::SIGNED_CURVE25519) == unused_fallback_keys->end()) |
| 1294 | replace_fallback_key = true; |
| 1295 | nhlog::crypto()->debug( |
| 1296 | "Updated server key count {} {}, fallback keys supported: {}, new fallback key: {}", |
| 1297 | count->second, |
| 1298 | mtx::crypto::SIGNED_CURVE25519, |
| 1299 | unused_fallback_keys.has_value(), |
| 1300 | replace_fallback_key); |
| 1301 | |
| 1302 | if (count->second < MAX_ONETIME_KEYS || replace_fallback_key) { |
| 1303 | const size_t nkeys = |
| 1304 | count->second < MAX_ONETIME_KEYS ? (MAX_ONETIME_KEYS - count->second) : 0; |
| 1305 | |
| 1306 | nhlog::crypto()->info("uploading {} {} keys", nkeys, mtx::crypto::SIGNED_CURVE25519); |
| 1307 | olm::client()->generate_one_time_keys(nkeys, replace_fallback_key); |
| 1308 | |
| 1309 | http::client()->upload_keys( |
| 1310 | olm::client()->create_upload_keys_request(), |
| 1311 | [replace_fallback_key, this](const mtx::responses::UploadKeys &, |
| 1312 | mtx::http::RequestErr err) { |
| 1313 | if (err) { |
| 1314 | nhlog::crypto()->warn("failed to update one-time keys: {}", err); |
| 1315 | |
| 1316 | if (err->status_code < 400 || err->status_code >= 500) |
| 1317 | return; |
| 1318 | } |
| 1319 | |
| 1320 | // mark as published anyway, otherwise we may end up in a loop. |
| 1321 | olm::mark_keys_as_published(); |
| 1322 | |
| 1323 | if (replace_fallback_key) { |
| 1324 | emit startRemoveFallbackKeyTimer(); |
| 1325 | } |
| 1326 | }); |
| 1327 | } else if (count->second > 2 * MAX_ONETIME_KEYS) { |
| 1328 | nhlog::crypto()->warn("too many one-time keys, deleting 1"); |
| 1329 | mtx::requests::ClaimKeys req; |
| 1330 | req.one_time_keys[http::client()->user_id().to_string()][http::client()->device_id()] = |
| 1331 | std::string(mtx::crypto::SIGNED_CURVE25519); |
| 1332 | http::client()->claim_keys( |
| 1333 | req, [](const mtx::responses::ClaimKeys &, mtx::http::RequestErr err) { |
| 1334 | if (err) |
| 1335 | nhlog::crypto()->warn("failed to clear 1 one-time key: {}", err); |
| 1336 | else |
| 1337 | nhlog::crypto()->info("cleared 1 one-time key"); |
| 1338 | }); |
| 1339 | } |
| 1340 | } |
| 1341 | } |
| 1342 | |
| 1343 | void |
| 1344 | ChatPage::removeOldFallbackKey() |
| 1345 | { |
| 1346 | olm::client()->forget_old_fallback_key(); |
| 1347 | olm::mark_keys_as_published(); |
| 1348 | } |
| 1349 | |
| 1350 | void |
| 1351 | ChatPage::getProfileInfo() |
| 1352 | { |
| 1353 | const auto userid = utils::localUser().toStdString(); |
| 1354 | |
| 1355 | http::client()->get_profile( |
| 1356 | userid, [this](const mtx::responses::Profile &res, mtx::http::RequestErr err) { |
| 1357 | if (err) { |
| 1358 | nhlog::net()->warn("failed to retrieve own profile info"); |
| 1359 | return; |
| 1360 | } |
| 1361 | |
| 1362 | emit setUserDisplayName(QString::fromStdString(res.display_name)); |
| 1363 | |
| 1364 | emit setUserAvatar(QString::fromStdString(res.avatar_url)); |
| 1365 | }); |
| 1366 | } |
| 1367 | |
| 1368 | void |
| 1369 | ChatPage::getBackupVersion() |
| 1370 | { |
| 1371 | if (!UserSettings::instance()->useOnlineKeyBackup()) { |
| 1372 | nhlog::crypto()->info("Online key backup disabled."); |
| 1373 | return; |
| 1374 | } |
| 1375 | |
| 1376 | http::client()->backup_version( |
| 1377 | [this](const mtx::responses::backup::BackupVersion &res, mtx::http::RequestErr err) { |
| 1378 | if (err) { |
| 1379 | nhlog::net()->warn("Failed to retrieve backup version"); |
| 1380 | if (err->status_code == 404) |
| 1381 | cache::client()->deleteBackupVersion(); |
| 1382 | return; |
| 1383 | } |
| 1384 | |
| 1385 | // switch to UI thread for secrets stuff |
| 1386 | QTimer::singleShot(0, this, [this, res] { |
| 1387 | auto auth_data = nlohmann::json::parse(res.auth_data); |
| 1388 | |
| 1389 | if (res.algorithm == "m.megolm_backup.v1.curve25519-aes-sha2") { |
| 1390 | auto key = cache::secret(mtx::secret_storage::secrets::megolm_backup_v1); |
| 1391 | if (!key) { |
| 1392 | nhlog::crypto()->info("No key for online key backup."); |
| 1393 | cache::client()->deleteBackupVersion(); |
| 1394 | return; |
| 1395 | } |
| 1396 | |
| 1397 | using namespace mtx::crypto; |
| 1398 | auto pubkey = CURVE25519_public_key_from_private(to_binary_buf(base642bin(*key))); |
| 1399 | |
| 1400 | if (auth_data["public_key"].get<std::string>() != pubkey) { |
| 1401 | nhlog::crypto()->info("Our backup key {} does not match the one " |
| 1402 | "used in the online backup {}", |
| 1403 | pubkey, |
| 1404 | auth_data["public_key"].get<std::string>()); |
| 1405 | cache::client()->deleteBackupVersion(); |
| 1406 | return; |
| 1407 | } |
| 1408 | |
| 1409 | auto oldBackupVersion = cache::client()->backupVersion(); |
| 1410 | |
| 1411 | nhlog::crypto()->info("Using online key backup."); |
| 1412 | OnlineBackupVersion data{}; |
| 1413 | data.algorithm = res.algorithm; |
| 1414 | data.version = res.version; |
| 1415 | cache::client()->saveBackupVersion(data); |
| 1416 | |
| 1417 | if (!oldBackupVersion || oldBackupVersion->version != data.version) { |
| 1418 | view_manager_->rooms()->refetchOnlineKeyBackupKeys(); |
| 1419 | } |
| 1420 | } else { |
| 1421 | nhlog::crypto()->info("Unsupported key backup algorithm: {}", res.algorithm); |
| 1422 | cache::client()->deleteBackupVersion(); |
| 1423 | } |
| 1424 | }); |
| 1425 | }); |
| 1426 | } |
| 1427 | |
| 1428 | void |
| 1429 | ChatPage::initiateLogout() |
| 1430 | { |
| 1431 | http::client()->logout([this](const mtx::responses::Logout &, mtx::http::RequestErr err) { |
| 1432 | if (err) { |
| 1433 | // TODO: handle special errors |
| 1434 | emit contentLoaded(); |
| 1435 | nhlog::net()->warn("failed to logout: {}", err); |
| 1436 | return; |
| 1437 | } |
| 1438 | |
| 1439 | emit loggedOut(); |
| 1440 | }); |
| 1441 | } |
| 1442 | |
| 1443 | template<typename T> |
| 1444 | void |
| 1445 | ChatPage::connectCallMessage() |
| 1446 | { |
| 1447 | connect(callManager_, |
| 1448 | qOverload<const QString &, const T &>(&CallManager::newMessage), |
| 1449 | view_manager_, |
| 1450 | qOverload<const QString &, const T &>(&TimelineViewManager::queueCallMessage)); |
| 1451 | } |
| 1452 | |
| 1453 | void |
| 1454 | ChatPage::decryptDownloadedSecrets(mtx::secret_storage::AesHmacSha2KeyDescription keyDesc, |
| 1455 | const SecretsToDecrypt &secrets) |
| 1456 | { |
| 1457 | QString text = QInputDialog::getText( |
| 1458 | nullptr, |
| 1459 | QCoreApplication::translate("CrossSigningSecrets", "Decrypt secrets"), |
| 1460 | keyDesc.name.empty() |
| 1461 | ? QCoreApplication::translate( |
| 1462 | "CrossSigningSecrets", "Enter your recovery key or passphrase to decrypt your secrets:") |
| 1463 | : QCoreApplication::translate( |
| 1464 | "CrossSigningSecrets", |
| 1465 | "Enter your recovery key or passphrase called %1 to decrypt your secrets:") |
| 1466 | .arg(QString::fromStdString(keyDesc.name)), |
| 1467 | QLineEdit::Password); |
| 1468 | |
| 1469 | if (text.isEmpty()) |
| 1470 | return; |
| 1471 | |
| 1472 | // strip space chars from a recovery key. It can't contain those, but some clients insert them |
| 1473 | // to make them easier to read. |
| 1474 | QString stripped = text; |
| 1475 | stripped.remove(' '); |
| 1476 | stripped.remove('\n'); |
| 1477 | stripped.remove('\t'); |
| 1478 | |
| 1479 | auto decryptionKey = mtx::crypto::key_from_recoverykey(stripped.toStdString(), keyDesc); |
| 1480 | if (!decryptionKey && keyDesc.passphrase) { |
| 1481 | try { |
| 1482 | decryptionKey = mtx::crypto::key_from_passphrase(text.toStdString(), keyDesc); |
| 1483 | } catch (std::exception &e) { |
| 1484 | nhlog::crypto()->error("Failed to derive secret key from passphrase: {}", e.what()); |
| 1485 | } |
| 1486 | } |
| 1487 | |
| 1488 | if (!decryptionKey) { |
| 1489 | QMessageBox::information( |
| 1490 | nullptr, |
| 1491 | QCoreApplication::translate("CrossSigningSecrets", "Decryption failed"), |
| 1492 | QCoreApplication::translate("CrossSigningSecrets", |
| 1493 | "Failed to decrypt secrets with the " |
| 1494 | "provided recovery key or passphrase")); |
| 1495 | return; |
| 1496 | } |
| 1497 | |
| 1498 | auto deviceKeys = cache::client()->userKeys(http::client()->user_id().to_string()); |
| 1499 | mtx::requests::KeySignaturesUpload req; |
| 1500 | |
| 1501 | for (const auto &[secretName, encryptedSecret] : secrets) { |
| 1502 | auto decrypted = mtx::crypto::decrypt(encryptedSecret, *decryptionKey, secretName); |
| 1503 | nhlog::crypto()->debug("Secret {} decrypted: {}", secretName, !decrypted.empty()); |
| 1504 | |
| 1505 | if (!decrypted.empty()) { |
| 1506 | cache::storeSecret(secretName, decrypted); |
| 1507 | |
| 1508 | if (deviceKeys && deviceKeys->device_keys.count(http::client()->device_id()) && |
| 1509 | secretName == mtx::secret_storage::secrets::cross_signing_self_signing) { |
| 1510 | auto myKey = deviceKeys->device_keys.at(http::client()->device_id()); |
| 1511 | if (myKey.user_id == http::client()->user_id().to_string() && |
| 1512 | myKey.device_id == http::client()->device_id() && |
| 1513 | myKey.keys["ed25519:" + http::client()->device_id()] == |
| 1514 | olm::client()->identity_keys().ed25519 && |
| 1515 | myKey.keys["curve25519:" + http::client()->device_id()] == |
| 1516 | olm::client()->identity_keys().curve25519) { |
| 1517 | nlohmann::json j = myKey; |
| 1518 | j.erase("signatures"); |
| 1519 | j.erase("unsigned"); |
| 1520 | |
| 1521 | auto ssk = mtx::crypto::PkSigning::from_seed(decrypted); |
| 1522 | myKey.signatures[http::client()->user_id().to_string()] |
| 1523 | ["ed25519:" + ssk.public_key()] = ssk.sign(j.dump()); |
| 1524 | req.signatures[http::client()->user_id().to_string()] |
| 1525 | [http::client()->device_id()] = myKey; |
| 1526 | } |
| 1527 | } else if (deviceKeys && |
| 1528 | secretName == mtx::secret_storage::secrets::cross_signing_master) { |
| 1529 | auto mk = mtx::crypto::PkSigning::from_seed(decrypted); |
| 1530 | |
| 1531 | if (deviceKeys->master_keys.user_id == http::client()->user_id().to_string() && |
| 1532 | deviceKeys->master_keys.keys["ed25519:" + mk.public_key()] == mk.public_key()) { |
| 1533 | nlohmann::json j = deviceKeys->master_keys; |
| 1534 | j.erase("signatures"); |
| 1535 | j.erase("unsigned"); |
| 1536 | mtx::crypto::CrossSigningKeys master_key = |
| 1537 | j.get<mtx::crypto::CrossSigningKeys>(); |
| 1538 | master_key.signatures[http::client()->user_id().to_string()] |
| 1539 | ["ed25519:" + http::client()->device_id()] = |
| 1540 | olm::client()->sign_message(j.dump()); |
| 1541 | req.signatures[http::client()->user_id().to_string()][mk.public_key()] = |
| 1542 | master_key; |
| 1543 | } |
| 1544 | } |
| 1545 | } |
| 1546 | } |
| 1547 | |
| 1548 | if (!req.signatures.empty()) { |
| 1549 | nhlog::crypto()->debug("Uploading new signatures: {}", nlohmann::json(req).dump(2)); |
| 1550 | http::client()->keys_signatures_upload( |
| 1551 | req, [](const mtx::responses::KeySignaturesUpload &res, mtx::http::RequestErr err) { |
| 1552 | if (err) { |
| 1553 | nhlog::net()->error("failed to upload signatures: {}", *err); |
| 1554 | } |
| 1555 | |
| 1556 | for (const auto &[user_id, tmp] : res.errors) |
| 1557 | for (const auto &[key_id, e] : tmp) |
| 1558 | nhlog::net()->error("signature error for user '{}' and key " |
| 1559 | "id {}: {} {}", |
| 1560 | user_id, |
| 1561 | key_id, |
| 1562 | mtx::errors::to_string(e.errcode), |
| 1563 | e.error); |
| 1564 | }); |
| 1565 | } |
| 1566 | } |
| 1567 | |
| 1568 | void |
| 1569 | ChatPage::startChat(QString userid, std::optional<bool> encryptionEnabled) |
| 1570 | { |
| 1571 | auto joined_rooms = cache::joinedRooms(); |
| 1572 | auto room_infos = cache::getRoomInfo(joined_rooms); |
| 1573 | |
| 1574 | for (const std::string &room_id : joined_rooms) { |
| 1575 | if (const auto &info = room_infos[QString::fromStdString(room_id)]; |
| 1576 | info.member_count == 2 && !info.is_space) { |
| 1577 | auto room_members = cache::roomMembers(room_id); |
| 1578 | if (std::find(room_members.begin(), room_members.end(), (userid).toStdString()) != |
| 1579 | room_members.end()) { |
| 1580 | view_manager_->rooms()->setCurrentRoom(QString::fromStdString(room_id)); |
| 1581 | return; |
| 1582 | } |
| 1583 | } |
| 1584 | } |
| 1585 | |
| 1586 | if (QMessageBox::Yes != |
| 1587 | QMessageBox::question( |
| 1588 | nullptr, |
| 1589 | tr("Confirm invite"), |
| 1590 | tr("Do you really want to start a private chat with %1?").arg(userid))) |
| 1591 | return; |
| 1592 | |
| 1593 | mtx::requests::CreateRoom req; |
| 1594 | req.preset = mtx::requests::Preset::TrustedPrivateChat; |
| 1595 | req.visibility = mtx::common::RoomVisibility::Private; |
| 1596 | |
| 1597 | if (!encryptionEnabled.has_value()) { |
| 1598 | if (auto keys = cache::client()->userKeys(userid.toStdString())) |
| 1599 | encryptionEnabled = !keys->device_keys.empty(); |
| 1600 | } |
| 1601 | |
| 1602 | if (encryptionEnabled.value_or(false)) { |
| 1603 | mtx::events::StrippedEvent<mtx::events::state::Encryption> enc; |
| 1604 | enc.type = mtx::events::EventType::RoomEncryption; |
| 1605 | enc.content.algorithm = mtx::crypto::MEGOLM_ALGO; |
| 1606 | req.initial_state.emplace_back(std::move(enc)); |
| 1607 | } |
| 1608 | |
| 1609 | if (utils::localUser() != userid) { |
| 1610 | req.invite = {userid.toStdString()}; |
| 1611 | req.is_direct = true; |
| 1612 | } |
| 1613 | emit ChatPage::instance()->createRoom(req); |
| 1614 | } |
| 1615 | |
| 1616 | bool |
| 1617 | ChatPage::handleMatrixUri(QString uri) |
| 1618 | { |
| 1619 | nhlog::ui()->info("Received uri! {}", uri.toStdString()); |
| 1620 | |
| 1621 | auto m = utils::parseMatrixUri(uri); |
| 1622 | |
| 1623 | if (!m) { |
| 1624 | nhlog::ui()->info("failed to parse uri! {}", uri.toStdString()); |
| 1625 | return false; |
| 1626 | } |
| 1627 | |
| 1628 | const auto &[sigil1, mxid1, sigil2, mxid2, action, vias] = *m; |
| 1629 | |
| 1630 | if (sigil1 == u"u") { |
| 1631 | if (action.isEmpty()) { |
| 1632 | auto t = MainWindow::instance()->focusedRoom(); |
| 1633 | if (!t.isEmpty() && cache::isRoomMember(mxid1.toStdString(), t.toStdString())) { |
| 1634 | auto rm = view_manager_->rooms()->getRoomById(t); |
| 1635 | if (rm) |
| 1636 | rm->openUserProfile(mxid1); |
| 1637 | return true; |
| 1638 | } |
| 1639 | emit view_manager_->openGlobalUserProfile(mxid1); |
| 1640 | } else if (action == u"chat") { |
| 1641 | this->startChat(mxid1); |
| 1642 | } |
| 1643 | return true; |
| 1644 | } else if (sigil1 == u"roomid") { |
| 1645 | auto joined_rooms = cache::joinedRooms(); |
| 1646 | auto targetRoomId = mxid1.toStdString(); |
| 1647 | |
| 1648 | for (const auto &roomid : joined_rooms) { |
| 1649 | if (roomid == targetRoomId) { |
| 1650 | view_manager_->rooms()->setCurrentRoom(mxid1); |
| 1651 | if (!mxid2.isEmpty()) |
| 1652 | view_manager_->showEvent(mxid1, mxid2); |
| 1653 | return true; |
| 1654 | } |
| 1655 | } |
| 1656 | |
| 1657 | if (action == u"join" || action.isEmpty()) { |
| 1658 | joinRoomVia(targetRoomId, vias); |
| 1659 | return true; |
| 1660 | } else if (action == u"knock" || action.isEmpty()) { |
| 1661 | knockRoom(mxid1, vias); |
| 1662 | return true; |
| 1663 | } |
| 1664 | return false; |
| 1665 | } else if (sigil1 == u"r") { |
| 1666 | auto joined_rooms = cache::joinedRooms(); |
| 1667 | auto targetRoomAlias = mxid1.toStdString(); |
| 1668 | |
| 1669 | for (const auto &roomid : joined_rooms) { |
| 1670 | auto aliases = |
| 1671 | cache::client()->getStateEvent<mtx::events::state::CanonicalAlias>(roomid); |
| 1672 | if (aliases) { |
| 1673 | if (aliases->content.alias == targetRoomAlias) { |
| 1674 | view_manager_->rooms()->setCurrentRoom(QString::fromStdString(roomid)); |
| 1675 | if (!mxid2.isEmpty()) |
| 1676 | view_manager_->showEvent(QString::fromStdString(roomid), mxid2); |
| 1677 | return true; |
| 1678 | } |
| 1679 | } |
| 1680 | } |
| 1681 | |
| 1682 | if (action == u"join" || action.isEmpty()) { |
| 1683 | joinRoomVia(mxid1.toStdString(), vias); |
| 1684 | return true; |
| 1685 | } else if (action == u"knock" || action.isEmpty()) { |
| 1686 | knockRoom(mxid1, vias); |
| 1687 | return true; |
| 1688 | } |
| 1689 | return false; |
| 1690 | } |
| 1691 | return false; |
| 1692 | } |
| 1693 | |
| 1694 | void |
| 1695 | ChatPage::sendNotificationReply(const QString &roomid, const QString &eventid, const QString &body) |
| 1696 | { |
| 1697 | view_manager_->queueReply(roomid, eventid, body); |
| 1698 | auto exWin = MainWindow::instance()->windowForRoom(roomid); |
| 1699 | if (exWin) { |
| 1700 | exWin->setVisible(true); |
| 1701 | exWin->raise(); |
| 1702 | exWin->requestActivate(); |
| 1703 | } else { |
| 1704 | view_manager_->rooms()->setCurrentRoom(roomid); |
| 1705 | MainWindow::instance()->setVisible(true); |
| 1706 | MainWindow::instance()->raise(); |
| 1707 | MainWindow::instance()->requestActivate(); |
| 1708 | } |
| 1709 | } |
| 1710 | |
| 1711 | bool |
| 1712 | ChatPage::handleMatrixUri(const QUrl &uri) |
| 1713 | { |
| 1714 | return handleMatrixUri(uri.toString(QUrl::ComponentFormattingOption::FullyEncoded).toUtf8()); |
| 1715 | } |
| 1716 | |
| 1717 | bool |
| 1718 | ChatPage::isRoomActive(const QString &room_id) |
| 1719 | { |
| 1720 | return QGuiApplication::focusWindow() && QGuiApplication::focusWindow()->isActive() && |
| 1721 | MainWindow::instance()->windowForRoom(room_id) == QGuiApplication::focusWindow(); |
| 1722 | } |
| 1723 | |
| 1724 | void |
| 1725 | ChatPage::removeAllNotifications() |
| 1726 | { |
| 1727 | #if defined(Q_OS_UNIX) && !defined(Q_OS_MACOS) |
| 1728 | notificationsManager->closeAllNotifications(); |
| 1729 | #endif |
| 1730 | } |
| 1731 | |
| 1732 | #include "moc_ChatPage.cpp" |