// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "MediaCache.h" #include #include #include #include #include #include #include #include #include #include #include MediaCache::MediaCache(QObject *parent) : QObject(parent) { QDir().mkpath(cacheDir()); remeasure(); } MediaCache *MediaCache::create(QQmlEngine *, QJSEngine *) { return new MediaCache; } QString MediaCache::cacheDir() { return QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/urls"); } QString MediaCache::fileNameFor(const QUrl &url) { // The name the url carries, so a person looking in a file manager sees what // the picture is; the digest in front of it, so two urls whose names agree // are not one file. The extension is left off: what is inside decides how // it is decoded, and a name that lies about it would be worse than none. const QString urlName = url.fileName(); const QString digest = QString::fromLatin1(QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Sha1).toHex().left(24)); return urlName.isEmpty() ? digest : digest + QLatin1Char('-') + urlName; } QString MediaCache::localPathFor(const QUrl &url) const { if (!url.isValid() || url.scheme().isEmpty()) return {}; const QFileInfo info(QDir(cacheDir()).absoluteFilePath(fileNameFor(url))); return info.isFile() && info.size() > 0 ? info.absoluteFilePath() : QString(); } void MediaCache::fetch(const QUrl &url) { if (!url.isValid() || url.scheme().isEmpty()) return; if (!localPathFor(url).isEmpty()) return; // the whole point: already on this disk, ask the server for nothing const QString key = url.toString(QUrl::FullyEncoded); if (m_inFlight.contains(key)) return; // a hundred rows of one avatar are still one download // The manager the library installed for QML, which is the one that knows an // mxc:// url is a request to the homeserver with this session's token on it. // The QML engine asks that factory for the manager it loads images through, // so going through it is not a second way of fetching the same thing. QNetworkRequest request(url); request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); QNetworkReply *reply = Quotient::NetworkAccessManager::instance()->get(request); if (!reply) { return; } m_inFlight.insert(key, reply); connect(reply, &QNetworkReply::finished, this, [this, url, reply]() { reply->deleteLater(); m_inFlight.remove(url.toString(QUrl::FullyEncoded)); // A file is only a file if it is complete: a picture written half way // is a broken picture that the next row would find on disk and believe. if (reply->error() != QNetworkReply::NoError || !reply->isFinished()) return; const QByteArray bytes = reply->readAll(); if (bytes.isEmpty()) return; const QString path = QDir(cacheDir()).absoluteFilePath(fileNameFor(url)); // Written through a temporary and renamed, so an interrupted write // leaves nothing behind that a later read would take for a picture. QSaveFile file(path); if (!file.open(QIODevice::WriteOnly) || file.write(bytes) < 0 || !file.commit()) return; remeasure(); trimToLimit(); }); } void MediaCache::setLimitMb(int mb) { const int capped = std::max(0, mb); if (capped == m_limitMb) return; m_limitMb = capped; trimToLimit(); } void MediaCache::trimToLimit() { if (m_limitMb <= 0 || m_diskUsage <= static_cast(m_limitMb) * 1024 * 1024) return; QDir dir(cacheDir()); QList files; for (const QString &name : dir.entryList(QDir::Files | QDir::NoDotAndDotDot)) files.append(QFileInfo(dir.absoluteFilePath(name))); std::sort(files.begin(), files.end(), [](const QFileInfo &a, const QFileInfo &b) { return a.lastModified() < b.lastModified(); }); const qulonglong limit = static_cast(m_limitMb) * 1024 * 1024; for (const QFileInfo &info : files) { if (m_diskUsage <= limit) break; if (!dir.remove(info.fileName())) continue; const qulonglong size = static_cast(info.size()); m_diskUsage = m_diskUsage > size ? m_diskUsage - size : 0; } Q_EMIT diskUsageChanged(); } void MediaCache::clear() { QDir dir(cacheDir()); for (const QString &name : dir.entryList(QDir::Files | QDir::NoDotAndDotDot)) dir.remove(name); remeasure(); } QVariantList MediaCache::files() const { QDir dir(cacheDir()); QVariantList out; QDateTime newest; QFileInfo newestFile; for (const QString &name : dir.entryList(QDir::Files | QDir::NoDotAndDotDot)) { const QFileInfo info(dir.absoluteFilePath(name)); const QDateTime written = info.lastModified(); // Newest first, and a stable order among files written in the same // second - which a burst of thumbnails very well is. if (written > newest || (written == newest && info.fileName() < newestFile.fileName())) { newest = written; newestFile = info; } out << QVariantMap{{QStringLiteral("name"), name}, {QStringLiteral("size"), info.size()}}; } std::sort(out.begin(), out.end(), [&dir](const QVariant &a, const QVariant &b) { const QFileInfo ai(dir.absoluteFilePath(a.toMap().value(QStringLiteral("name")).toString())); const QFileInfo bi(dir.absoluteFilePath(b.toMap().value(QStringLiteral("name")).toString())); if (ai.lastModified() != bi.lastModified()) return ai.lastModified() > bi.lastModified(); return ai.fileName() < bi.fileName(); }); return out; } void MediaCache::remeasure() { qulonglong total = 0; QDir dir(cacheDir()); for (const QString &name : dir.entryList(QDir::Files | QDir::NoDotAndDotDot)) total += QFileInfo(dir.absoluteFilePath(name)).size(); if (total == m_diskUsage) return; m_diskUsage = total; Q_EMIT diskUsageChanged(); }