// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - the room-event helpers MatrixRoomBridge's translation units share. // // Not a public header: nothing outside src/matrix/ includes it. The definitions // are inline inside an anonymous namespace, so each of those units keeps its own // copy and none of them pays for the ones it never calls. #pragma once #include "MatrixTranslate.h" #include "core/chat/TextHandler.h" #include "pollevent.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace koutnet { // The helpers were written against the same using-directive the bridge's own // translation units carry, so the unqualified Quotient names in their signatures // still mean what they meant in one file. using namespace Quotient; namespace { using koutnet::matrix::MediaKind; using koutnet::matrix::StateChange; inline MediaKind mediaKindOf(RoomMessageEvent::MsgType type) { switch (type) { case RoomMessageEvent::MsgType::Image: return MediaKind::Image; case RoomMessageEvent::MsgType::Video: return MediaKind::Video; case RoomMessageEvent::MsgType::Audio: return MediaKind::Audio; case RoomMessageEvent::MsgType::File: return MediaKind::File; default: return MediaKind::None; } } // a name, not the enum number; the other end is QML, where a number is unreadable. inline QString mediaKindName(MediaKind kind) { switch (kind) { case MediaKind::Image: return QStringLiteral("image"); case MediaKind::Video: return QStringLiteral("video"); case MediaKind::Audio: return QStringLiteral("audio"); case MediaKind::File: return QStringLiteral("file"); case MediaKind::Location: return QStringLiteral("location"); case MediaKind::None: break; } return QString(); } // without a key store libQuotient drops the event, and sending in the clear // is never right. inline bool canSendEncrypted(const Room *room) { if (room == nullptr || !room->usesEncryption()) return true; return room->connection() != nullptr && room->connection()->encryptionEnabled(); } // The key that seals call media rides in the invite and answer events // themselves, so it is only as private as those events are. An unencrypted // room would carry the key in cleartext for anyone on the federation path, so // a room call is refused unless the whole room is sealed. inline bool roomCallAllowed(const Room *room) { if (room == nullptr || !room->usesEncryption()) return false; return room->connection() != nullptr && room->connection()->encryptionEnabled(); } // Whether the UI may offer to verify a device at all. Separate from // roomCallAllowed(): a room can be encrypted while the device list is out of // reach, and then there is nothing to show either. inline bool canAskAboutTrust(const Connection *connection) { return connection != nullptr && connection->encryptionEnabled(); } inline QString encryptionUnavailableReason() { return i18nc("@info:status a message for an encrypted room was not sent because the session has no keys", "This room is end-to-end encrypted and this session could not open its encryption keys, so nothing was sent."); } // never blank inline QString memberLabel(const Room *room, const QString &userId) { if (room == nullptr || userId.isEmpty()) return userId; const QString name = room->member(userId).displayName(); return name.isEmpty() ? userId : name; } // Resolve room-specific avatars, including the local member's avatar. inline QString memberAvatarUrl(const Room *room, const QString &userId) { if (room == nullptr || userId.isEmpty() || room->connection() == nullptr) return QString(); const QUrl avatar = room->member(userId).avatarUrl(); if (avatar.scheme() != QLatin1String("mxc")) return QString(); return room->connection()->makeMediaUrl(avatar).toString(); } // whether a member is currently joined. inline bool isJoinedMember(const Room *room, const QString &userId) { if (room == nullptr || userId.isEmpty()) return false; return room->memberState(userId) == Membership::Join; } // the picture a conversation row carries. empty when none. inline QString roomAvatarUrl(const Room *room) { if (room == nullptr || room->connection() == nullptr) return QString(); if (room->isDirectChat()) { const auto members = room->joinedMembers(); for (const RoomMember &member : members) { if (member.id() == room->connection()->userId()) continue; const QUrl avatar = member.avatarUrl(); if (avatar.scheme() == QLatin1String("mxc")) return room->connection()->makeMediaUrl(avatar).toString(); } } const QUrl avatar = room->avatarUrl(); if (avatar.scheme() == QLatin1String("mxc")) return room->connection()->makeMediaUrl(avatar).toString(); return QString(); } // Classify member events using the same distinctions as NeoChat. inline StateChange classifyMember(const Room *room, const RoomMemberEvent &event, QString &subject) { const bool aboutSomeoneElse = event.senderId() != event.userId(); switch (event.membership()) { case Membership::Invite: subject = memberLabel(room, event.userId()); return StateChange::Invited; case Membership::Join: { if (event.changesMembership()) return StateChange::Joined; // already joined, so a profile change not an arrival. names before // pictures: a picture change alone is the duller half, no line of its own. if (event.isRename()) { if (!event.newDisplayName()) return StateChange::DisplayNameCleared; if (!event.prevContent() || !event.prevContent()->displayName) return StateChange::DisplayNameSet; subject = *event.prevContent()->displayName; return StateChange::DisplayNameChanged; } if (event.isAvatarUpdate()) return StateChange::MemberAvatarChanged; // a join event that changed nothing - a sync artefact, dropped. return StateChange::None; } case Membership::Leave: subject = memberLabel(room, event.userId()); if (event.prevContent() && event.prevContent()->membership == Membership::Invite) return aboutSomeoneElse ? StateChange::InviteWithdrawn : StateChange::InviteRejected; if (event.prevContent() && event.prevContent()->membership == Membership::Ban) return aboutSomeoneElse ? StateChange::Unbanned : StateChange::SelfUnbanned; return aboutSomeoneElse ? StateChange::Kicked : StateChange::Left; case Membership::Ban: subject = memberLabel(room, event.userId()); return aboutSomeoneElse ? StateChange::Banned : StateChange::SelfBanned; case Membership::Knock: return StateChange::KnockRequested; default: break; } return StateChange::Unknown; } inline StateChange classifyState(const Room *room, const RoomEvent *event, QString &subject) { if (!event->isStateEvent()) return StateChange::None; // a state event that just repeats the room state is a sync artefact. // checked first, or every branch prints a duplicate line after reconnect. if (const auto *state = eventCast(event); state && state->repeatsState()) return StateChange::None; if (const auto *member = eventCast(event)) return classifyMember(room, *member, subject); if (const auto *name = eventCast(event)) { subject = name->name(); return subject.isEmpty() ? StateChange::RoomNameCleared : StateChange::RoomNameSet; } if (const auto *topic = eventCast(event)) { // flattened: the topic gets one timeline line, not one per paragraph. subject = topic->topic().simplified(); return subject.isEmpty() ? StateChange::TopicCleared : StateChange::TopicSet; } if (const auto *alias = eventCast(event)) { subject = alias->alias(); return subject.isEmpty() ? StateChange::AliasCleared : StateChange::AliasSet; } if (is(*event)) return StateChange::RoomAvatarChanged; if (is(*event)) return StateChange::EncryptionEnabled; if (const auto *create = eventCast(event)) return create->isUpgrade() ? StateChange::RoomUpgraded : StateChange::RoomCreated; if (is(*event)) return StateChange::PowerLevelsChanged; // some other state event: a widget, a server ACL, a call member. Named as // unknown rather than skipped, so the timeline never has a silent gap. return StateChange::Unknown; } inline void fillMedia(const Room *room, const RoomMessageEvent &message, koutnet::matrix::RawEvent &raw) { // read the raw JSON, not the typed accessors. get() is a template // libQuotient instantiates for a fixed content-type list, and a build whose // library list disagrees with its headers links nothing. the JSON fields // are the spec and read the same everywhere. const QJsonObject content = message.contentJson(); const QJsonObject info = content.value(QStringLiteral("info")).toObject(); raw.mediaName = content.value(QStringLiteral("body")).toString(); raw.mediaMime = info.value(QStringLiteral("mimetype")).toString(); raw.mediaSize = info.value(QStringLiteral("size")).toInteger(); // the dimensions matter: without them a picture is laid out at whatever the // decoder reports after the download, shifting the timeline under the reader. raw.mediaWidth = info.value(QStringLiteral("w")).toInt(); raw.mediaHeight = info.value(QStringLiteral("h")).toInt(); raw.mediaDurationMs = info.value(QStringLiteral("duration")).toInt(); // an encrypted attachment keeps the url one level down, under file. const QJsonObject file = content.value(QStringLiteral("file")).toObject(); const QUrl source(file.isEmpty() ? content.value(QStringLiteral("url")).toString() : file.value(QStringLiteral("url")).toString()); // Keep the original source for already-fetchable URLs. Matrix media is // normally mxc://, but imported events and some bridges provide https:// // URLs; dropping those made otherwise valid images look like attachments // with no media at all. if (source.scheme() == QLatin1String("mxc") && room != nullptr && room->connection() != nullptr) { raw.mediaUrl = room->makeMediaUrl(message.id(), source).toString(); // A scaled copy of the same picture, for the timeline to draw from: a chat // photograph is several times what a row is wide, and the timeline asks // for one per row it scrolls past. // // Not asked of an encrypted room: the server cannot read those files // and so cannot scale them. if (!room->usesEncryption()) raw.thumbnailUrl = room->urlToThumbnail(message.id()).toString(); } else if (source.isValid() && (source.scheme() == QLatin1String("http") || source.scheme() == QLatin1String("https"))) { raw.mediaUrl = source.toString(); } } // A poll arrives under several event types and content shapes; detect by // content so every client's poll renders instead of falling through to text. inline QVariantMap pollFromContent(const QJsonObject &content) { QString pollKey; if (content.contains(QStringLiteral("org.matrix.msc3381.poll.start"))) pollKey = QStringLiteral("org.matrix.msc3381.poll.start"); else if (content.contains(QStringLiteral("poll"))) pollKey = QStringLiteral("poll"); else return {}; const QJsonObject poll = content.value(pollKey).toObject(); const QString textKey = QStringLiteral("org.matrix.msc1767.text"); QString question = poll.value(QStringLiteral("question")).toObject().value(textKey).toString(); if (question.isEmpty()) question = poll.value(QStringLiteral("question")).toObject().value(QStringLiteral("body")).toString(); if (question.isEmpty()) question = content.value(textKey).toString(); if (question.isEmpty()) question = content.value(QStringLiteral("body")).toString(); QVariantList answers; const QJsonArray answersJson = poll.value(QStringLiteral("answers")).toArray(); for (const QJsonValue &answer : answersJson) { const QJsonObject answerObj = answer.toObject(); QString body = answerObj.value(textKey).toString(); if (body.isEmpty()) body = answerObj.value(QStringLiteral("body")).toString(); QVariantMap entry; entry.insert(QStringLiteral("id"), answerObj.value(QStringLiteral("id")).toString()); entry.insert(QStringLiteral("body"), body); answers.append(entry); } const QString kind = poll.value(QStringLiteral("kind")).toString(); const bool disclosed = kind == QStringLiteral("disclosed") || kind == QStringLiteral("org.matrix.msc3381.poll.disclosed"); QVariantMap out; out.insert(QStringLiteral("question"), question); out.insert(QStringLiteral("answers"), answers); out.insert(QStringLiteral("disclosed"), disclosed); return out; } inline QString formattedBodyOf(const QJsonObject &content) { if (content.value(QStringLiteral("format")).toString() != QStringLiteral("org.matrix.custom.html")) return {}; const QString html = content.value(QStringLiteral("formatted_body")).toString(); return html.isEmpty() ? QString() : TextHandler::sanitizeFormattedBody(html); } inline koutnet::matrix::RawEvent flatten(const Room *room, const RoomEvent *event) { koutnet::matrix::RawEvent raw; raw.eventId = event->id(); raw.senderId = event->senderId(); raw.senderName = room->member(event->senderId()).displayName(); raw.originTimestampMs = event->originTimestamp().toMSecsSinceEpoch(); raw.isOwn = !raw.senderId.isEmpty() && room->connection() != nullptr && raw.senderId == room->connection()->userId(); raw.redacted = event->isRedacted(); raw.state = classifyState(room, event, raw.stateSubject); if (raw.state != StateChange::None) return raw; // a state event classified as None has nothing to show; cleared so it is // not drawn as an empty message. if (event->isStateEvent()) { raw.eventId.clear(); return raw; } // Registered poll classes let libQuotient parse the unstable poll events // without guessing at their wire format. if (const auto *poll = eventCast(event)) { QVariantList answers; const auto pollAnswers = poll->answers(); for (const auto &a : pollAnswers) { QVariantMap e; e.insert(QStringLiteral("id"), a.id); e.insert(QStringLiteral("body"), a.text); answers.append(e); } QVariantMap pollMap; pollMap.insert(QStringLiteral("question"), poll->question()); pollMap.insert(QStringLiteral("answers"), answers); pollMap.insert(QStringLiteral("disclosed"), poll->kind() == PollKind::Disclosed); raw.poll = pollMap; raw.body = poll->question(); return raw; } if (const auto *vote = eventCast(event)) { const std::optional rel = vote->relatesTo(); raw.pollStartId = rel ? rel->eventId : QString(); const QStringList selections = vote->selections(); raw.pollAnswerId = selections.isEmpty() ? QString() : selections.first(); return raw; } if (const auto *message = eventCast(event)) { // Read the msgtype from the raw content: the typed MsgType enum does not // have every unstable kind (m.sticker, m.location), and a library whose // message list disagrees with its headers would link nothing. const QJsonObject content = message->contentJson(); const QString msgtype = content.value(QStringLiteral("msgtype")).toString(); raw.formattedBody = formattedBodyOf(content); raw.textLike = msgtype == QStringLiteral("m.text") || msgtype == QStringLiteral("m.notice") || msgtype == QStringLiteral("m.emote"); // A poll may arrive under several msgtypes/event types; detect it by its // content so the voting UI renders instead of a bare question line. const QVariantMap pollData = pollFromContent(content); if (!pollData.isEmpty()) { raw.poll = pollData; raw.body = pollData.value(QStringLiteral("question")).toString(); return raw; } if (msgtype == QStringLiteral("m.location")) { // A geo: point is opened as a map, not downloaded; keep the uri as // the body so the row shows where it points, and as the media url so // the attachment block can hand it straight to a map application. raw.media = MediaKind::Location; raw.body = content.value(QStringLiteral("geo_uri")).toString(); if (raw.body.isEmpty()) raw.body = message->plainBody(); raw.mediaUrl = raw.body; raw.mediaName = content.value(QStringLiteral("body")).toString(); } else if (msgtype == QStringLiteral("m.sticker")) { // A sticker is an image with a different msgtype; render it as one. raw.media = MediaKind::Image; if (!raw.redacted) fillMedia(room, *message, raw); } else if (msgtype == QStringLiteral("org.matrix.msc3381.poll.response")) { const QJsonObject relates = content.value(QStringLiteral("m.relates_to")).toObject(); raw.pollStartId = relates.value(QStringLiteral("event_id")).toString(); const QJsonArray answers = content.value(QStringLiteral("org.matrix.msc3381.poll.response")).toObject().value(QStringLiteral("answers")).toArray(); if (!answers.isEmpty()) raw.pollAnswerId = answers.at(0).isObject() ? answers.at(0).toObject().value(QStringLiteral("id")).toString() : answers.at(0).toString(); } else { raw.body = message->plainBody(); raw.media = mediaKindOf(message->msgtype()); if (raw.media != MediaKind::None && !raw.redacted) fillMedia(room, *message, raw); } // MSC2446 spoiler: the hidden text rides in a "spoiler" array or as a // in the formatted body; the window hides it. if (msgtype == QStringLiteral("m.text") && (content.value(QStringLiteral("spoiler")).isArray() || raw.formattedBody.contains(QLatin1String("data-mx-spoiler")))) { raw.spoiler = true; // Wrap in || so the shared TextHandler hides it the same way a LAN // writer's ||secret|| does; revealed, the inner text is what shows. raw.body = QStringLiteral("||%1||").arg(raw.body); } } else if (is(*event)) { raw.encrypted = true; } else { // a reaction, a redaction event, or a call signal: not a row. raw.eventId.clear(); } return raw; } // the "* text" fallback for clients that do not understand edits. inline QString replacementBody(const RoomMessageEvent &message) { const QJsonObject newContent = message.contentJson().value(QLatin1String("m.new_content")).toObject(); const QString body = newContent.value(QLatin1String("body")).toString(); return body.isEmpty() ? message.plainBody() : body; } inline QString replacementFormattedBody(const RoomMessageEvent &message) { const QJsonObject newContent = message.contentJson().value(QLatin1String("m.new_content")).toObject(); return formattedBodyOf(newContent); } inline QString mediaCacheDir() { const QString dir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/media"); QDir().mkpath(dir); return dir; } inline QString mediaFilePrefix(Room *room, const QString &eventId) { // The room is in the name because an event id is only unique inside one room. const QString safeRoom = QString::fromLatin1(room->id().toUtf8().toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)); return safeRoom + QLatin1Char('-') + eventId + QLatin1Char('-'); } inline QString mediaFilePrefixForAddress(const QString &mediaUrl) { // A media id is unique on its homeserver, so the address alone is the name: // there is no room and no event to make it out of, because a forwarded // attachment is fetched without either of them. const QString safe = QString::fromLatin1(mediaUrl.toUtf8().toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)); return safe.left(80) + QLatin1Char('-'); } inline qint64 fileSizeOf(const RoomMessageEvent *message) { if (auto file = message->get()) return file->commonInfo().payloadSize; if (auto image = message->get()) return image->commonInfo().payloadSize; if (auto video = message->get()) return video->commonInfo().payloadSize; if (auto audio = message->get()) return audio->commonInfo().payloadSize; return 0; } inline QVariantMap rowForEvent(const RoomEvent *ev) { QVariantMap m; m.insert(QStringLiteral("eventId"), ev->id()); m.insert(QStringLiteral("ts"), ev->originTimestamp().toMSecsSinceEpoch() / 1000.0); m.insert(QStringLiteral("sender"), ev->senderId()); if (const auto *me = eventCast(ev)) m.insert(QStringLiteral("text"), me->plainBody()); return m; } inline QString markdownToHtml(const QString &markdown) { QTextDocument doc; doc.setMarkdown(markdown); QString html = doc.toHtml(); const int bodyOpen = html.indexOf(QLatin1String("")); if (bodyOpen >= 0 && bodyClose > bodyOpen) { const int tagEnd = html.indexOf(QLatin1String(">"), bodyOpen); html = html.mid(tagEnd + 1, bodyClose - tagEnd - 1); } return html.trimmed(); } inline bool looksFormatted(const QString &text) { return text.contains(QLatin1String("**")) || text.contains(QLatin1String("__")) || text.contains(QLatin1String("`")) || text.contains(QLatin1String("~~")) || text.contains(QLatin1String("# ")) || text.contains(QLatin1String("\n")); } } // namespace } // namespace koutnet