// 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/constructor/AppSettings.h" #include "core/media/OutgoingFile.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Quotient; namespace koutnet { // KOutNet - attachments, stickers, voice notes, location and sticker files: the half // of the bridge that moves bytes, and the polling that turns a finished download // into a row. QString MatrixRoomBridge::finishedMediaFile(const MediaWatch &watch) const { const QDir dir(mediaCacheDir()); const QStringList matches = dir.entryList({watch.filePrefix + QLatin1Char('*')}, QDir::Files, QDir::Name); for (const QString &name : matches) { const QFileInfo info(dir.absoluteFilePath(name)); if (info.isFile() && info.size() > 0) return info.absoluteFilePath(); } return {}; } void MatrixRoomBridge::finishMediaDownload(const QString &eventId) { const auto it = m_mediaWatches.constFind(eventId); if (it == m_mediaWatches.cend()) return; const MediaWatch watch = it.value(); m_mediaWatches.remove(eventId); if (m_mediaWatches.isEmpty()) m_mediaWatch.stop(); // the poll that decided this one was whole already found the file; looking // for it again is a second pass over the cache directory for an answer that // is in hand. const QString file = watch.file.isEmpty() ? finishedMediaFile(watch) : watch.file; if (file.isEmpty()) return; Q_EMIT attachmentReady(watch.chatId, eventId, QUrl::fromLocalFile(file)); } void MatrixRoomBridge::failMediaDownload(const QString &eventId, const QString &reason) { const auto it = m_mediaWatches.constFind(eventId); if (it == m_mediaWatches.cend()) return; const MediaWatch watch = it.value(); // a transfer the library called refused is not the same thing as no file: a // half-written one left behind is the normal state of a download that was // cut short, and it is still what is on disk. if (!watch.file.isEmpty() || !finishedMediaFile(watch).isEmpty()) { finishMediaDownload(eventId); return; } m_mediaWatches.remove(eventId); if (m_mediaWatches.isEmpty()) m_mediaWatch.stop(); Q_EMIT attachmentFailed(watch.chatId, eventId, reason); } void MatrixRoomBridge::pollMediaDownloads() { const QStringList ids = m_mediaWatches.keys(); for (const QString &eventId : ids) { MediaWatch watch = m_mediaWatches.value(eventId); const QString file = finishedMediaFile(watch); // kept so that the two paths that end this watch do not each go looking watch.file = file; if (file.isEmpty()) { // A download that has not begun yet, or one that was refused. Nothing // is said about it either way, and the only thing that would end the // wait is a person asking again. if (watch.since.isValid() && watch.since.elapsed() > 45000) { m_mediaWatches.remove(eventId); Q_EMIT attachmentFailed(watch.chatId, eventId, i18nc("@info:status", "This attachment took too long to download.")); } continue; } // A file that is still the size it was a moment ago is a file that has // stopped growing. When the event says how big it should be, that is what // is waited for instead, and a file that arrives complete is not made to // wait out the samples that would prove it. const qint64 size = QFileInfo(file).size(); if (watch.expectedSize > 0 && size >= watch.expectedSize) { finishMediaDownload(eventId); continue; } if (size == watch.lastSize && size > 0 && ++watch.stillSamples >= 3) { finishMediaDownload(eventId); continue; } watch.lastSize = size; m_mediaWatches.insert(eventId, watch); } if (m_mediaWatches.isEmpty()) m_mediaWatch.stop(); } void MatrixRoomBridge::downloadAttachment(const QString &chatId, const QString &eventId, const QString &mediaUrl, const QString &fileName) { Room *room = roomFor(chatId); // A room is not needed to fetch media by its own address, and a forwarded // attachment has no event in this room at all: the message that quotes it // carries the media of an event in another room, or one this timeline no // longer holds. The address is enough, so it is the second way in. const bool byAddress = mediaUrl.startsWith(QLatin1String("mxc:")) || mediaUrl.startsWith(QLatin1String("http")); if (!room && !byAddress) { Q_EMIT attachmentFailed(chatId, eventId, i18nc("@info:status", "The room is not available.")); return; } if (room) { // The event has to be in the timeline this session holds, because that is // where the file content is read from. historyEdge() is what comes back // for an event this timeline does not have, so it is the not-found answer // rather than an event to look inside. const auto event = room->findInTimeline(eventId); if (event != room->historyEdge() && eventCast(event->event())) { const RoomMessageEvent *message = eventCast(event->event()); // An m.image whose body names an https address has no file block in // it, and downloadFile() returns without a word for one - no error, // no job. Said out loud instead: an empty reason means there is // nothing to download and the address is the only way to see it. if (message->has()) return downloadEventMedia(room, chatId, eventId, message); if (!byAddress) { Q_EMIT attachmentFailed(chatId, eventId, QString()); return; } } else if (!byAddress) { Q_EMIT attachmentFailed(chatId, eventId, i18nc("@info:status", "This message is not in the loaded history.")); return; } } downloadMediaByUrl(chatId, eventId, mediaUrl, fileName); } // The ordinary case: the event is here, and the room knows how to fetch it with // the session's own credentials. void MatrixRoomBridge::downloadEventMedia(Room *room, const QString &chatId, const QString &eventId, const RoomMessageEvent *message) { MediaWatch watch; watch.chatId = chatId; watch.filePrefix = mediaFilePrefix(room, eventId); watch.expectedSize = fileSizeOf(message); // A file already under that name answers at once, which is what the second // and every later pass over a row of pictures costs. const QString already = finishedMediaFile(watch); if (!already.isEmpty() && (watch.expectedSize <= 0 || QFileInfo(already).size() >= watch.expectedSize)) { Q_EMIT attachmentReady(chatId, eventId, QUrl::fromLocalFile(already)); return; } // Asked for every time: with a file that is already there the library // answers with fileTransferCompleted and nothing else, and a transfer this // program never hears the end of is a picture that never appears. So the // file is watched as well. if (!m_mediaWatches.contains(eventId)) { watch.since.start(); m_mediaWatches.insert(eventId, watch); m_mediaWatch.start(); } QString name = room->fileNameToDownload(eventId); name.replace(QRegularExpression(QStringLiteral("[^A-Za-z0-9._ -]")), QStringLiteral("_")); if (name.isEmpty()) name = QStringLiteral("attachment"); if (name.size() > 80) name.truncate(80); room->downloadFile(eventId, QUrl::fromLocalFile(mediaCacheDir() + QLatin1Char('/') + watch.filePrefix + name)); } // The forwarded case: nothing of the event is here, so the media is fetched by // its own address. The session's credentials go with it, which is the part that // matters - a homeserver does not serve its own media to an anonymous GET. void MatrixRoomBridge::downloadMediaByUrl(const QString &chatId, const QString &eventId, const QString &mediaUrl, const QString &fileName) { if (mediaUrl.isEmpty() || !m_manager || !m_manager->connection()) { Q_EMIT attachmentFailed(chatId, eventId, i18nc("@info:status", "That attachment cannot be fetched from here.")); return; } MediaWatch watch; watch.chatId = chatId; watch.filePrefix = mediaFilePrefixForAddress(mediaUrl); // The size is in the event that is not here, so the watch waits for the file // to stop growing rather than for a length nobody can check it against. watch.expectedSize = 0; const QString already = finishedMediaFile(watch); if (!already.isEmpty()) { Q_EMIT attachmentReady(chatId, eventId, QUrl::fromLocalFile(already)); return; } if (!m_mediaWatches.contains(eventId)) { watch.since.start(); m_mediaWatches.insert(eventId, watch); m_mediaWatch.start(); } QString name = fileName; if (name.isEmpty()) name = QFileInfo(QUrl(mediaUrl).path()).fileName(); name.replace(QRegularExpression(QStringLiteral("[^A-Za-z0-9._ -]")), QStringLiteral("_")); if (name.isEmpty()) name = QStringLiteral("attachment"); if (name.size() > 80) name.truncate(80); const QString target = mediaCacheDir() + QLatin1Char('/') + watch.filePrefix + name; DownloadFileJob *job = m_manager->connection()->downloadFile(QUrl(mediaUrl), target); if (!job) { failMediaDownload(eventId, i18nc("@info:status", "That attachment cannot be fetched from here.")); return; } // The file watcher below is what turns a finished download into a row, but it // cannot tell a transfer that was refused from one that has not started, so // the refusal is taken from the job itself and said at once. connect(job, &BaseJob::finished, this, [this, eventId](BaseJob *finished) { // A refusal, said at once rather than waited out: the file watcher cannot // tell a transfer that was refused from one that has not started, and a // row that spins for the best part of a minute is worse than a row that // says why it cannot be fetched. if (finished->error() != Quotient::BaseJob::NoError) failMediaDownload(eventId, finished->errorString()); }); } bool MatrixRoomBridge::sendFile(const QString &chatId, const QString &localFilePath) { 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; } const QFileInfo original(localFilePath); if (!original.exists() || !original.isReadable()) { Q_EMIT sendFailed(chatId, i18nc("@info:status %1 is a file name", "%1 could not be read, so nothing was sent.", original.fileName())); return false; } // A photograph is scaled and re-encoded before it is uploaded, and what goes // out is the smaller file: every reader would otherwise download the whole // original to look at a thumbnail. A recording or a document is sent as it // is - there is no encoder here - and so is a picture that came out bigger. const OutgoingFile::Prepared prepared = OutgoingFile::prepare(localFilePath); const QFileInfo file(prepared.path); // Checked on what goes out rather than on what was picked: a photograph is // scaled below, so a five-megabyte file can be a hundred kilobytes. Said // before the upload, because an upload that will be refused has already // spent the reader's time. const AppSettings *settings = m_manager != nullptr ? m_manager->settings() : nullptr; const qint64 limitBytes = static_cast(settings != nullptr ? settings->maxAttachmentSizeMb() : 0) * 1024 * 1024; if (limitBytes > 0 && file.size() > limitBytes) { Q_EMIT sendFailed(chatId, i18nc("@info:status a file was too large to send, %1 is how large it is", "%1 is larger than the %2 MB limit.", QLocale().formattedDataSize(file.size()), settings->maxAttachmentSizeMb())); return false; } const QUrl localUrl = QUrl::fromLocalFile(file.absoluteFilePath()); const QMimeType mime = QMimeDatabase().mimeTypeForFile(file); const QString mimeName = mime.name(); // the msgtype comes from the content type, not the extension, since that is // what every other client reads it back as. no poster frame for a video: // making one means decoding a frame and uploading it as a second media, and // a video with no poster still plays. std::unique_ptr content; if (mimeName.startsWith(QLatin1String("image/"))) { const QImage image(file.absoluteFilePath()); content = std::make_unique(localUrl, file.size(), mime, image.size(), file.fileName()); } else if (mimeName.startsWith(QLatin1String("audio/"))) { auto audio = std::make_unique(localUrl, file.size(), mime, file.fileName()); // set by hand: the duration member belongs to the libQuotient playable // content and only its JSON constructor fills it, so a local-file one // starts holding whatever was on the stack and that goes out in the event. audio->duration = 0; content = std::move(audio); } else if (mimeName.startsWith(QLatin1String("video/"))) { auto video = std::make_unique(localUrl, file.size(), mime, QSize(), file.fileName()); video->duration = 0; content = std::move(video); } else { content = std::make_unique(localUrl, file.size(), mime, file.fileName()); } // Named as it will be received: a photograph that was re-encoded is no // longer the file the person picked, and a name saying "photo.jpeg" on a // webp body is a name some client will open and find nothing in. // The transaction id is kept: an upload that dies before the server ever // sees the event reports itself by this id, and the bridge turns that into // the sendFailed a silent discard would never say. const QString txnId = room->postFile(prepared.name, std::move(content)); if (!txnId.isEmpty()) m_uploadTxns.insert(txnId); return true; } void MatrixRoomBridge::sendLocation(const QString &chatId, double latitude, double longitude, const QString &label) { Room *room = roomFor(chatId); if (room == nullptr) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return; } if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return; } // geo: takes lat,lon; the label is what shows before the map opens. const QString geo = QStringLiteral("geo:%1,%2").arg(latitude, 0, 'f', 6).arg(longitude, 0, 'f', 6); QJsonObject content; content.insert(QStringLiteral("msgtype"), QStringLiteral("m.location")); content.insert(QStringLiteral("geo_uri"), geo); content.insert(QStringLiteral("body"), label.isEmpty() ? geo : label); room->postJson(QStringLiteral("m.room.message"), content); } void MatrixRoomBridge::sendSticker(const QString &chatId, const QString &mxcUrl, const QString &description) { Room *room = roomFor(chatId); if (room == nullptr) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return; } if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return; } QJsonObject content; content.insert(QStringLiteral("msgtype"), QStringLiteral("m.sticker")); content.insert(QStringLiteral("url"), mxcUrl); content.insert(QStringLiteral("body"), description.isEmpty() ? i18nc("@item a sticker with no caption", "sticker") : description); room->postJson(QStringLiteral("m.room.message"), content); } void MatrixRoomBridge::sendSpoiler(const QString &chatId, const QString &text) { if (text.trimmed().isEmpty()) return; Room *room = roomFor(chatId); if (room == nullptr) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return; } if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return; } // MSC2446: the hidden text rides in a in the html // body, while the plain body stays readable for clients that ignore it. const QString escaped = text.toHtmlEscaped(); const QString html = QStringLiteral("%1").arg(escaped); QJsonObject content; content.insert(QStringLiteral("msgtype"), QStringLiteral("m.text")); content.insert(QStringLiteral("format"), QStringLiteral("org.matrix.custom.html")); content.insert(QStringLiteral("formatted_body"), html); content.insert(QStringLiteral("body"), text); room->postJson(QStringLiteral("m.room.message"), content); } void MatrixRoomBridge::sendStickerFile(const QString &chatId, const QString &localFilePath) { Room *room = roomFor(chatId); if (room == nullptr || room->connection() == nullptr) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return; } if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return; } // the composer hands over a file:// URL straight from a dialog or the // recorder; QFileInfo will not stat that, so turn it into a local path first. const QString path = localFilePath.startsWith(QStringLiteral("file://")) ? QUrl(localFilePath).toLocalFile() : localFilePath; const QFileInfo original(path); if (!original.exists() || !original.isReadable()) { Q_EMIT sendFailed(chatId, i18nc("@info:status %1 is a file name", "%1 could not be read, so nothing was sent.", original.fileName())); return; } // A sticker is a picture, and a photograph-sized one is a great deal larger // than the sticker it becomes, so it goes out shrunk. The body is named // after the smaller file so the name and the format agree. const OutgoingFile::Prepared prepared = OutgoingFile::prepare(path); const QFileInfo file(prepared.path); const QString mimeName = QMimeDatabase().mimeTypeForFile(file).name(); // No content type passed: uploadContent() only opens the source device when // it has to sniff the type, and a still-closed QFile makes BaseJob abort // with "Request data not ready". The name-based detection below yields the // same type anyway. auto job = room->connection()->uploadFile(file.absoluteFilePath()); connect(job.operator->(), &Quotient::BaseJob::success, this, [this, chatId, file, mimeName, prepared, job]() { Room *room = roomFor(chatId); if (!room) return; QJsonObject content; content.insert(QStringLiteral("msgtype"), QStringLiteral("m.sticker")); content.insert(QStringLiteral("url"), job->contentUri().toString()); content.insert(QStringLiteral("body"), prepared.name); QJsonObject info; info.insert(QStringLiteral("mimetype"), mimeName); info.insert(QStringLiteral("size"), file.size()); content.insert(QStringLiteral("info"), info); room->postJson(QStringLiteral("m.room.message"), content); }); connect(job.operator->(), &Quotient::BaseJob::failure, this, [this, chatId, job]() { Q_EMIT sendFailed(chatId, job->errorString()); }); } void MatrixRoomBridge::sendVoice(const QString &chatId, const QString &localFilePath, int durationMs) { Room *room = roomFor(chatId); if (room == nullptr || room->connection() == nullptr) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "That Matrix room is not available in this session.")); return; } if (!canSendEncrypted(room)) { Q_EMIT sendFailed(chatId, encryptionUnavailableReason()); return; } const QString path = localFilePath.startsWith(QStringLiteral("file://")) ? QUrl(localFilePath).toLocalFile() : localFilePath; const QFileInfo file(path); if (!file.exists() || !file.isReadable()) { Q_EMIT sendFailed(chatId, i18nc("@info:status %1 is a file name", "%1 could not be read, so nothing was sent.", file.fileName())); return; } const QString ext = file.suffix().toLower(); QString mimeName = QStringLiteral("audio/ogg"); if (ext == QStringLiteral("m4a") || ext == QStringLiteral("mp4")) mimeName = QStringLiteral("audio/mp4"); else if (ext == QStringLiteral("aac")) mimeName = QStringLiteral("audio/aac"); else if (ext == QStringLiteral("ogg")) mimeName = QStringLiteral("audio/ogg"); else if (ext == QStringLiteral("wav")) mimeName = QStringLiteral("audio/wav"); else if (ext == QStringLiteral("flac")) mimeName = QStringLiteral("audio/flac"); else if (ext == QStringLiteral("mp3")) mimeName = QStringLiteral("audio/mpeg"); // See the sticker/avatar uploads above: no content type, so the file gets // opened for reading and the type is detected from the file name. auto job = room->connection()->uploadFile(file.absoluteFilePath()); connect(job.operator->(), &Quotient::BaseJob::success, this, [this, chatId, file, mimeName, durationMs, job]() { Room *room = roomFor(chatId); if (!room) return; const QString url = job->contentUri().toString(); QJsonObject content; content.insert(QStringLiteral("msgtype"), QStringLiteral("m.audio")); content.insert(QStringLiteral("body"), QStringLiteral("Voice message")); content.insert(QStringLiteral("url"), url); QJsonObject fileInfo; fileInfo.insert(QStringLiteral("mimetype"), mimeName); fileInfo.insert(QStringLiteral("name"), QStringLiteral("Voice Message")); fileInfo.insert(QStringLiteral("size"), file.size()); fileInfo.insert(QStringLiteral("url"), url); content.insert(QStringLiteral("org.matrix.msc1767.file"), fileInfo); QJsonObject info; info.insert(QStringLiteral("mimetype"), mimeName); info.insert(QStringLiteral("size"), file.size()); info.insert(QStringLiteral("duration"), durationMs); content.insert(QStringLiteral("info"), info); QJsonObject audio; audio.insert(QStringLiteral("duration"), durationMs); audio.insert(QStringLiteral("waveform"), QJsonArray()); content.insert(QStringLiteral("org.matrix.msc1767.audio"), audio); content.insert(QStringLiteral("org.matrix.msc3245.voice"), QJsonObject()); room->postJson(QStringLiteral("m.room.message"), content); }); connect(job.operator->(), &Quotient::BaseJob::failure, this, [this, chatId, job]() { Q_EMIT sendFailed(chatId, job->errorString()); }); } } // namespace koutnet