diff --git a/src/timeline2/TimelineViewManager.cpp b/src/timeline2/TimelineViewManager.cpp
index 74e851c4..29c52ac9 100644
--- a/src/timeline2/TimelineViewManager.cpp
+++ b/src/timeline2/TimelineViewManager.cpp
@@ -4,6 +4,7 @@
#include <QMetaType>
#include <QMimeDatabase>
#include <QQmlContext>
+#include <QStandardPaths>
#include "Logging.h"
#include "MxcImageProvider.h"
@@ -144,6 +145,64 @@ TimelineViewManager::saveMedia(QString mxcUrl,
}
void
+TimelineViewManager::cacheMedia(QString mxcUrl, QString mimeType)
+{
+ // If the message is a link to a non mxcUrl, don't download it
+ if (!mxcUrl.startsWith("mxc://")) {
+ emit mediaCached(mxcUrl, mxcUrl);
+ return;
+ }
+
+ QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix();
+
+ const auto url = mxcUrl.toStdString();
+ QFileInfo filename(QString("%1/media_cache/%2.%3")
+ .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
+ .arg(QString(mxcUrl).remove("mxc://"))
+ .arg(suffix));
+ if (QDir::cleanPath(filename.path()) != filename.path()) {
+ nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url);
+ return;
+ }
+
+ QDir().mkpath(filename.path());
+
+ if (filename.isReadable()) {
+ emit mediaCached(mxcUrl, filename.filePath());
+ return;
+ }
+
+ http::client()->download(
+ url,
+ [this, mxcUrl, filename, url](const std::string &data,
+ const std::string &,
+ const std::string &,
+ mtx::http::RequestErr err) {
+ if (err) {
+ nhlog::net()->warn("failed to retrieve image {}: {} {}",
+ url,
+ err->matrix_error.error,
+ static_cast<int>(err->status_code));
+ return;
+ }
+
+ try {
+ QFile file(filename.filePath());
+
+ if (!file.open(QIODevice::WriteOnly))
+ return;
+
+ file.write(QByteArray(data.data(), data.size()));
+ file.close();
+ } catch (const std::exception &e) {
+ nhlog::ui()->warn("Error while saving file to: {}", e.what());
+ }
+
+ emit mediaCached(mxcUrl, filename.filePath());
+ });
+}
+
+void
TimelineViewManager::updateReadReceipts(const QString &room_id,
const std::vector<QString> &event_ids)
{
diff --git a/src/timeline2/TimelineViewManager.h b/src/timeline2/TimelineViewManager.h
index a8fcf7ce..6a6d3c6b 100644
--- a/src/timeline2/TimelineViewManager.h
+++ b/src/timeline2/TimelineViewManager.h
@@ -42,6 +42,7 @@ public:
QString originalFilename,
QString mimeType,
qml_mtx_events::EventType eventType) const;
+ Q_INVOKABLE void cacheMedia(QString mxcUrl, QString mimeType);
// Qml can only pass enum as int
Q_INVOKABLE void openImageOverlay(QString mxcUrl,
QString originalFilename,
@@ -63,6 +64,7 @@ signals:
void clearRoomMessageCount(QString roomid);
void updateRoomsLastMessage(QString roomid, const DescInfo &info);
void activeTimelineChanged(TimelineModel *timeline);
+ void mediaCached(QString mxcUrl, QString cacheUrl);
public slots:
void updateReadReceipts(const QString &room_id, const std::vector<QString> &event_ids);
|