// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "MatrixRoomBridge.h" #include "MatrixManager.h" #include "MatrixRoomBridge_p.h" #include #include #include #include #include #include #include #include #include #include #include using namespace Quotient; namespace koutnet { // KOutNet - rooms and the people in them: creating and joining a room, opening a // direct chat, and the three maps the room info pages read. void MatrixRoomBridge::createRoom(const QString &name, const QString &topic, const QString &alias, const QStringList &invitedUsers, bool isPrivate) { Connection *connection = m_manager->connection(); if (connection == nullptr) return; // a name without an alias is what the "make it up as we go" rooms want; the // alias is the address pasted to join, and cannot be handed out to a private // room, so it stays local when the room is not public. connection->createRoom(isPrivate ? Connection::UnpublishRoom : Connection::PublishRoom, isPrivate ? QString() : alias, name, topic, invitedUsers) .then( [](const auto &job) { // the room arrives through joinedRoom() like any other; the list hears about it there. Q_UNUSED(job); }, [this](const auto &job) { Q_EMIT roomOperationFailed(QString(), job->errorString()); }); } void MatrixRoomBridge::joinRoom(const QString &aliasOrId) { Connection *connection = m_manager->connection(); if (connection == nullptr || aliasOrId.trimmed().isEmpty()) return; // join, then track the room the job created. a room never in this session // cache would otherwise wait for the next sync before the list hears it. connection->joinRoom(aliasOrId.trimmed()) .then( [this](const auto &job) { Room *room = m_manager->connection()->room(job->roomId(), JoinState::Join); trackRoom(room); }, [this, aliasOrId](const auto &job) { Q_EMIT roomOperationFailed(QString(), job->errorString()); }); } // Turning encryption on is a state event nobody can turn back off, so it is one // button with a confirmation rather than a switch that can be flicked back. The // three refusals are the ones that would leave a room in a state somebody has to // fix by hand. void MatrixRoomBridge::enableEncryption(const QString &chatId) { Room *room = roomFor(chatId); if (room == nullptr) { Q_EMIT roomOperationFailed(chatId, i18nc("@info:status", "The room is not available.")); return; } if (room->usesEncryption()) return; // A session that could not open its key store cannot read what it is about to // start writing: every message sent here afterwards would come back as "this // device has no key for" in the window it was sent from. Refused before the // state event, where it can still be undone by nobody. const Connection *connection = room->connection(); if (connection == nullptr || !connection->encryptionEnabled()) { Q_EMIT roomOperationFailed(chatId, i18nc("@info:status", "This session has no working encryption keys, so an encrypted room would be " "unreadable here. Fix the secret store first.")); return; } // state_default is 50, and below it the homeserver refuses the event rather // than this asking for it first: a refused write here would be reported as a // failed room, which is a different sentence from not being allowed to. if (room->memberEffectivePowerLevel() < 50) { Q_EMIT roomOperationFailed(chatId, i18nc("@info:status", "You are not allowed to change the settings of this room.")); return; } auto *job = room->setState(EncryptionEvent(EncryptionType::MegolmV1AesSha2)); connect(job, &BaseJob::finished, this, [this, room, chatId](BaseJob *finished) { if (finished->error() != BaseJob::NoError) { Q_EMIT roomOperationFailed(chatId, finished->errorString()); return; } // the room knows it is encrypted now; the page asking about it does not // until it is told, and it would go on saying the room is in the clear. publishRoom(room); }); } void MatrixRoomBridge::openDirectChat(const QString &userId) { const QString target = userId.trimmed(); auto *connection = m_manager != nullptr ? m_manager->connection() : nullptr; if (target.isEmpty() || connection == nullptr) return; // an existing direct room with just the two of us is reused, not multiplied: // the spec allows several, and neither this window nor the peer wants to // pick between lookalikes. const auto rooms = connection->allRooms(); for (Room *room : rooms) { if (room == nullptr || room->joinState() != JoinState::Join || !room->isDirectChat()) continue; if (room->joinedCount() == 2 && isJoinedMember(room, target)) { Q_EMIT directChatOpened(chatid::matrixChatId(room->id())); return; } } m_pendingDirectTarget = target; connection->requestDirectChat(target); } QVariantMap MatrixRoomBridge::roomInfo(const QString &chatId) const { QVariantMap info; const Room *room = roomFor(chatId); if (room == nullptr) return info; info.insert(QStringLiteral("roomId"), room->id()); info.insert(QStringLiteral("displayName"), matrix::conversationTitle(room->displayName(), room->id())); info.insert(QStringLiteral("topic"), room->topic()); info.insert(QStringLiteral("canonicalAlias"), room->canonicalAlias()); info.insert(QStringLiteral("altAliases"), room->altAliases()); info.insert(QStringLiteral("joinedCount"), room->joinedCount()); info.insert(QStringLiteral("invitedCount"), room->invitedCount()); info.insert(QStringLiteral("encrypted"), room->usesEncryption()); // whether this session can do encryption at all, which is not the same as // whether the room asked for it. an encrypted room without a key store is // unreadable and unwritable, and the column must say so, not draw a padlock. const Connection *connection = room->connection(); const bool trustKnown = canAskAboutTrust(connection); info.insert(QStringLiteral("encryptionActive"), connection != nullptr && connection->encryptionEnabled()); info.insert(QStringLiteral("trustKnown"), trustKnown); // only about this account own other sessions, and only one query. whether // every member every device is verified is a question the column does not // ask - one database round trip per member, and the answer is always no. info.insert(QStringLiteral("ownSessionsVerified"), trustKnown && connection->allSessionsSelfVerified(connection->userId())); // the room key backup is account-level, but this is where encryption state // is discussed, so it is reported here: does the server hold an encrypted // copy of the room keys, and has this session unlocked it. info.insert(QStringLiteral("keyBackupAvailable"), m_manager->keyBackupAvailable()); info.insert(QStringLiteral("keyBackupUnlocked"), m_manager->isKeyBackupUnlocked()); info.insert(QStringLiteral("version"), room->version()); info.insert(QStringLiteral("isDirect"), room->isDirectChat()); // what this session is allowed to do here. the column hides actions it would // only be refused for, rather than offering them and reporting the refusal. info.insert(QStringLiteral("ownPowerLevel"), room->memberEffectivePowerLevel()); const QUrl avatar = room->avatarUrl(); info.insert(QStringLiteral("avatarUrl"), (avatar.scheme() == QLatin1String("mxc") && room->connection() != nullptr) ? room->connection()->makeMediaUrl(avatar).toString() : QString()); return info; } QVariantList MatrixRoomBridge::roomMembers(const QString &chatId) const { QVariantList list; Room *room = roomFor(chatId); if (room == nullptr) return list; // setLazyLoading(true) in MatrixManager makes the homeserver send only a // handful of m.room.member events up front, so joinedMembers() starts out // short of joinedCount(). Marking the room displayed makes libQuotient // fetch the rest; memberListChanged() -> announceInfo() -> roomInfoChanged() // then makes the room info page re-read this list once they arrive. room->setDisplayed(true); // joinedMembers() rather than members(): a list that also holds everyone // who ever left is a list of a different thing. QList members = room->joinedMembers(); std::sort(members.begin(), members.end(), [](const RoomMember &left, const RoomMember &right) { if (left.powerLevel() != right.powerLevel()) return left.powerLevel() > right.powerLevel(); return left.displayName().localeAwareCompare(right.displayName()) < 0; }); list.reserve(members.size()); for (const RoomMember &member : std::as_const(members)) { QVariantMap entry; entry.insert(QStringLiteral("userId"), member.id()); entry.insert(QStringLiteral("displayName"), member.displayName().isEmpty() ? member.id() : member.displayName()); entry.insert(QStringLiteral("powerLevel"), member.powerLevel()); const QUrl avatar = member.avatarUrl(); entry.insert(QStringLiteral("avatarUrl"), (avatar.scheme() == QLatin1String("mxc") && room->connection() != nullptr) ? room->connection()->makeMediaUrl(avatar).toString() : QString()); list.append(entry); } return list; } QVariantMap MatrixRoomBridge::memberInfo(const QString &chatId, const QString &userId) const { QVariantMap info; const Room *room = roomFor(chatId); if (room == nullptr || userId.isEmpty()) return info; const RoomMember member = room->member(userId); if (member.isEmpty()) return info; info.insert(QStringLiteral("userId"), member.id()); info.insert(QStringLiteral("displayName"), member.displayName().isEmpty() ? member.id() : member.displayName()); info.insert(QStringLiteral("powerLevel"), member.powerLevel()); info.insert(QStringLiteral("isLocalMember"), member.isLocalMember()); // a ban is its own membership state on the server and outlives the member // list: a banned member is still listed, just flagged. the card answers with // the unban button instead of kick and ban on this flag. info.insert(QStringLiteral("isBanned"), room->memberState(member.id()) == Membership::Ban); // trust, one member at a time, which is the only place it is cheap enough // to ask. trustKnown false means the question could not be put - no key // store, or a member of a room nobody has shared an encrypted room with - // and the card says that rather than reporting an unverified device this // session never looked at. const Connection *connection = room->connection(); const bool trustKnown = canAskAboutTrust(connection); info.insert(QStringLiteral("trustKnown"), trustKnown); info.insert(QStringLiteral("userVerified"), trustKnown && connection->isUserVerified(member.id())); // this libQuotient build has no devicesForUser() implementation, so a // per-device count is not available and only the padlock is shown. int deviceCount = 0; int verifiedDeviceCount = 0; info.insert(QStringLiteral("deviceCount"), deviceCount); info.insert(QStringLiteral("verifiedDeviceCount"), verifiedDeviceCount); const QUrl avatar = member.avatarUrl(); info.insert(QStringLiteral("avatarUrl"), (avatar.scheme() == QLatin1String("mxc") && room->connection() != nullptr) ? room->connection()->makeMediaUrl(avatar).toString() : QString()); return info; } // The newest banner a member announced into this room, read out of the // timeline's loaded history. A per-room scan rather than a cache: the sender // re-sends the picture into every room when it changes, so the newest message // from that member with the banner msgtype IS the current answer, and a cache // would need its own invalidation to say the same thing. QString MatrixRoomBridge::memberBanner(const QString &chatId, const QString &userId) const { const Room *room = roomFor(chatId); if (room == nullptr || room->connection() == nullptr || userId.isEmpty()) return {}; for (int i = room->maxTimelineIndex(); i >= room->minTimelineIndex(); --i) { const auto it = room->findInTimeline(i); if (it == room->historyEdge()) continue; const auto *message = eventCast(it->event()); if (message == nullptr || message->senderId() != userId || message->rawMsgtype() != QStringLiteral("im.koutnet.banner")) continue; const QUrl source(message->contentJson().value(QStringLiteral("url")).toString()); if (source.scheme() != QLatin1String("mxc")) continue; return room->connection()->makeMediaUrl(source).toString(); } return {}; } } // namespace koutnet