From ea98d7b2aed5d5085d0ce1833568ec93ff813b0f Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Sat, 5 Oct 2019 23:11:20 +0200 Subject: Add simple audio message widget --- src/timeline2/TimelineViewManager.cpp | 59 +++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) (limited to 'src/timeline2/TimelineViewManager.cpp') 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 #include #include +#include #include "Logging.h" #include "MxcImageProvider.h" @@ -143,6 +144,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(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 &event_ids) -- cgit 1.5.1