aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/utils/filedownloader.cpp
blob: 8b3bb63993e74478bd169a7421a8ccd5d4090917 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0
#include "filedownloader.h"

#include <private/qqmldata_p.h>
#include <utils/networkaccessmanager.h>
#include <utils/filepath.h>

#include <QDir>
#include <QQmlEngine>
#include <QRandomGenerator>
#include <QSslSocket>

namespace QmlDesigner {

FileDownloader::FileDownloader(QObject *parent)
    : QObject(parent)
{
    QObject::connect(this, &FileDownloader::downloadFailed, this, [this]() {
        if (m_outputFile.exists())
            m_outputFile.remove();
    });

    QObject::connect(this, &FileDownloader::downloadCanceled, this, [this]() {
        if (m_outputFile.exists())
            m_outputFile.remove();
    });
}

FileDownloader::~FileDownloader()
{
    // Delete the temp file only if a target Path was set (i.e. file will be moved)
    if (deleteFileAtTheEnd() && m_outputFile.exists())
        m_outputFile.remove();
}

bool FileDownloader::deleteFileAtTheEnd() const
{
    return m_targetFilePath.isEmpty();
}

QNetworkRequest FileDownloader::makeRequest() const
{
    QUrl url = m_url;

    if (url.scheme() == "https" && !QSslSocket::supportsSsl()) {
        qWarning() << "SSL is not available. HTTP will be used instead of HTTPS.";
        url.setScheme("http");
    }

    auto request = QNetworkRequest(url);
    request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
                         QNetworkRequest::UserVerifiedRedirectPolicy);

    return request;
}

void FileDownloader::start()
{
    emit downloadStarting();

    auto uniqueText = QByteArray::number(QRandomGenerator::global()->generate(), 16);
    QString tempFileName = QDir::tempPath() + "/.qds_" + uniqueText + "_download_" + url().fileName();

    m_outputFile.setFileName(tempFileName);
    m_outputFile.open(QIODevice::WriteOnly);

    QNetworkRequest request = makeRequest();
    QNetworkReply *reply = Utils::NetworkAccessManager::instance()->get(request);
    m_reply = reply;

    QNetworkReply::connect(reply, &QNetworkReply::readyRead, this, [this, reply]() {
        bool isDownloadingFile = false;
        QString contentType;
        if (!reply->hasRawHeader("Content-Type")) {
            isDownloadingFile = true;
        } else {
            contentType = QString::fromUtf8(reply->rawHeader("Content-Type"));

            if (contentType.startsWith("application/")
                || contentType.startsWith("image/")
                || contentType.startsWith("binary/")) {
                isDownloadingFile = true;
            } else {
                qWarning() << "FileDownloader: Content type '" << contentType << "' is not supported";
            }
        }

        if (isDownloadingFile)
            m_outputFile.write(reply->readAll());
        else
            reply->close();
    });

    QNetworkReply::connect(reply,
                           &QNetworkReply::downloadProgress,
                           this,
                           [this](qint64 current, qint64 max) {
                               if (max <= 0) {
                                   // NOTE: according to doc, we might have the second arg
                                   // of QNetworkReply::downloadProgress less than 0.
                                   return;
                               }

                               m_progress = current * 100 / max;
                               emit progressChanged();
                           });

    QNetworkReply::connect(reply, &QNetworkReply::redirected, [reply](const QUrl &) {
        emit reply->redirectAllowed();
    });

    QNetworkReply::connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        if (reply->error()) {
            if (reply->error() != QNetworkReply::OperationCanceledError) {
                qWarning() << Q_FUNC_INFO << m_url << reply->errorString();
                emit downloadFailed();
            } else {
                emit downloadCanceled();
            }
        } else {
            m_outputFile.flush();
            m_outputFile.close();

            QString dirPath = QFileInfo(m_targetFilePath).dir().absolutePath();
            if (!deleteFileAtTheEnd()) {
                if (!QDir{}.mkpath(dirPath)) {
                    emit downloadFailed();
                    return;
                }

                if (m_overwriteTarget && QFileInfo().exists(m_targetFilePath)) {
                    if (!QFile::remove(m_targetFilePath)) {
                        emit downloadFailed();
                        return;
                    }
                }

                if (!QFileInfo().exists(m_targetFilePath) && !m_outputFile.rename(m_targetFilePath)) {
                    emit downloadFailed();
                    return;
                }
            }

            m_finished = true;
            emit outputFileChanged();
            emit finishedChanged();
        }

        reply->deleteLater();
        m_reply = nullptr;
    });
}

