• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

graphia-app / graphia / 41618190308

03 Nov 2026 12:10AM UTC coverage: 71.393% (+0.06%) from 71.33%
41618190308

push

github

timangus
Identify proxy types by value, not by their translated names

11761 of 18022 branches covered (65.26%)

Branch coverage included in aggregate %.

29963 of 40421 relevant lines covered (74.13%)

197248.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

7.18
/source/shared/utils/downloadqueue.cpp
1
/* Copyright © 2013-2025 Tim Angus
2
 * Copyright © 2013-2025 Tom Freeman
3
 *
4
 * This file is part of Graphia.
5
 *
6
 * Graphia is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * Graphia is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with Graphia.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

20
#include "downloadqueue.h"
21

22
#include <QDebug>
23
#include <QDir>
24
#include <QFile>
25
#include <QNetworkReply>
26
#include <QTemporaryDir>
27
#include <QFileInfo>
28
#include <QRegularExpression>
29
#include <QtGlobal>
30
#include <QVariant>
31

32
#include <algorithm>
33
#include <cstdio>
34

35
using namespace Qt::Literals::StringLiterals;
36

37
DownloadQueue::DownloadQueue() :
38
    _corsUrl(qEnvironmentVariable("CORS_PROXY"))
90 ✔
39
{
90 ✔
40
    _networkManager.setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
90 ✔
41
    connect(&_networkManager, &QNetworkAccessManager::finished, this, &DownloadQueue::onReplyReceived);
90 ✔
42
}
90 ✔
43

44
DownloadQueue::~DownloadQueue()
45
{
46 ✔
46
    cancel();
46 ✔
47

48
    for(const auto& [deletee, isDir] : _downloaded)
46 !
49
    {
×
50
        if(isDir == IsDir::Yes)
×
51
            QDir(deletee).removeRecursively();
×
52
        else
×
53
            QFile::remove(deletee);
×
54
    }
×
55
}
46 ✔
56

57
bool DownloadQueue::add(const QUrl& url)
58
{
×
59
    // If idle, start downloading
60
    if(idle())
×
61
    {
×
62
        start(url);
×
63
        return true;
×
64
    }
×
65

66
    _queue.push(url);
×
67

68
    return false;
×
69
}
×
70

71
void DownloadQueue::cancel()
72
{
46 ✔
73
    // Clear _queue
74
    _queue = {};
46 ✔
75

76
    if(!idle())
46 !
77
    {
×
78
        _reply->abort();
×
79
        reset();
×
80
    }
×
81
}
46 ✔
82

83
bool DownloadQueue::resume()
84
{
×
85
    // If idle and non empty, start downloading
86
    if(!_queue.empty() && idle())
×
87
    {
×
88
        const auto& url = _queue.front();
×
89
        start(url);
×
90
        _queue.pop();
×
91

92
        return true;
×
93
    }
×
94

95
    return false;
×
96
}
×
97

98
bool DownloadQueue::downloaded(const QUrl& url) const
99
{
×
100
    auto fileinfo = QFileInfo(url.toLocalFile());
×
101
    auto filename = fileinfo.canonicalFilePath();
×
102
    auto dirname = fileinfo.canonicalPath();
×
103

104
    return std::ranges::any_of(_downloaded, [&](const auto& deletee)
×
105
    {
×
106
        auto downloadedFilename =
×
107
            QFileInfo(deletee.first).canonicalFilePath();
×
108

109
        const bool match = deletee.second == IsDir::Yes ?
×
110
            (dirname == downloadedFilename) :
×
111
            (filename == downloadedFilename);
×
112

113
        return match;
×
114
    });
×
115
}
×
116

117
void DownloadQueue::start(const QUrl& url)
118
{
×
119
    _temporaryFile = std::make_unique<QTemporaryFile>();
×
120
    if(!_temporaryFile->open())
×
121
    {
×
122
        qDebug() << "Failed to create temporary file while downloading" << url.toString();
×
123
        return;
×
124
    }
×
125
    _downloaded.emplace(_temporaryFile->fileName(), IsDir::No);
×
126
    _temporaryFile->setAutoRemove(false);
×
127

128
    QNetworkRequest request;
×
129
    request.setUrl(url);
×
130
    _reply = _networkManager.get(request);
×
131

132
    _timeoutTimer.setSingleShot(true);
×
133
    const int HTTP_TIMEOUT = 60000;
×
134
    _timeoutTimer.start(HTTP_TIMEOUT);
×
135

136
    connect(_reply, &QNetworkReply::downloadProgress, [this]
×
137
    (qint64 bytesReceived, qint64 bytesTotal)
×
138
    {
×
139
        _timeoutTimer.start(HTTP_TIMEOUT);
×
140

141
        auto oldProgress = _progress;
×
142

143
        if(bytesTotal > 0)
×
144
            _progress = static_cast<int>((bytesReceived * 100u) / bytesTotal);
×
145

146
        if(_progress != oldProgress)
×
147
            emit progressChanged(_progress);
×
148
    });
×
149

150
    connect(_reply, &QNetworkReply::readyRead, [this]
×
151
    {
×
152
        _temporaryFile->write(_reply->readAll());
×
153
    });
×
154

155
    connect(&_timeoutTimer, &QTimer::timeout, [this]
×
156
    {
×
157
        _reply->abort();
×
158
        reset();
×
159
    });
×
160

161
    _progress = 0;
×
162
    emit progressChanged(_progress);
×
163
    emit idleChanged();
×
164
}
×
165

166
void DownloadQueue::onReplyReceived(QNetworkReply* reply)
167
{
×
168
    Q_ASSERT(reply == _reply);
×
169

170
    if(_timeoutTimer.isActive())
×
171
        _timeoutTimer.stop();
×
172

173
    if(_reply->error() != QNetworkReply::NetworkError::NoError)
×
174
    {
×
175
        auto httpCode = static_cast<int>(_reply->error());
×
176
        auto networkErrorString = QVariant::fromValue(_reply->error()).toString();
×
177
        auto errorString = u"Network Error: %1 (%2/%3)"_s
×
178
            .arg(_reply->errorString(), QString::number(httpCode), networkErrorString);
×
179

180
#ifdef Q_OS_WASM
181
        // A CORS error is reported as a HTTP 339/ProtocolFailure (for now? forever?)
182
        // Try again using a CORS proxy, if available
183
        if(_corsUrl.isValid() &&
184
           _reply->error() == QNetworkReply::NetworkError::ProtocolFailure &&
185
           _reply->url().host() != _corsUrl.host()) // Prevent loops
186
        {
187
            _reply->deleteLater();
188
            start(QUrl(u"%1/%2"_s.arg(_corsUrl.toString(), _reply->url().toString())));
189
            return;
190
        }
191
#endif
192

193
        if(_reply->error() != QNetworkReply::NetworkError::OperationCanceledError)
×
194
            emit error(_reply->url(), errorString);
×
195

196
        _reply->deleteLater();
×
197
        reset();
×
198
        return;
×
199
    }
×
200

201
    _progress = -1;
×
202
    emit progressChanged(_progress);
×
203

204
    QString filename;
×
205

206
    auto contentDisposition = _reply->header(QNetworkRequest::ContentDispositionHeader);
×
207
    if(contentDisposition.isValid())
×
208
    {
×
209
        filename = contentDisposition.toString();
×
210
        static const QRegularExpression re(
×
211
            uR"|(^(?:[^;]*;)*\s*filename\*?="?([^"]+)"?$)|"_s);
×
212
        filename.replace(re, uR"(\1)"_s);
×
213
    }
×
214
    else
×
215
        filename = _reply->url().fileName();
×
216

217
    if(_temporaryFile != nullptr && _temporaryFile->isOpen())
×
218
    {
×
219
        if(filename.isEmpty())
×
220
        {
×
221
            // Can't figure out an appropriate name from the reply,
222
            // so resort to using the existing temp file name
223
            filename = _temporaryFile->fileName();
×
224
            _temporaryFile->close();
×
225
        }
×
226
        else
×
227
        {
×
228
            QTemporaryDir tempDir;
×
229
            filename = tempDir.filePath(filename);
×
230
            tempDir.setAutoRemove(false);
×
231

232
            if(!_temporaryFile->rename(filename))
×
233
            {
×
234
                qDebug() << "Failed to rename" << _temporaryFile->fileName() << "to" << filename;
×
235
                return;
×
236
            }
×
237

238
            _downloaded.erase(_temporaryFile->fileName());
×
239
            _downloaded.emplace(tempDir.path(), IsDir::Yes);
×
240
        }
×
241
    }
×
242

243
    if(!filename.isEmpty())
×
244
        emit complete(_reply->url(), filename);
×
245

246
    _reply->deleteLater();
×
247
    reset();
×
248
}
×
249

250
void DownloadQueue::reset()
251
{
×
252
    if(_progress >= 0)
×
253
    {
×
254
        _progress = -1;
×
255
        emit progressChanged(_progress);
×
256
    }
×
257

258
    if(_reply != nullptr)
×
259
    {
×
260
        _reply = nullptr;
×
261
        emit idleChanged();
×
262
    }
×
263

264
    if(_temporaryFile != nullptr)
×
265
        _temporaryFile = nullptr;
×
266
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc