| 1 |
// SPDX-FileCopyrightText: Nheko Contributors |
| 2 |
// |
| 3 |
// SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
#include "MxcImageProvider.h" |
| 6 |
|
| 7 |
#include <optional> |
| 8 |
|
| 9 |
#include <mtx/common.hpp> |
| 10 |
#include <mtxclient/crypto/client.hpp> |
| 11 |
|
| 12 |
#include <QByteArray> |
| 13 |
#include <QCache> |
| 14 |
#include <QDir> |
| 15 |
#include <QFileInfo> |
| 16 |
#include <QPainter> |
| 17 |
#include <QPainterPath> |
| 18 |
#include <QStandardPaths> |
| 19 |
#include <QThreadPool> |
| 20 |
#include <QTimer> |
| 21 |
|
| 22 |
#include "Logging.h" |
| 23 |
#include "MatrixClient.h" |
| 24 |
#include "Utils.h" |
| 25 |
|
| 26 |
QHash<QString, mtx::crypto::EncryptedFile> infos; |
| 27 |
|
| 28 |
MxcImageProvider::MxcImageProvider() |
| 29 |
: QQuickAsyncImageProvider() |
| 30 |
{ |
| 31 |
auto timer = new QTimer(this); |
| 32 |
timer->setInterval(std::chrono::hours(1)); |
| 33 |
connect(timer, &QTimer::timeout, this, [] { |
| 34 |
QThreadPool::globalInstance()->start([] { |
| 35 |
nhlog::net()->debug("Running media purge"); |
| 36 |
QDir dir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + |
| 37 |
"/media_cache", |
| 38 |
"", |
| 39 |
QDir::SortFlags(QDir::Name | QDir::IgnoreCase), |
| 40 |
QDir::Filter::Writable | QDir::Filter::NoDotAndDotDot | QDir::Filter::Files | |
| 41 |
QDir::Filter::Dirs); |
| 42 |
|
| 43 |
auto handleFile = [](const QFileInfo &fileInfo) { |
| 44 |
if (fileInfo.fileTime(QFile::FileTime::FileAccessTime) |
| 45 |
.daysTo(QDateTime::currentDateTime()) > 14) { |
| 46 |
if (QFile::remove(fileInfo.absoluteFilePath())) |
| 47 |
nhlog::net()->debug("Deleted stale media '{}'", |
| 48 |
fileInfo.absoluteFilePath().toStdString()); |
| 49 |
else |
| 50 |
nhlog::net()->warn("Failed to delete stale media '{}'", |
| 51 |
fileInfo.absoluteFilePath().toStdString()); |
| 52 |
} |
| 53 |
}; |
| 54 |
|
| 55 |
auto files = dir.entryInfoList(); |
| 56 |
for (const auto &fileInfo : std::as_const(files)) { |
| 57 |
if (fileInfo.isDir()) { |
| 58 |
// handle one level of legacy directories |
| 59 |
auto nestedDir = QDir(fileInfo.absoluteFilePath(), |
| 60 |
"", |
| 61 |
QDir::SortFlags(QDir::Name | QDir::IgnoreCase), |
| 62 |
QDir::Filter::Writable | QDir::Filter::NoDotAndDotDot | |
| 63 |
QDir::Filter::Files) |
| 64 |
.entryInfoList(); |
| 65 |
for (const auto &nestedFile : std::as_const(nestedDir)) { |
| 66 |
handleFile(nestedFile); |
| 67 |
} |
| 68 |
} else { |
| 69 |
handleFile(fileInfo); |
| 70 |
} |
| 71 |
} |
| 72 |
}); |
| 73 |
}); |
| 74 |
timer->start(); |
| 75 |
} |
| 76 |
|
| 77 |
QQuickImageResponse * |
| 78 |
MxcImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize) |
| 79 |
{ |
| 80 |
auto id_ = id; |
| 81 |
bool crop = true; |
| 82 |
double radius = 0; |
| 83 |
auto size = requestedSize; |
| 84 |
|
| 85 |
if (requestedSize.width() == 0 && requestedSize.height() == 0) |
| 86 |
size = QSize(); |
| 87 |
|
| 88 |
auto queryStart = id.lastIndexOf('?'); |
| 89 |
if (queryStart != -1) { |
| 90 |
id_ = id.left(queryStart); |
| 91 |
auto query = QStringView(id).mid(queryStart + 1); |
| 92 |
auto queryBits = query.split('&'); |
| 93 |
|
| 94 |
for (auto b : std::as_const(queryBits)) { |
| 95 |
if (b == QStringView(u"scale")) { |
| 96 |
crop = false; |
| 97 |
} else if (b.startsWith(QStringView(u"radius="))) { |
| 98 |
radius = b.mid(7).toDouble(); |
| 99 |
} else if (b.startsWith(u"height=")) { |
| 100 |
size.setHeight(b.mid(7).toInt()); |
| 101 |
size.setWidth(0); |
| 102 |
} |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
return new MxcImageResponse(id_, crop, radius, size); |
| 107 |
} |
| 108 |
|
| 109 |
void |
| 110 |
MxcImageProvider::addEncryptionInfo(const mtx::crypto::EncryptedFile &info) |
| 111 |
{ |
| 112 |
infos.insert(QString::fromStdString(info.url), info); |
| 113 |
} |
| 114 |
void |
| 115 |
MxcImageRunnable::run() |
| 116 |
{ |
| 117 |
MxcImageProvider::download( |
| 118 |
m_id, |
| 119 |
m_requestedSize, |
| 120 |
[this](QString id, QSize, QImage image, QString) { |
| 121 |
if (image.isNull()) { |
| 122 |
emit error(QStringLiteral("Failed to download image: %1").arg(id)); |
| 123 |
} else { |
| 124 |
emit done(image); |
| 125 |
} |
| 126 |
this->deleteLater(); |
| 127 |
}, |
| 128 |
m_crop, |
| 129 |
m_radius); |
| 130 |
} |
| 131 |
|
| 132 |
static QImage |
| 133 |
clipRadius(QImage img, double radius) |
| 134 |
{ |
| 135 |
QImage out(img.size(), QImage::Format_ARGB32_Premultiplied); |
| 136 |
out.fill(Qt::transparent); |
| 137 |
|
| 138 |
QPainter painter(&out); |
| 139 |
painter.setRenderHint(QPainter::Antialiasing, true); |
| 140 |
painter.setRenderHint(QPainter::SmoothPixmapTransform, true); |
| 141 |
|
| 142 |
QPainterPath ppath; |
| 143 |
ppath.addRoundedRect(img.rect(), radius, radius, Qt::SizeMode::RelativeSize); |
| 144 |
|
| 145 |
painter.setClipPath(ppath); |
| 146 |
painter.drawImage(img.rect(), img); |
| 147 |
|
| 148 |
return out; |
| 149 |
} |
| 150 |
|
| 151 |
static void |
| 152 |
possiblyUpdateAccessTime(const QFileInfo &fileInfo) |
| 153 |
{ |
| 154 |
if (fileInfo.fileTime(QFile::FileTime::FileAccessTime).daysTo(QDateTime::currentDateTime()) > |
| 155 |
7) { |
| 156 |
nhlog::net()->debug("Updating file time for '{}'", |
| 157 |
fileInfo.absoluteFilePath().toStdString()); |
| 158 |
|
| 159 |
QFile f(fileInfo.absoluteFilePath()); |
| 160 |
|
| 161 |
if (!f.open(QIODevice::ReadWrite) || |
| 162 |
!f.setFileTime(QDateTime::currentDateTime(), QFile::FileTime::FileAccessTime)) { |
| 163 |
nhlog::net()->warn("Failed to update filetime for '{}'", |
| 164 |
fileInfo.absoluteFilePath().toStdString()); |
| 165 |
} |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
void |
| 170 |
MxcImageProvider::download(const QString &id, |
| 171 |
const QSize &requestedSize, |
| 172 |
std::function<void(QString, QSize, QImage, QString)> then, |
| 173 |
bool crop, |
| 174 |
double radius) |
| 175 |
{ |
| 176 |
if (id.isEmpty()) { |
| 177 |
nhlog::net()->warn("Attempted to download image with empty ID"); |
| 178 |
then(id, QSize{}, QImage{}, QString{}); |
| 179 |
return; |
| 180 |
} |
| 181 |
|
| 182 |
bool cropLocally = false; |
| 183 |
if (crop && requestedSize.width() > 96) { |
| 184 |
crop = false; |
| 185 |
cropLocally = true; |
| 186 |
} |
| 187 |
|
| 188 |
std::optional<mtx::crypto::EncryptedFile> encryptionInfo; |
| 189 |
auto temp = infos.find("mxc://" + id); |
| 190 |
if (temp != infos.end()) |
| 191 |
encryptionInfo = *temp; |
| 192 |
|
| 193 |
if (requestedSize.isValid() && |
| 194 |
!encryptionInfo |
| 195 |
// Protect against synapse not following the spec: |
| 196 |
// https://github.com/matrix-org/synapse/issues/5302 |
| 197 |
&& requestedSize.height() <= 600 && requestedSize.width() <= 800) { |
| 198 |
QString fileName = QStringLiteral("%1_%2x%3_%4_radius%5") |
| 199 |
.arg(QString::fromUtf8(id.toUtf8().toBase64( |
| 200 |
QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals))) |
| 201 |
.arg(requestedSize.width()) |
| 202 |
.arg(requestedSize.height()) |
| 203 |
.arg(crop ? "crop" : "scale") |
| 204 |
.arg(radius); |
| 205 |
QFileInfo fileInfo(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + |
| 206 |
"/media_cache", |
| 207 |
fileName); |
| 208 |
QDir().mkpath(fileInfo.absolutePath()); |
| 209 |
|
| 210 |
if (fileInfo.exists()) { |
| 211 |
QImage image = utils::readImageFromFile(fileInfo.absoluteFilePath()); |
| 212 |
if (!image.isNull()) { |
| 213 |
possiblyUpdateAccessTime(fileInfo); |
| 214 |
|
| 215 |
if (requestedSize.width() <= 0) { |
| 216 |
image = image.scaledToHeight(requestedSize.height(), Qt::SmoothTransformation); |
| 217 |
} else { |
| 218 |
image = image.scaled(requestedSize, |
| 219 |
cropLocally ? Qt::KeepAspectRatioByExpanding |
| 220 |
: Qt::KeepAspectRatio, |
| 221 |
Qt::SmoothTransformation); |
| 222 |
if (cropLocally) { |
| 223 |
image = image.copy((image.width() - requestedSize.width()) / 2, |
| 224 |
(image.height() - requestedSize.height()) / 2, |
| 225 |
requestedSize.width(), |
| 226 |
requestedSize.height()); |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
if (radius != 0) { |
| 231 |
image = clipRadius(std::move(image), radius); |
| 232 |
} |
| 233 |
|
| 234 |
if (!image.isNull()) { |
| 235 |
then(id, requestedSize, image, fileInfo.absoluteFilePath()); |
| 236 |
return; |
| 237 |
} |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
mtx::http::ThumbOpts opts; |
| 242 |
opts.mxc_url = "mxc://" + id.toStdString(); |
| 243 |
opts.width = static_cast<uint16_t>(requestedSize.width() > 0 ? requestedSize.width() : -1); |
| 244 |
opts.height = |
| 245 |
static_cast<uint16_t>(requestedSize.height() > 0 ? requestedSize.height() : -1); |
| 246 |
opts.method = crop ? "crop" : "scale"; |
| 247 |
http::client()->get_thumbnail( |
| 248 |
opts, |
| 249 |
[fileInfo, requestedSize, radius, then, id, crop, cropLocally]( |
| 250 |
const std::string &res, mtx::http::RequestErr err) { |
| 251 |
if (err || res.empty()) { |
| 252 |
download(id, QSize(), then, crop, radius); |
| 253 |
return; |
| 254 |
} |
| 255 |
|
| 256 |
auto data = QByteArray(res.data(), (int)res.size()); |
| 257 |
QImage image = utils::readImage(data); |
| 258 |
if (!image.isNull()) { |
| 259 |
possiblyUpdateAccessTime(fileInfo); |
| 260 |
|
| 261 |
if (requestedSize.width() <= 0) { |
| 262 |
image = |
| 263 |
image.scaledToHeight(requestedSize.height(), Qt::SmoothTransformation); |
| 264 |
} else { |
| 265 |
image = image.scaled(requestedSize, |
| 266 |
cropLocally ? Qt::KeepAspectRatioByExpanding |
| 267 |
: Qt::KeepAspectRatio, |
| 268 |
Qt::SmoothTransformation); |
| 269 |
if (cropLocally) { |
| 270 |
image = image.copy((image.width() - requestedSize.width()) / 2, |
| 271 |
(image.height() - requestedSize.height()) / 2, |
| 272 |
requestedSize.width(), |
| 273 |
requestedSize.height()); |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
if (radius != 0) { |
| 278 |
image = clipRadius(std::move(image), radius); |
| 279 |
} |
| 280 |
} |
| 281 |
image.setText(QStringLiteral("mxc url"), "mxc://" + id); |
| 282 |
if (image.save(fileInfo.absoluteFilePath(), "png")) { |
| 283 |
utils::markFileAsFromWeb(fileInfo.absoluteFilePath()); |
| 284 |
nhlog::ui()->debug("Wrote: {}", fileInfo.absoluteFilePath().toStdString()); |
| 285 |
} else |
| 286 |
nhlog::ui()->debug("Failed to write: {}", |
| 287 |
fileInfo.absoluteFilePath().toStdString()); |
| 288 |
|
| 289 |
then(id, requestedSize, image, fileInfo.absoluteFilePath()); |
| 290 |
}); |
| 291 |
} else { |
| 292 |
try { |
| 293 |
QString fileName = QStringLiteral("%1_radius%2") |
| 294 |
.arg(QString::fromUtf8(id.toUtf8().toBase64( |
| 295 |
QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals))) |
| 296 |
.arg(radius); |
| 297 |
|
| 298 |
QFileInfo fileInfo(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + |
| 299 |
"/media_cache", |
| 300 |
fileName); |
| 301 |
QDir().mkpath(fileInfo.absolutePath()); |
| 302 |
|
| 303 |
if (fileInfo.exists()) { |
| 304 |
if (encryptionInfo) { |
| 305 |
QFile f(fileInfo.absoluteFilePath()); |
| 306 |
f.open(QIODevice::ReadOnly); |
| 307 |
|
| 308 |
QByteArray fileData = f.readAll(); |
| 309 |
auto tempData = mtx::crypto::to_string( |
| 310 |
mtx::crypto::decrypt_file(fileData.toStdString(), encryptionInfo.value())); |
| 311 |
auto data = QByteArray(tempData.data(), (int)tempData.size()); |
| 312 |
QImage image = utils::readImage(data); |
| 313 |
image.setText(QStringLiteral("mxc url"), "mxc://" + id); |
| 314 |
if (!image.isNull()) { |
| 315 |
possiblyUpdateAccessTime(fileInfo); |
| 316 |
if (radius != 0) { |
| 317 |
image = clipRadius(std::move(image), radius); |
| 318 |
} |
| 319 |
|
| 320 |
then(id, requestedSize, image, fileInfo.absoluteFilePath()); |
| 321 |
return; |
| 322 |
} |
| 323 |
} else { |
| 324 |
QImage image = utils::readImageFromFile(fileInfo.absoluteFilePath()); |
| 325 |
if (!image.isNull()) { |
| 326 |
possiblyUpdateAccessTime(fileInfo); |
| 327 |
if (radius != 0) { |
| 328 |
image = clipRadius(std::move(image), radius); |
| 329 |
} |
| 330 |
|
| 331 |
then(id, requestedSize, image, fileInfo.absoluteFilePath()); |
| 332 |
return; |
| 333 |
} |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
http::client()->download( |
| 338 |
"mxc://" + id.toStdString(), |
| 339 |
[fileInfo, requestedSize, then, id, radius, encryptionInfo]( |
| 340 |
const std::string &res, |
| 341 |
const std::string &, |
| 342 |
const std::string &originalFilename, |
| 343 |
mtx::http::RequestErr err) { |
| 344 |
if (err) { |
| 345 |
nhlog::net()->error("Failed to download {}: {}", id.toStdString(), *err); |
| 346 |
then(id, QSize(), {}, QLatin1String("")); |
| 347 |
return; |
| 348 |
} |
| 349 |
|
| 350 |
auto tempData = res; |
| 351 |
QFile f(fileInfo.absoluteFilePath()); |
| 352 |
if (!f.open(QIODevice::Truncate | QIODevice::WriteOnly)) { |
| 353 |
nhlog::net()->error( |
| 354 |
"Failed to write {}: {}", id.toStdString(), f.errorString().toStdString()); |
| 355 |
then(id, QSize(), {}, QLatin1String("")); |
| 356 |
return; |
| 357 |
} |
| 358 |
f.write(tempData.data(), tempData.size()); |
| 359 |
f.close(); |
| 360 |
utils::markFileAsFromWeb(fileInfo.absoluteFilePath()); |
| 361 |
|
| 362 |
if (encryptionInfo) { |
| 363 |
tempData = mtx::crypto::to_string( |
| 364 |
mtx::crypto::decrypt_file(tempData, encryptionInfo.value())); |
| 365 |
auto data = QByteArray(tempData.data(), (int)tempData.size()); |
| 366 |
QImage image = utils::readImage(data); |
| 367 |
if (radius != 0) { |
| 368 |
image = clipRadius(std::move(image), radius); |
| 369 |
} |
| 370 |
|
| 371 |
image.setText(QStringLiteral("original filename"), |
| 372 |
QString::fromStdString(originalFilename)); |
| 373 |
image.setText(QStringLiteral("mxc url"), "mxc://" + id); |
| 374 |
|
| 375 |
then(id, requestedSize, image, fileInfo.absoluteFilePath()); |
| 376 |
return; |
| 377 |
} |
| 378 |
|
| 379 |
QImage image = utils::readImageFromFile(fileInfo.absoluteFilePath()); |
| 380 |
if (radius != 0) { |
| 381 |
image = clipRadius(std::move(image), radius); |
| 382 |
} |
| 383 |
|
| 384 |
image.setText(QStringLiteral("original filename"), |
| 385 |
QString::fromStdString(originalFilename)); |
| 386 |
image.setText(QStringLiteral("mxc url"), "mxc://" + id); |
| 387 |
|
| 388 |
then(id, requestedSize, image, fileInfo.absoluteFilePath()); |
| 389 |
}); |
| 390 |
} catch (std::exception &e) { |
| 391 |
nhlog::net()->error("Exception while downloading media: {}", e.what()); |
| 392 |
} |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
#include "moc_MxcImageProvider.cpp" |