void FileDownloader::setProbeUrl(bool value)
{
    if (m_probeUrl == value)
        return;

    m_probeUrl = value;
    emit probeUrlChanged();
}

bool FileDownloader::probeUrl() const
{
    return m_probeUrl;
}

void FileDownloader::cancel()
{
    if (m_reply)
        m_reply->abort();
}

void FileDownloader::setUrl(const QUrl &url)
{
    if (m_url != url) {
        m_url = url;
        emit urlChanged();
    }

    if (m_probeUrl)
        doProbeUrl();
}

QUrl FileDownloader::url() const
{
    return m_url;
}

void FileDownloader::setDownloadEnabled(bool value)
{
    if (m_downloadEnabled == value)
        return;

    m_downloadEnabled = value;
    emit downloadEnabledChanged();

    if (!m_url.isEmpty() && m_probeUrl)
        doProbeUrl();
}

bool FileDownloader::downloadEnabled() const
{
    return m_downloadEnabled;
}

bool FileDownloader::overwriteTarget() const
{
    return m_overwriteTarget;
}

void FileDownloader::setOverwriteTarget(bool value)
{
    if (value != m_overwriteTarget) {
        m_overwriteTarget = value;
        emit overwriteTargetChanged();
    }
}

bool FileDownloader::finished() const
{
    return m_finished;
}

bool FileDownloader::error() const
{
    return m_error;
}

QString FileDownloader::name() const
{
    const QFileInfo fileInfo(m_url.path());
    return fileInfo.baseName();
}

QString FileDownloader::completeBaseName() const
{
    return QFileInfo(m_url.path()).completeBaseName();
}

int FileDownloader::progress() const
{
    return m_progress;
}

QString FileDownloader::outputFile() const
{
    return QFileInfo(m_outputFile).canonicalFilePath();
}

QDateTime FileDownloader::lastModified() const
{
    return m_lastModified;
}

bool FileDownloader::available() const
{
    return m_available;
}

void FileDownloader::doProbeUrl()
{
    if (!m_probeUrl)
        return;

    if (!m_downloadEnabled) {
        m_available = false;
        emit availableChanged();
        return;
    }

    QNetworkRequest request = makeRequest();
    QNetworkReply *reply = Utils::NetworkAccessManager::instance()->head(request);

    QNetworkReply::connect(reply, &QNetworkReply::redirected, [reply](const QUrl &) {
        emit reply->redirectAllowed();
    });

    QNetworkReply::connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        if (reply->error())
            return;

        m_lastModified = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime();
        emit lastModifiedChanged();

        m_available = true;
        emit availableChanged();

        reply->deleteLater();
    });

    QNetworkReply::connect(reply,
                           &QNetworkReply::errorOccurred,
                           this,
                           [this](QNetworkReply::NetworkError code) {

                               if (QQmlData::wasDeleted(this)) {
                                   qDebug() << Q_FUNC_INFO << "FileDownloader was deleted.";
                                   return;
                               }

                               qDebug() << Q_FUNC_INFO << "Network error:" << code
                                        << qobject_cast<QNetworkReply *>(sender())->errorString();

                               m_available = false;
                               emit availableChanged();
                           });
}

void FileDownloader::setTargetFilePath(const QString &path)
{
    m_targetFilePath = path;
}

QString FileDownloader::targetFilePath() const
{
    return m_targetFilePath;
}

} // namespace QmlDesigner