// 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 - the bridge itself: attaching to a connection, turning room events // into model rows, sending text, and the capability questions the registry asks. // The rest of the class is split by subject into the MatrixRoom*.cpp files beside // this one. MatrixRoomBridge::MatrixRoomBridge(MatrixManager *manager, QObject *parent) : ChatBackend(parent) , m_manager(manager) { // Downloads are watched on their files. The library says a transfer finished // and where it is, which is the first thing to believe, but it says nothing // at all in some of the cases that matter - a file it is told to fetch that // is already there, a transfer that was under way before this program asked // for it - and a timeline waiting for a signal that never comes is a // timeline of empty rectangles. m_mediaWatch.setInterval(250); connect(&m_mediaWatch, &QTimer::timeout, this, &MatrixRoomBridge::pollMediaDownloads); if (m_manager) { connect(m_manager, &MatrixManager::connectionChanged, this, [this]() { // detached by hand, not left to the rooms being destroyed: a // connection on its way out lives until the server answers or gives // up, and its rooms would keep filing messages into a session the // user already left. for (const QPointer &room : std::as_const(m_tracked)) { if (room) room->disconnect(this); } m_tracked.clear(); attach(m_manager ? m_manager->connection() : nullptr); }); attach(m_manager->connection()); } } void MatrixRoomBridge::attach(Connection *connection) { if (!connection) return; connect(connection, &Connection::joinedRoom, this, [this](Room *room) { trackRoom(room); }); connect(connection, &Connection::invitedRoom, this, [this](Room *room, Room *) { // nothing to track yet (see trackRoom). The join moves it through // joinedRoom() and the invite object is deleted, which is how the list // knows it is gone. QString inviterId; QString inviterName; inviterOf(room, &inviterId, &inviterName); Q_EMIT roomInvited(chatid::matrixChatId(room->id()), matrix::conversationTitle(room->displayName(), room->id()), inviterId, inviterName); }); connect(connection, &Connection::loadedRoomState, this, [this](Room *room) { // the room name and members are only settled here; joinedRoom() fires // while the object is still nameless, which is why rows used to appear // titled with their room id and stay that way. trackRoom(room); }); connect(connection, &Connection::leftRoom, this, [this](Room *room, Room *prev) { const QString chatId = chatid::matrixChatId(room->id()); m_tracked.remove(room->id()); m_tsToEventId.remove(chatId); m_eventIdToTs.remove(chatId); m_lastTypingSent.remove(chatId); m_reactions.remove(chatId); m_calls.remove(chatId); Q_EMIT roomLeft(chatId); // declining an invite: the room we were asked into matches a new object // (this one), and the invite object itself is in prev. if (prev != nullptr && prev->joinState() == JoinState::Invite) Q_EMIT roomInviteGone(chatid::matrixChatId(prev->id())); }); connect(connection, &Connection::aboutToDeleteRoom, this, [this](Room *room) { const QString chatId = chatid::matrixChatId(room->id()); if (m_tracked.value(room->id()) == room) { m_tracked.remove(room->id()); m_tsToEventId.remove(chatId); m_eventIdToTs.remove(chatId); m_lastTypingSent.remove(chatId); m_reactions.remove(chatId); m_calls.remove(chatId); } // the other way an invite dies: the join landed, a stale invite object // was created and is being retired. no leftRoom() precedes this. if (room->joinState() == JoinState::Invite) Q_EMIT roomInviteGone(chatId); }); // a verification that just succeeded moved the trust table, and the column // and card draw straight from it. without this the padlock only catches up // when something else makes the column re-read, which for a quiet room never // happens. auto retellTrust = [this]() { const auto ids = m_tracked.keys(); for (const QString &roomId : ids) Q_EMIT roomInfoChanged(chatid::matrixChatId(roomId)); }; connect(connection, &Connection::sessionVerified, this, retellTrust); connect(connection, &Connection::userVerified, this, retellTrust); // whatever loadState() already put in place; later rooms come via the signals above. const auto rooms = connection->allRooms(); for (Room *room : rooms) trackRoom(room); } void MatrixRoomBridge::trackRoom(Room *room) { // an invitation is a room we have no timeline in yet, so it cannot be opened // as a chat. the Connection hands every join-state transition to a different // Room object - an invite is its own Room, deleted the moment the join lands // - so invites are announced by attach() and never tracked here. if (!room || room->joinState() != JoinState::Join) return; if (m_tracked.value(room->id()) == room) { // already wired; the name may still have moved. publishRoom(room); return; } m_tracked.insert(room->id(), room); // a direct room asked for by openDirectChat() comes through the join after // the homeserver made it; emit the moment it is the one requested. if (!m_pendingDirectTarget.isEmpty() && room->isDirectChat() && isJoinedMember(room, m_pendingDirectTarget) && room->joinedCount() == 2) { m_pendingDirectTarget.clear(); Q_EMIT directChatOpened(chatid::matrixChatId(room->id())); } connect(room, &Room::addedMessages, this, [this, room](int fromIndex, int toIndex) { publishRange(room, fromIndex, toIndex); }); // Standalone poll events bypass addedMessages(); publish them from this signal. connect(room, &Room::aboutToAddNewMessages, this, [this, room](const Quotient::RoomEventsRange &events) { for (const auto &ev : events) { const RoomEvent *event = ev.get(); // Registered event types identify polls without inspecting raw JSON. if (eventCast(event) || eventCast(event)) { publishEvent(room, event); } } }); // this is how an outgoing message reaches the timeline, and the only way. // addedMessages() fires for a sync span that is not an echo of our own send; // mergePendingEvent() folds our message into its pending item and emits // this instead. a message typed here was posted, accepted by the server and // seen by every other client, but never shown on this screen. connect(room, &Room::pendingEventAboutToMerge, this, [this, room](RoomEvent *serverEvent, int) { publishEvent(room, serverEvent); }); // the other half of the silence: a send libQuotient gave up on. connect(room, &Room::pendingEventChanged, this, [this, room](int index) { reportPendingFailure(room, index); }); connect(room, &Room::displaynameChanged, this, [this, room]() { publishRoom(room); }); // A megolm key that turned up after the message it opens. libQuotient swaps // the decrypted event into the timeline in place; without this the // placeholder row stays one for the rest of the run despite the text. connect(room, &Room::replacedEvent, this, [this, room](const RoomEvent *newEvent, const RoomEvent *) { revealEvent(room, newEvent); }); // A download finishing, or failing. The file it is watched in is the thing // that decides, so this is only the faster of the two answers; the id is the // event's own, and the watch is what says which chat and which row it is. connect(room, &Room::fileTransferCompleted, this, [this](const QString &eventId, const QUrl &, FileSourceInfo) { // An upload that lands reports itself by its transaction id here: the // entry has said its piece and can go. m_uploadTxns.remove(eventId); finishMediaDownload(eventId); }); connect(room, &Room::fileTransferFailed, this, [this](const QString &eventId, const QString &errorMessage) { failMediaDownload(eventId, errorMessage.isEmpty() ? i18nc("@info:status", "This attachment could not be downloaded.") : errorMessage); }); // The id is either a download's event id or an upload's transaction id, and // the set is what tells the two apart. An upload failure never reaches the // server, so no echo would ever show the sender a row: this handler is the // one place the silence gets a sentence, and it is said as sendFailed. connect(room, &Room::fileTransferFailed, this, [this, room](const QString &eventId, const QString &errorMessage) { if (m_uploadTxns.remove(eventId) > 0) { Q_EMIT sendFailed(chatid::matrixChatId(room->id()), errorMessage.isEmpty() ? i18nc("@info:status", "The file could not be uploaded to the server.") : errorMessage); return; } Q_EMIT attachmentFailed(chatid::matrixChatId(room->id()), eventId, errorMessage.isEmpty() ? i18nc("@info:status", "This attachment could not be downloaded.") : errorMessage); }); // someone in the room is typing. the window shows one indicator per chat // and does not name who, so a boolean; and it is otherMembersTyping(), not // membersTyping(), since our own typing must not light the indicator we set. connect(room, &Room::typingChanged, this, [this, room]() { Q_EMIT roomTyping(chatid::matrixChatId(room->id()), !room->otherMembersTyping().isEmpty()); }); // a read receipt moved. reported only for someone else receipt, and only // when it is about our own message: a third member read says nothing about // whether our messages were read, and claiming it would be the same lie as // the LAN path for a message that was never on screen. connect(room, &Room::lastReadEventChanged, this, [this, room](const QVector &userIds) { const QString ownId = room->connection() ? room->connection()->userId() : QString(); for (const QString &userId : userIds) { if (userId == ownId) continue; emitReceiptUpTo(room, userId); } }); // the room column reads all of these through roomInfo(), so they share one signal. const auto announceInfo = [this, room]() { Q_EMIT roomInfoChanged(chatid::matrixChatId(room->id())); }; connect(room, &Room::topicChanged, this, announceInfo); // a room that just turned encryption on changes what the column says. the // timeline line for the same event comes from the m.room.encryption state // event like any other. connect(room, &Room::encryption, this, announceInfo); connect(room, &Room::avatarChanged, this, announceInfo); connect(room, &Room::fileTransferCompleted, this, [this, room](const QString &id, const QUrl &url) { Q_EMIT attachmentReady(chatid::matrixChatId(room->id()), id, url); }); connect(room, &Room::fileTransferFailed, this, [this, room](const QString &id, const QString &error) { Q_EMIT attachmentFailed(chatid::matrixChatId(room->id()), id, error); }); connect(room, &Room::memberListChanged, this, announceInfo); connect(room, &Room::namesChanged, this, announceInfo); connect(room, &Room::pinnedEventsChanged, this, [this, room]() { Q_EMIT roomPinnedChanged(chatid::matrixChatId(room->id()), pinnedRows(room)); }); // m.call.invite/answer/hangup. libQuotient hands the whole event over; the // caller is in the sender, the rest in the content. connect(room, &Room::callEvent, this, [this](Room *callRoom, const RoomEvent *event) { handleCallEvent(callRoom, event); }); publishRoom(room); // whatever is already in the timeline from the state cache. indices run from // the oldest known event to the newest, both inclusive. if (!room->messageEvents().empty()) publishRange(room, room->minTimelineIndex(), room->maxTimelineIndex()); // The receipts the server already knew about when this timeline was // replayed. Without this a read that happened while the session was away // stays a single tick until the next live receipt moves - which may be days. const QString ownId = room->connection() ? room->connection()->userId() : QString(); const auto members = room->members(); for (const RoomMember &member : members) { if (member.id() != ownId) emitReceiptUpTo(room, member.id()); } } void MatrixRoomBridge::publishRoom(Room *room) { const QString chatId = chatid::matrixChatId(room->id()); Q_EMIT roomListed(chatId, matrix::conversationTitle(room->displayName(), room->id()), roomAvatarUrl(room), !room->isDirectChat()); Q_EMIT roomInfoChanged(chatId); } void MatrixRoomBridge::publishRange(Room *room, int fromIndex, int toIndex) { for (int i = fromIndex; i <= toIndex; ++i) { const auto it = room->findInTimeline(i); // out-of-range lookups hand back historyEdge(), the only sentinel the // reverse iterator has (= crend()), and dereferencing it is UB. the // range comes from the room min/max, so this is usually in range; // the check is for the index that races an ongoing sync. if (it == room->historyEdge()) continue; publishEvent(room, it->event()); } } void MatrixRoomBridge::publishEvent(Room *room, const RoomEvent *event) { if (room == nullptr || event == nullptr) return; const QString chatId = chatid::matrixChatId(room->id()); // a reaction is never a row: it is about a message already on screen and // earns no line of its own. the ReactionStore keys on the target message // stamp, like the LAN protocol, so the reaction timestamp itself is not sent. if (const auto *reaction = eventCast(event)) { const QString reactionId = event->id(); const double targetTs = m_eventIdToTs.value(chatId).value(reaction->eventId()); // a redacted reaction loses its content, so the emoji is gone from the // event; it is remembered here from when the reaction was first sent. if (event->isRedacted()) { auto &reactions = m_reactions[chatId]; const auto it = reactions.constFind(reactionId); if (it != reactions.constEnd()) { Q_EMIT roomReaction(chatId, it->targetTs, it->emoji, it->sender, false); reactions.erase(it); } return; } if (targetTs > 0.0 && !reaction->key().isEmpty()) { // our own reaction also comes back through sync, but the local // toggle already filed it under "me"; the echo would badge the // same reaction twice under two names - and the label is the // display name, not "me". const QString ownId = room->connection() ? room->connection()->userId() : QString(); if (reaction->senderId() != ownId) Q_EMIT roomReaction(chatId, targetTs, reaction->key(), memberLabel(room, reaction->senderId()), true); m_reactions[chatId].insert(reactionId, {targetTs, reaction->key(), memberLabel(room, reaction->senderId())}); } return; } // a redaction takes a message or a reaction back. the redacted event stays // in the timeline, so what the window shows is told apart by who redacted: // a message row is removed, a reaction badge taken down. if (const auto *redaction = eventCast(event)) { const QString redactedId = redaction->redactedEvent(); auto &reactions = m_reactions[chatId]; const auto it = reactions.constFind(redactedId); if (it != reactions.constEnd()) { Q_EMIT roomReaction(chatId, it->targetTs, it->emoji, it->sender, false); reactions.erase(it); return; } if (m_eventIdToTs.value(chatId).contains(redactedId)) Q_EMIT roomMessageRemoved(chatId, redactedId); return; } // an edit is dealt with first and never becomes a row: it is about a message // already on screen. if (const auto *message = eventCast(event)) { const QString replaced = message->replacedEvent(); if (!replaced.isEmpty()) { const QString body = replacementBody(*message); if (!body.isEmpty()) Q_EMIT roomMessageEdited(chatId, replaced, body, replacementFormattedBody(*message)); return; } // A banner is someone's header picture carried as a message, KOutNet's // own msgtype. It earns no timeline row: the profile card reads the // newest one out of the room's history, and this signal tells a card // that is already open to re-read it. if (message->rawMsgtype() == QStringLiteral("im.koutnet.banner")) { Q_EMIT roomBanner(chatId, message->senderId()); return; } } const matrix::Row row = matrix::rowFor(flatten(room, event)); switch (row.kind) { case matrix::RowKind::Skip: break; case matrix::RowKind::Text: { const QString avatar = memberAvatarUrl(room, row.senderId); Q_EMIT roomMessage(chatId, row.msgId, row.text, row.sender, row.isOwn, row.ts, false, avatar, row.formattedText, row.senderId); break; } case matrix::RowKind::System: { const QString avatar = memberAvatarUrl(room, row.senderId); Q_EMIT roomMessage(chatId, row.msgId, row.text, row.sender, row.isOwn, row.ts, true, avatar, QString(), row.senderId); break; } case matrix::RowKind::Encrypted: { // per event, not per room. the room is readable; this message is not, // and saying so about the room would be a lie about the rest. const QString avatar = memberAvatarUrl(room, row.senderId); Q_EMIT roomMessage(chatId, row.msgId, row.text, row.sender, row.isOwn, row.ts, true, avatar, QString(), row.senderId); break; } case matrix::RowKind::Attachment: { QVariantMap media; media.insert(QStringLiteral("kind"), mediaKindName(row.media)); media.insert(QStringLiteral("url"), row.mediaUrl); media.insert(QStringLiteral("thumbnailUrl"), row.thumbnailUrl); media.insert(QStringLiteral("name"), row.mediaName); media.insert(QStringLiteral("mime"), row.mediaMime); media.insert(QStringLiteral("size"), QVariant::fromValue(row.mediaSize)); media.insert(QStringLiteral("width"), row.mediaWidth); media.insert(QStringLiteral("height"), row.mediaHeight); media.insert(QStringLiteral("duration"), row.mediaDurationMs); const QString avatar = memberAvatarUrl(room, row.senderId); Q_EMIT roomAttachment(chatId, row.msgId, media, row.sender, row.isOwn, row.ts, avatar, row.senderId); break; } case matrix::RowKind::Poll: { // the question and options ride as structured data, not as a string the // window would have to re-parse; votes go back through sendPollVote(). const QString avatar = memberAvatarUrl(room, row.senderId); Q_EMIT roomPoll(chatId, row.msgId, row.poll.value(QStringLiteral("question")).toString(), row.poll.value(QStringLiteral("answers")).toList(), row.poll.value(QStringLiteral("disclosed")).toBool(), row.sender, row.isOwn, row.ts, avatar, row.senderId); break; } case matrix::RowKind::PollVote: { // not a row: an amendment to the poll named by row.msgId. The window keeps // the tally, and the event id here is the poll it votes on, not a message. Q_EMIT roomPollVote(chatId, row.msgId, row.pollAnswerId, row.senderId, row.isOwn); break; } } // the window addresses messages by stamp, the homeserver by event id; both // directions are kept so a reaction/edit/unsend resolves to the event it is // about. system rows carry a synthetic id that cannot be reacted to, so // they are not indexed - a reaction to a state line has no Matrix event. A // poll vote names the poll it answers, not itself, so it is not indexed either. if (!row.msgId.isEmpty() && row.kind != matrix::RowKind::Skip && row.kind != matrix::RowKind::System && row.kind != matrix::RowKind::PollVote && row.ts > 0.0) { m_tsToEventId[chatId].insert(row.ts, row.msgId); m_eventIdToTs[chatId].insert(row.msgId, row.ts); } } void MatrixRoomBridge::revealEvent(Room *room, const RoomEvent *event) { if (room == nullptr || event == nullptr) return; // only a decryption. libQuotient also emits replacedEvent() for an m.replace, // handled where the replacement arrives; the original is kept only when the // swap was a decryption. if (event->originalEvent() == nullptr) return; const matrix::Row row = matrix::rowFor(flatten(room, event)); if (row.kind == matrix::RowKind::Skip || row.kind == matrix::RowKind::Encrypted || row.text.isEmpty()) return; // text for an attachment too. the row went in as a placeholder line and a // line is what it can become again; turning it into a picture would replace // the entry, and a late-keyed attachment is rare enough not to earn that. // it is named rather than left saying there is no key, which would be untrue. Q_EMIT roomMessageRevealed(chatid::matrixChatId(room->id()), row.msgId, row.text, row.formattedText); } void MatrixRoomBridge::emitReceiptUpTo(Room *room, const QString &userId) { if (room == nullptr || room->connection() == nullptr || userId.isEmpty()) return; const QString ownId = room->connection()->userId(); if (ownId.isEmpty()) return; const ReadReceipt receipt = room->lastReadReceipt(userId); const QString chatId = chatid::matrixChatId(room->id()); const auto target = room->findInTimeline(receipt.eventId); // a receipt for an event outside this timeline says nothing this window can // place: the message may be anything, and guessing would be a claim. if (target == room->historyEdge()) return; // a receipt over somebody else's message says nothing about ours. if (target->event()->senderId() != ownId) return; // the stamp the receipt names, looked up the same way reactions and edits // resolve their targets. Zero falls back to "everything of ours is read", // which is the only true sentence left when the target is ours but older // than anything the window still indexes. Q_EMIT roomReadReceipt(chatId, m_eventIdToTs.value(chatId).value(receipt.eventId, 0.0)); } void MatrixRoomBridge::reportPendingFailure(Room *room, int pendingIndex) { if (room == nullptr || pendingIndex < 0) return; const auto &pending = room->pendingEvents(); if (size_t(pendingIndex) >= pending.size()) return; const auto &item = pending[size_t(pendingIndex)]; // every other status is progress and says itself in the timeline. if (item.deliveryStatus() != EventStatus::SendingFailed) return; const QString reason = item.annotation(); Q_EMIT sendFailed( chatid::matrixChatId(room->id()), reason.isEmpty() ? i18nc("@info:status a Matrix message was not accepted and nothing said why", "The message could not be sent to this room.") : i18nc("@info:status a Matrix message was not accepted, %1 is what the homeserver reported", "The message could not be sent: %1", reason)); } Room *MatrixRoomBridge::roomFor(const QString &chatId) const { const QString roomId = chatid::matrixRoomId(chatId); if (roomId.isEmpty() || !m_manager || !m_manager->connection()) return nullptr; return m_manager->connection()->room(roomId, JoinState::Join); } Room *MatrixRoomBridge::invitedRoomFor(const QString &chatId) const { const QString roomId = chatid::matrixRoomId(chatId); if (roomId.isEmpty() || !m_manager || !m_manager->connection()) return nullptr; // invites are JoinState::Invite rooms, roomFor() only sees Join, so look here return m_manager->connection()->room(roomId, JoinState::Invite); } void MatrixRoomBridge::inviterOf(Room *room, QString *inviterId, QString *inviterName) const { if (inviterId != nullptr) inviterId->clear(); if (inviterName != nullptr) inviterName->clear(); if (room == nullptr || room->connection() == nullptr) return; // the inviter is whoever sent our own m.room.member invite event const QString ownId = room->connection()->userId(); const auto *memberEvent = room->currentState().get(ownId); if (memberEvent == nullptr) return; const QString sender = memberEvent->senderId(); if (sender.isEmpty()) return; if (inviterId != nullptr) *inviterId = sender; if (inviterName != nullptr) { const auto member = room->member(sender); const QString name = member.displayName(); *inviterName = name.isEmpty() ? sender : name; } } bool MatrixRoomBridge::sendText(const QString &chatId, const QString &text) { if (text.trimmed().isEmpty()) return false; // split from the lookup so the two errors are not reported as one: a session // that is down and a room that is not joined need different answers, and // "not available" used to be the same sentence for both. if (!m_manager || !m_manager->connection()) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "Not signed in to Matrix, so this message was not sent.")); return false; } Room *room = roomFor(chatId); if (!room) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return false; } if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return false; } // nothing here encrypts. libQuotient does it all inside the send: // doSendEvent() makes or rotates the outbound megolm session, ships the key // to every device without it, and puts an m.room.encrypted on the wire. room->postText(text); return true; } chatid::Transport MatrixRoomBridge::transport() const { return chatid::Transport::Matrix; } bool MatrixRoomBridge::canHandle(const QString &chatId) const { return chatid::isMatrix(chatId); } bool MatrixRoomBridge::serverOwnsTimeline(const QString &) const { return true; } bool MatrixRoomBridge::hasRooms(const QString &) const { return true; } bool MatrixRoomBridge::supportsCalls(const QString &) const { // a room call rides the LAN voice channel, so the answer is whether the // local side exists - which is every real session, voice is not optional. return m_net != nullptr && m_voice != nullptr; } bool MatrixRoomBridge::supportsTyping(const QString &) const { return true; } bool MatrixRoomBridge::supportsEdits(const QString &) const { return true; } bool MatrixRoomBridge::supportsReactions(const QString &) const { return true; } void MatrixRoomBridge::sendTyping(const QString &chatId) { // no stop packet: a typing event carries a timeout the server clears. // Cost: one HTTP round trip per packet, so the bridge sends one only when // the previous has been on the wire long enough. 4s ≈ a sentence. if (!m_manager || !m_manager->connection()) return; Room *room = roomFor(chatId); if (room == nullptr) return; const qint64 now = QDateTime::currentMSecsSinceEpoch(); const qint64 last = m_lastTypingSent.value(chatId, 0); if (now - last < 4000) return; m_lastTypingSent.insert(chatId, now); // 10s timeout: short enough to clear a walk-away, long enough to survive a pause. m_manager->connection()->callApi(m_manager->connection()->userId(), room->id(), true, 10000); } } // namespace koutnet