// 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 "core/media/OutgoingFile.h" #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Quotient; namespace koutnet { // KOutNet - the editing half of a conversation: reactions, edits, deletions, // replies, room name, topic and avatar, pins, the ignore list, search, invites. void MatrixRoomBridge::markRead(const QString &chatId) { if (Room *room = roomFor(chatId)) room->markAllMessagesAsRead(); } bool MatrixRoomBridge::leaveChat(const QString &chatId) { Room *room = roomFor(chatId); if (room == nullptr) return false; const auto job = room->leaveRoom(); // the window must not wait for sync to echo the leave: join-state changes // are driven by sync, so with the loop down or slow the row would linger - // "I left and the chat is still here" was the report. when sync does echo, // Connection::leftRoom lands too and the handler is idempotent. if (job != nullptr) { connect(job.data(), &Quotient::BaseJob::success, this, [this, chatId]() { Q_EMIT roomLeft(chatId); }); } return true; } void MatrixRoomBridge::sendReaction(const QString &chatId, const QVariant &identifier, const QString &emoji, bool added) { Room *room = roomFor(chatId); // identifier is either a string (event id) or a double (stamp). The string // path is preferred: it is exact and cannot collide. QString eventId; if (identifier.canConvert()) eventId = identifier.toString(); else eventId = m_tsToEventId.value(chatId).value(identifier.toDouble()); if (room == nullptr || eventId.isEmpty() || emoji.isEmpty()) return; if (added) { // the local reaction store decides added/removed from disk, and across // a restart or account switch that can be wrong: the tap then arrives as // "add" for a reaction this account already sent, and the server answers // the second copy with a 400. the room annotations are the truth - // an existing one from this account means the tap meant "off", a redaction. const auto &annotations = room->relatedEvents(eventId, EventRelation::AnnotationType); for (const RoomEvent *annotation : annotations) { const auto *reaction = eventCast(annotation); if (reaction && reaction->key() == emoji && !room->connection()->userId().isEmpty() && reaction->senderId() == room->connection()->userId()) { room->redactEvent(reaction->id()); return; } } room->postReaction(eventId, emoji); return; } // Redact all matching reaction events from this session. const auto &annotations = room->relatedEvents(eventId, EventRelation::AnnotationType); for (const RoomEvent *annotation : annotations) { const auto *reaction = eventCast(annotation); if (reaction && reaction->key() == emoji && !room->connection()->userId().isEmpty() && reaction->senderId() == room->connection()->userId()) room->redactEvent(reaction->id()); } } bool MatrixRoomBridge::sendEdit(const QString &chatId, const QVariant &identifier, const QString &newText) { if (newText.trimmed().isEmpty()) return false; Room *room = roomFor(chatId); QString eventId; if (identifier.canConvert()) eventId = identifier.toString(); else eventId = m_tsToEventId.value(chatId).value(identifier.toDouble()); if (room == nullptr || eventId.isEmpty()) return false; if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return false; } // everything an edit needs is in the related-to: the replacement body and // an m.relates_to with the corrected event serial. libQuotient stamps // new_content itself, which is what every other client reads back. room->postText(newText, std::nullopt, EventRelation::replace(eventId)); return true; } bool MatrixRoomBridge::sendDelete(const QString &chatId, const QVariant &identifier) { Room *room = roomFor(chatId); QString eventId; if (identifier.canConvert()) eventId = identifier.toString(); else eventId = m_tsToEventId.value(chatId).value(identifier.toDouble()); if (room == nullptr || eventId.isEmpty()) return false; room->redactEvent(eventId); return true; } bool MatrixRoomBridge::sendReply(const QString &chatId, const QVariant &identifier, const QString &plainText) { const double ts = identifier.toDouble(); if (plainText.trimmed().isEmpty()) return false; Room *room = roomFor(chatId); const QString eventId = m_tsToEventId.value(chatId).value(ts); if (room == nullptr || eventId.isEmpty()) return false; if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return false; } room->postText(plainText, std::nullopt, EventRelation::replyTo(eventId)); return true; } bool MatrixRoomBridge::sendRichText(const QString &chatId, const QString &plainText, const QString &html) { if (plainText.trimmed().isEmpty()) return false; Room *room = roomFor(chatId); if (room == nullptr) { 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; } // the composer passes an empty html when it only has markdown; derive the // formatted body here so the window never has to know the markup dialect. QString htmlBody = html; if (htmlBody.isEmpty() && looksFormatted(plainText)) htmlBody = markdownToHtml(plainText); const std::optional htmlOpt = htmlBody.isEmpty() ? std::nullopt : std::optional(htmlBody); room->postText(plainText, htmlOpt); return true; } void MatrixRoomBridge::setRoomName(const QString &chatId, const QString &name) { if (Room *room = roomFor(chatId)) room->setName(name); } void MatrixRoomBridge::setRoomTopic(const QString &chatId, const QString &topic) { if (Room *room = roomFor(chatId)) room->setTopic(topic); } void MatrixRoomBridge::setRoomAvatar(const QString &chatId, const QString &localFilePath) { Room *room = roomFor(chatId); if (room == nullptr || room->connection() == nullptr) { Q_EMIT roomOperationFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return; } // Upload the picture, then point the room's avatar state at the mxc id the // homeserver returns - the same two-step the file transfer uses, so an avatar // and an attachment fail and recover the same way. // No explicit content type: passing one makes uploadContent() skip opening // the file, and BaseJob::initiate() then rejects the still-closed device // with "Request data not ready" (FileError). Let libQuotient detect the // type from the name and open the file itself. // // A room avatar is drawn forty pixels across, so a photograph handed to this // is uploaded at its full resolution and served to every member of the room // in every message header, forever. It is scaled and re-encoded on the way // in, at a size the drawing actually wants. const QString path = localFilePath.startsWith(QStringLiteral("file://")) ? QUrl(localFilePath).toLocalFile() : localFilePath; auto job = room->connection()->uploadFile(OutgoingFile::preparedPath(path)); connect(job.operator->(), &Quotient::BaseJob::success, this, [this, chatId, job]() { // Re-resolve: the room may have been left while the upload was in flight. Room *room = roomFor(chatId); if (!room) return; Quotient::BaseJob *stateJob = room->setState(Quotient::RoomAvatarEvent(job->contentUri())); if (stateJob != nullptr) { // A homeserver refusal (no permission, restricted room) must surface: // the upload itself succeeding is not the same as the avatar applying. connect(stateJob, &Quotient::BaseJob::failure, this, [this, chatId, stateJob]() { Q_EMIT roomOperationFailed(chatId, stateJob->errorString()); }); } Q_EMIT roomOperationSucceeded(chatId); }); connect(job.operator->(), &Quotient::BaseJob::failure, this, [this, chatId, job]() { Q_EMIT roomOperationFailed(chatId, job->errorString()); }); } void MatrixRoomBridge::pinMessage(const QString &chatId, const QVariant &identifier) { const double ts = identifier.toDouble(); Room *room = roomFor(chatId); if (room == nullptr) return; const QString eventId = m_tsToEventId.value(chatId).value(ts); if (eventId.isEmpty()) return; QStringList pinned = room->pinnedEventIds(); if (!pinned.contains(eventId)) { pinned.append(eventId); room->setPinnedEvents(pinned); } } void MatrixRoomBridge::unpinMessage(const QString &chatId, const QVariant &identifier) { const double ts = identifier.toDouble(); Room *room = roomFor(chatId); if (room == nullptr) return; const QString eventId = m_tsToEventId.value(chatId).value(ts); if (eventId.isEmpty()) return; QStringList pinned = room->pinnedEventIds(); pinned.removeAll(eventId); room->setPinnedEvents(pinned); } void MatrixRoomBridge::ignoreUser(const QString &userId) { if (m_manager && m_manager->connection()) if (User *u = m_manager->connection()->user(userId)) u->ignore(); } void MatrixRoomBridge::unignoreUser(const QString &userId) { if (m_manager && m_manager->connection()) if (User *u = m_manager->connection()->user(userId)) u->unmarkIgnore(); } void MatrixRoomBridge::searchMessages(const QString &chatId, const QString &query) { QVariantList results; if (Room *room = roomFor(chatId)) { const QString q = query.toLower(); for (const auto &item : room->messageEvents()) { const RoomEvent *ev = item.event(); const auto *me = eventCast(ev); if (!me) continue; if (me->plainBody().toLower().contains(q)) { results.append(rowForEvent(ev)); if (results.size() >= 50) break; } } } Q_EMIT roomSearchResults(chatId, results); } void MatrixRoomBridge::acceptInvite(const QString &chatId) { // invite is a JoinState::Invite room, find it through invitedRoomFor() Room *room = invitedRoomFor(chatId); if (room == nullptr) return; // joining is a connection-level call in libQuotient; the room state // catches up when the join lands, and trackRoom() picks it up there. m_manager->connection()->joinRoom(room->id()); } void MatrixRoomBridge::declineInvite(const QString &chatId) { Room *room = invitedRoomFor(chatId); if (room == nullptr) return; room->leaveRoom(); } void MatrixRoomBridge::inviteMember(const QString &chatId, const QString &userId) { Room *room = roomFor(chatId); if (room == nullptr || userId.trimmed().isEmpty()) return; room->inviteToRoom(userId.trimmed()); } void MatrixRoomBridge::kickMember(const QString &chatId, const QString &userId) { Room *room = roomFor(chatId); if (room == nullptr || userId.trimmed().isEmpty()) return; room->kickMember(userId.trimmed()); } void MatrixRoomBridge::banMember(const QString &chatId, const QString &userId) { Room *room = roomFor(chatId); if (room == nullptr || userId.trimmed().isEmpty()) return; room->ban(userId.trimmed()); } void MatrixRoomBridge::unbanMember(const QString &chatId, const QString &userId) { Room *room = roomFor(chatId); if (room == nullptr || userId.trimmed().isEmpty()) return; room->unban(userId.trimmed()); } } // namespace koutnet