Debian Codegraph @

src/ui/MxcAnimatedImage.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "MxcAnimatedImage.h"
6
7 #include <QDir>
8 #include <QFileInfo>
9 #include <QMimeDatabase>
10 #include <QQuickWindow>
11 #include <QSGImageNode>
12 #include <QStandardPaths>
13
14 #include "EventAccessors.h"
15 #include "Logging.h"
16 #include "MatrixClient.h"
17 #include "timeline/TimelineModel.h"
18
19 void
20 MxcAnimatedImage::startDownload()
21 {
22 if (!room_)
23 return;
24 if (eventId_.isEmpty())
25 return;
26
27 auto event = room_->eventById(eventId_);
28 if (!event) {
29 nhlog::ui()->error("Failed to load media for event {}, event not found.",
30 eventId_.toStdString());
31 return;
32 }
33
34 QByteArray mimeType = QString::fromStdString(mtx::accessors::mimetype(*event)).toUtf8();
35
36 static const auto formats = QMovie::supportedFormats();
37 animatable_ = formats.contains(mimeType.split('/').back());
38 animatableChanged();
39
40 if (!animatable_)
41 return;
42
43 QString mxcUrl = QString::fromStdString(mtx::accessors::url(*event));
44
45 auto encryptionInfo = mtx::accessors::file(*event);
46
47 // If the message is a link to a non mxcUrl, don't download it
48 if (!mxcUrl.startsWith(QLatin1String("mxc://"))) {
49 return;
50 }
51
52 QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix();
53
54 const auto url = mxcUrl.toStdString();
55 const auto name = QString(mxcUrl).remove(QStringLiteral("mxc://"));
56 QFileInfo filename(QStringLiteral("%1/media_cache/media/%2.%3")
57 .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation),
58 QString::fromUtf8(name.toUtf8().toBase64(
59 QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)),
60 suffix));
61 if (QDir::cleanPath(filename.filePath()) != filename.filePath()) {
62 nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url);
63 return;
64 }
65
66 QDir().mkpath(filename.path());
67
68 QPointer<MxcAnimatedImage> self = this;
69
70 auto processBuffer = [this, mimeType, encryptionInfo, self](QIODevice &device) {
71 if (!self)
72 return;
73
74 try {
75 if (buffer.isOpen()) {
76 movie.stop();
77 movie.setDevice(nullptr);
78 buffer.close();
79 }
80
81 if (encryptionInfo) {
82 QByteArray ba = device.readAll();
83 std::string temp(ba.constData(), ba.size());
84 temp =
85 mtx::crypto::to_string(mtx::crypto::decrypt_file(temp, encryptionInfo.value()));
86 buffer.setData(temp.data(), static_cast<int>(temp.size()));
87 } else {
88 buffer.setData(device.readAll());
89 }
90 buffer.open(QIODevice::ReadOnly);
91 buffer.reset();
92 } catch (const std::exception &e) {
93 nhlog::net()->error("Failed to setup animated image buffer: {}", e.what());
94 }
95
96 QTimer::singleShot(0, this, [this, mimeType] {
97 nhlog::ui()->info(
98 "Playing movie with size: {}, {}", buffer.bytesAvailable(), buffer.isOpen());
99 movie.setFormat(mimeType);
100 movie.setDevice(&buffer);
101
102 if (height() != 0 && width() != 0)
103 movie.setScaledSize(this->size().toSize());
104 if (buffer.bytesAvailable() <
105 4LL * 1024 * 1024 * 1024) // cache images smaller than 4MB in RAM
106 movie.setCacheMode(QMovie::CacheAll);
107 if (play_ && movie.frameCount() > 1)
108 movie.start();
109 else {
110 movie.jumpToFrame(0);
111 movie.setPaused(true);
112 }
113 emit loadedChanged();
114 update();
115 });
116 };
117
118 if (filename.isReadable()) {
119 QFile f(filename.filePath());
120 if (f.open(QIODevice::ReadOnly)) {
121 processBuffer(f);
122 return;
123 }
124 }
125
126 http::client()->download(url,
127 [filename, url, processBuffer](const std::string &data,
128 const std::string &,
129 const std::string &,
130 mtx::http::RequestErr err) {
131 if (err) {
132 nhlog::net()->warn("failed to retrieve media {}: {} {}",
133 url,
134 err->matrix_error.error,
135 static_cast<int>(err->status_code));
136 return;
137 }
138
139 try {
140 QFile file(filename.filePath());
141
142 if (!file.open(QIODevice::WriteOnly))
143 return;
144
145 QByteArray ba(data.data(), (int)data.size());
146 file.write(ba);
147 file.close();
148
149 QBuffer buf(&ba);
150 buf.open(QBuffer::ReadOnly);
151 processBuffer(buf);
152 } catch (const std::exception &e) {
153 nhlog::ui()->warn("Error while saving file to: {}", e.what());
154 }
155 });
156 }
157
158 void
159 MxcAnimatedImage::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
160 {
161 QQuickItem::geometryChange(newGeometry, oldGeometry);
162
163 if (newGeometry.size() != oldGeometry.size()) {
164 if (height() != 0 && width() != 0) {
165 QSizeF r = movie.scaledSize();
166 r.scale(newGeometry.size(), Qt::KeepAspectRatio);
167 movie.setScaledSize(r.toSize());
168 imageDirty = true;
169 update();
170 }
171 }
172 }
173
174 QSGNode *
175 MxcAnimatedImage::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *)
176 {
177 if (!imageDirty)
178 return oldNode;
179
180 // If the image is offscreen, just return the old node (if it exists) to save on animation CPU
181 // use. Don't return null here, or you will never be called again.
182 if (clipRect().isEmpty() && oldNode)
183 return oldNode;
184
185 imageDirty = false;
186 QSGImageNode *n = static_cast<QSGImageNode *>(oldNode);
187 if (!n) {
188 n = window()->createImageNode();
189 n->setOwnsTexture(true);
190 // n->setFlags(QSGNode::OwnedByParent | QSGNode::OwnsGeometry |
191 // GSGNode::OwnsMaterial);
192 n->setFlags(QSGNode::OwnedByParent);
193 }
194
195 auto img = movie.currentImage();
196 n->setSourceRect(img.rect());
197 if (!img.isNull())
198 n->setTexture(window()->createTextureFromImage(std::move(img)));
199 else {
200 delete n;
201 return nullptr;
202 }
203
204 QSizeF r = img.size();
205 r.scale(size(), Qt::KeepAspectRatio);
206
207 n->setRect((width() - r.width()) / 2, (height() - r.height()) / 2, r.width(), r.height());
208 n->setFiltering(QSGTexture::Linear);
209 n->setMipmapFiltering(QSGTexture::None);
210
211 return n;
212 }
213
214 #include "moc_MxcAnimatedImage.cpp"