1// SPDX-FileCopyrightText: Tobias Fella <fella@posteo.de>
2// SPDX-License-Identifier: LGPL-2.1-or-later
3
4#include "mxcreply.h"
5
6#include <QtCore/QBuffer>
7
8#ifdef Quotient_E2EE_ENABLED
9#include "events/filesourceinfo.h"
10#endif
11
12using namespace Quotient;
13
14class Q_DECL_HIDDEN MxcReply::Private
15{
16public:
17 QNetworkReply* m_reply;
18 QIODevice* m_device;
19};
20
21MxcReply::MxcReply(QNetworkReply* reply,
22 const EncryptedFileMetadata& fileMetadata)
23 : d(makeImpl<Private>(args&: reply, args: fileMetadata.isValid() ? nullptr : reply))
24{
25 reply->setParent(this);
26 connect(sender: d->m_reply, signal: &QNetworkReply::finished, context: this, slot: [this, fileMetadata] {
27 setError(errorCode: d->m_reply->error(), errorString: d->m_reply->errorString());
28
29#ifdef Quotient_E2EE_ENABLED
30 if (fileMetadata.isValid()) {
31 auto buffer = new QBuffer(this);
32 buffer->setData(decryptFile(d->m_reply->readAll(), fileMetadata));
33 buffer->open(ReadOnly);
34 d->m_device = buffer;
35 }
36#endif
37 setOpenMode(ReadOnly);
38 emit finished();
39 });
40}
41
42MxcReply::MxcReply()
43 : d(ZeroImpl<Private>())
44{
45 static const auto BadRequestPhrase = tr(s: "Bad Request");
46 QMetaObject::invokeMethod(object: this, function: [this]() {
47 setAttribute(code: QNetworkRequest::HttpStatusCodeAttribute, value: 400);
48 setAttribute(code: QNetworkRequest::HttpReasonPhraseAttribute,
49 value: BadRequestPhrase);
50 setError(errorCode: QNetworkReply::ProtocolInvalidOperationError,
51 errorString: BadRequestPhrase);
52 setFinished(true);
53 emit errorOccurred(QNetworkReply::ProtocolInvalidOperationError);
54 emit finished();
55 }, type: Qt::QueuedConnection);
56}
57
58qint64 MxcReply::readData(char *data, qint64 maxSize)
59{
60 if(d != nullptr && d->m_device != nullptr) {
61 return d->m_device->read(data, maxlen: maxSize);
62 }
63 return -1;
64}
65
66void MxcReply::abort()
67{
68 if(d != nullptr && d->m_reply != nullptr) {
69 d->m_reply->abort();
70 }
71}
72
73qint64 MxcReply::bytesAvailable() const
74{
75 if (d != nullptr && d->m_device != nullptr) {
76 return d->m_device->bytesAvailable() + QNetworkReply::bytesAvailable();
77 }
78 return 0;
79}
80