Debian Codegraph @

src/downloadinfo.h

raw symbols SCIP
1 // Copyright (C) 2014 Sacha Refshauge
2
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, version 3.0.
6
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 // GNU General Public License 3.0 for more details.
11
12 // A copy of the GPL 3.0 should have been included with the program.
13 // If not, see http://www.gnu.org/licenses/
14
15 // Official GIT repository and contact information can be found at
16 // http://github.com/xsacha/Sachesi
17
18 #pragma once
19 #include <QDir>
20 #include <QFile>
21 #include <QDesktopServices>
22 #include <QNetworkRequest>
23 #include <QNetworkReply>
24 #include <QNetworkAccessManager>
25 #include <QMessageBox>
26 #include "apps.h"
27 #include "ports.h"
28
29 // Need to get creative with CURR_FILE when threading comes
30 enum {
31 CURR_FILE = -1,
32 };
33
34 class DownloadInfo : public QObject {
35 Q_OBJECT
36 Q_PROPERTY(int id MEMBER id NOTIFY idChanged)
37 Q_PROPERTY(int maxId MEMBER maxId NOTIFY appsChanged)
38 Q_PROPERTY(int curProgress MEMBER curProgress NOTIFY sizeChanged)
39 Q_PROPERTY(int progress MEMBER progress NOTIFY sizeChanged)
40 Q_PROPERTY(int size MEMBER size NOTIFY sizeChanged)
41 Q_PROPERTY(qint64 totalSize MEMBER totalSize NOTIFY appsChanged)
42 Q_PROPERTY(QString curName READ getName NOTIFY idChanged)
43 Q_PROPERTY(bool verifying READ verifying NOTIFY verifyingChanged)
44 Q_PROPERTY(bool running MEMBER running NOTIFY idChanged)
45 public:
46 DownloadInfo(QObject* parent = 0)
47 : QObject(parent)
48 , baseDir("")
49 , id(0), maxId(0)
50 , progress(0), curProgress(0)
51 , size(0), totalSize(0)
52 , starting(false)
53 , toVerify(0)
54 , running(false)
55 {
56 _manager = new QNetworkAccessManager();
57 }
58
59 Q_INVOKABLE void reset() {
60 if (_updateFile.isOpen())
61 _updateFile.close();
62
63 starting = false;
64 running = false;
65 id = 0;
66 maxId = 0;
67 size = 0;
68 totalSize = 0;
69 toVerify = 0;
70 foreach(Apps* app, apps) {
71 if (app != nullptr) {
72 delete app;
73 app = nullptr;
74 }
75 }
76 apps.clear();
77 emit sizeChanged();
78 emit idChanged();
79 emit appsChanged();
80 }
81
82 Q_INVOKABLE void start() {
83 starting = true;
84 if (_updateFile.isOpen()) {
85 _updateFile.close();
86 _updateFile.remove();
87 }
88 }
89
90 bool isStarting() {
91 bool isRequested = starting;
92 starting = false;
93 return isRequested;
94 }
95
96 bool verifying() const {
97 return toVerify > 0;
98 }
99
100 void verifyDelta(int i) {
101 toVerify++;
102 emit verifyingChanged();
103 QString url = apps.at(i)->url();
104 QString oldVersion = apps.at(i)->installedVersion();
105 oldVersion.replace('.','_');
106 url.chop(4); // Remove extension
107 url.append(QString("+patch+%1.bar").arg(oldVersion));
108 QNetworkReply* reply = _manager->head(QNetworkRequest(url));
109
110 QObject::connect(reply, &QNetworkReply::finished, [=]() {
111 uint status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();
112 if (status == 200 || (status > 300 && status <= 308)) {
113 uint realSize = reply->header(QNetworkRequest::ContentLengthHeader).toUInt();
114 // Adjust the expected size
115 totalSize += realSize - apps.at(i)->size();
116 apps.at(i)->setSize(realSize);
117 apps.at(i)->setUrl(url);
118 emit sizeChanged();
119 emit appsChanged();
120 }
121 toVerify--;
122 emit verifyingChanged();
123 // Verified. Now to complete
124 if (toVerify == 0)
125 startDownload();
126 reply->deleteLater();
127 });
128 QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [=]() {
129 toVerify--;
130 emit verifyingChanged();
131 // Verified. Now to complete
132 if (toVerify == 0)
133 startDownload();
134 reply->deleteLater();
135 });
136 }
137
138 void verifyLink(QString url, QString type, bool delta) {
139 toVerify++;
140 emit verifyingChanged();
141 QNetworkReply* reply = _manager->head(QNetworkRequest(url));
142
143 QObject::connect(reply, &QNetworkReply::finished, [=]() {
144 uint status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();
145 if (status == 200 || (status > 300 && status <= 308)) {
146 uint realSize = reply->header(QNetworkRequest::ContentLengthHeader).toUInt();
147 // Adjust the expected size
148 foreach(Apps* app, apps) {
149 if (app->type() == type.toLower()) {
150 totalSize += realSize - app->size();
151 app->setSize(realSize);
152 emit sizeChanged();
153 emit appsChanged();
154 }
155 }
156
157 toVerify--;
158 emit verifyingChanged();
159 // Verified. Now to complete
160 if (toVerify == 0)
161 download(delta);
162 } else {
163 reset();
164 QMessageBox::information(NULL, "Error", "The server did not have the " + type + " for the selected 'Download Device'.\n\nPlease try a different search result or a different download device.");
165 }
166 reply->deleteLater();
167 });
168 QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [=]() {
169 if (toVerify > 0) {
170 QMessageBox::information(NULL, "Error", "Encountered an error when attempting to verify the " + type +".\n Aborting download.");
171 reset();
172 }
173 reply->deleteLater();
174 });
175 }
176
177 void download(bool delta) {
178 // Check for deltas
179 if (delta) { // Checking for connected
180 for (int i = 0; i < apps.count(); i++) {
181 if (!apps.at(i)->isMarked() || apps.at(i)->installedVersion().isEmpty())
182 continue;
183 if (isVersionNewer(apps.at(i)->version(), apps.at(i)->installedVersion(), false))
184 verifyDelta(i);
185 }
186 }
187 if (toVerify == 0)
188 startDownload();
189 }
190
191 void startDownload() {
192 running = true;
193 // OS and Radio files were just verified, so lets check if we already have them
194 for (int i = 0; i < apps.count(); i++) {
195 if (apps[i]->type() == "os" || apps[i]->type() == "radio") {
196 QFileInfo fileInfo(baseDir + "/" + apps[i]->name());
197 if (fileInfo.exists() && fileInfo.size() == apps[i]->size()) {
198 totalSize -= apps[i]->size();
199 delete apps[i];
200 apps.removeAt(i--);
201 maxId--;
202 emit appsChanged();
203 emit sizeChanged();
204 }
205 }
206 }
207 if (apps.count() == 0) {
208 running = false;
209 return;
210 }
211 emit idChanged(); // For above, running=true and if any apps changed
212 QDir(baseDir).mkpath(".");
213 downloadNextFile();
214 }
215
216 void downloadNextFile() {
217 curSize = 0;
218 QNetworkRequest request(getUrl());
219 request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
220 // Set to a temporary filename
221 _updateFile.setFileName(baseDir + "/." + apps.at(id)->name());
222 // Obviously something is wrong if this file is bigger than what we want
223 if (_updateFile.size() > apps.at(id)->size()) {
224 if (QMessageBox::warning(nullptr, "Issue",
225 QString("Expected filesize of %1 did not match (Expected %2, Received %3). Ignore the warning or discard the file to try again?").arg(apps.at(id)->name()).arg(apps.at(id)->size()).arg(_updateFile.size()),
226 QMessageBox::Discard, QMessageBox::Ignore) == QMessageBox::Discard) {
227 _updateFile.remove();
228 }
229 }
230 // In the unlikely event that we missed that we had already downloaded it
231 // Maybe the user copied the relevant files in to a new folder during download?
232 if (_updateFile.size() == apps.at(id)->size()) {
233 size += _updateFile.size();
234 _updateFile.rename(baseDir + "/" + apps.at(id)->name());
235 completedFile();
236 return;
237 }
238 // It is possible that it already exists and, in this case, we would want to resume
239 if (_updateFile.size() > 0) {
240 size += _updateFile.size();
241 curSize += _updateFile.size();
242 request.setRawHeader("Range", QString("bytes=%1-").arg(_updateFile.size()).toLatin1());
243 }
244 _updateFile.open(QIODevice::WriteOnly | QIODevice::Append);
245 QNetworkReply* replydl = _manager->get(request);
246
247 connect(replydl, &QNetworkReply::readyRead, [=]() {
248 if (!running) {
249 replydl->abort();
250 replydl->deleteLater();
251 return;
252 }
253
254 QByteArray data = replydl->readAll();
255 // Is this our first receive?
256 if (size == 0)
257 {
258 if (data.startsWith("<?xml")) {
259 QMessageBox::critical(nullptr, "Error", "You are restricted from downloading this file.");
260 replydl->abort();
261 replydl->deleteLater();
262 reset();
263 return;
264 }
265 }
266 progressSize(data.size());
267 _updateFile.write(data);
268 });
269 connect(replydl, &QNetworkReply::finished, [=]() {
270 replydl->deleteLater();
271
272 // Then why are we here?
273 if (!running)
274 return;
275
276 // This should always match otherwise I'm pretty sure something bad happened
277 if (_updateFile.size() == apps.at(id)->size())
278 _updateFile.rename(baseDir + "/" + apps.at(id)->name());
279 else {
280 if (QMessageBox::warning(nullptr, "Issue",
281 QString("Expected filesize of %1 did not match (Expected %2, Received %3). Ignore the warning or discard the file to try again?").arg(apps.at(id)->name()).arg(apps.at(id)->size()).arg(_updateFile.size()),
282 QMessageBox::Discard, QMessageBox::Ignore) == QMessageBox::Discard)
283 {
284 // Discard and try again
285 size -= _updateFile.size();
286 _updateFile.close();
287 _updateFile.remove();
288 downloadNextFile();
289 return;
290 }
291 // Pretend like that didn't happen
292 }
293
294 completedFile();
295 });
296 QObject::connect(replydl, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [=]() {
297 replydl->deleteLater();
298 reset();
299 if (replydl->error() == 5)
300 return; // User cancelled
301
302 qDebug() << "DL Error: " << replydl->error() << replydl->errorString();
303 });
304 }
305
306 void completedFile() {
307 if (nextFile())
308 {
309 downloadNextFile();
310 } else {
311 /*if (size != totalSize)
312 QMessageBox::information(NULL, "Warning", QString("Your update completed successfully.\n"
313 "However, the update size does not match the download size. This is probably just be a bug that you can ignore.\n"
314 "Downloaded: %1\n"
315 "Expected: %2")
316 .arg(size)
317 .arg(totalSize));*/
318
319 QDesktopServices::openUrl(QUrl(QFileInfo(_updateFile).absolutePath()));
320 reset();
321 }
322 }
323
324 void setApps(QList<Apps*> newApps, QString& version) {
325 baseDir = getSaveDir() + "/" + version;
326
327 // Check which apps user wanted
328 foreach (Apps* newApp, newApps) {
329 if (!newApp->isMarked())
330 continue;
331 // We have to verify OS/Radio first
332 if (newApp->type() == "application") {
333 // Check which apps user has already downloaded
334 QFileInfo fileInfo(baseDir + "/" + newApp->name());
335 if (fileInfo.exists() && fileInfo.size() == newApp->size())
336 continue;
337 }
338 apps.append(new Apps(newApp, this));
339 totalSize += newApp->size();
340 }
341
342 maxId = apps.count();
343 nextFile(0);
344 emit appsChanged();
345 }
346
347 QString getName(int i = CURR_FILE) {
348 if (i == CURR_FILE)
349 i = id;
350 if (i >= 0 && i < maxId)
351 return apps[i]->friendlyName();
352 else
353 return "";
354 }
355
356 QString getUrl(int i = CURR_FILE) {
357 if (i == CURR_FILE)
358 i = id;
359 if (i >= 0 && i < maxId)
360 return apps[i]->url();
361 else
362 return "";
363 }
364
365 int getSize(int i = CURR_FILE) {
366 if (i == CURR_FILE)
367 i = id;
368 if (i >= 0 && i < maxId)
369 return apps[i]->size();
370 else
371 return 0;
372 }
373 void progressSize(qint64 bytes) {
374 size += bytes;
375 curSize += bytes;
376 curProgress = 100*curSize / apps.at(id)->size();
377 if (totalSize == 0)
378 progress = 0;
379 else
380 progress = 100*size / totalSize;
381 emit sizeChanged();
382 }
383
384 bool nextFile(int i = CURR_FILE) {
385 curSize = 0;
386 if (i == CURR_FILE)
387 id++;
388 else
389 id = i;
390
391 emit idChanged();
392
393 return (id < maxId);
394 }
395
396 QString baseDir;
397 QList<Apps*> apps;
398 int id, maxId;
399 int progress, curProgress;
400 qint64 curSize, size, totalSize;
401 bool starting;
402 qint16 toVerify;
403 bool running;
404 signals:
405 void idChanged();
406 void sizeChanged();
407 void appsChanged();
408 void verifyingChanged();
409 private:
410 QFile _updateFile;
411 QNetworkAccessManager* _manager;
412 };