-
Notifications
You must be signed in to change notification settings - Fork 18
/
installer.cpp
635 lines (532 loc) · 20.1 KB
/
installer.cpp
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#include "installer.h"
#include "ui_installer.h"
#include <QDebug>
#include <QString>
#include <QFile>
#include <QFileDialog>
#include <iostream>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QMessageBox>
#include <QThread>
#include <QPlainTextEdit>
#if defined(Q_OS_WIN)
#include "diskwriter_windows.h"
#include "deviceenumerator_windows.h"
#include "confighandler_windows.h"
#elif defined(Q_OS_UNIX)
#include "diskwriter_unix.h"
#include "deviceenumerator_unix.h"
#include "confighandler_unix.h"
#endif
#include "simplejsonparser.h"
const QString Installer::m_serverUrl = "updater.rasplex.com";
//const QString Installer::m_serverUrl = "localhost:8080"; // for testing
// TODO: Get chunk size from server, or whatever
#define CHUNKSIZE 1*1024*1024
Installer::Installer(QWidget *parent) :
QDialog(parent),
ui(new Ui::Installer),
manager(new DownloadManager(this)),
state(STATE_IDLE),
bytesDownloaded(0),
imageHash(QCryptographicHash::Md5),
settings("RasPlex", "RasPlex Installer")
{
ui->setupUi(this);
#if defined(Q_OS_WIN)
diskWriter = new DiskWriter_windows();
devEnumerator = new DeviceEnumerator_windows();
configHandler = new ConfigHandler_windows();
#elif defined(Q_OS_UNIX)
diskWriter = new DiskWriter_unix();
devEnumerator = new DeviceEnumerator_unix();
configHandler = new ConfigHandler_unix();
#endif
diskWriterThread = new QThread(this);
diskWriter->moveToThread(diskWriterThread);
connect(diskWriterThread, SIGNAL(finished()), diskWriter, SLOT(deleteLater()));
connect(this, SIGNAL(proceedToWriteImageToDevice(QString,QString)),
diskWriter, SLOT(writeCompressedImageToRemovableDevice(QString,QString)));
connect(diskWriter, SIGNAL(bytesWritten(int)), ui->flashProgressBar, SLOT(setValue(int)));
connect(diskWriter, SIGNAL(syncing()), this, SLOT(writingSyncing()));
connect(diskWriter, SIGNAL(finished()), this, SLOT(writingFinished()));
connect(diskWriter, SIGNAL(error(QString)), this, SLOT(reset(QString)));
diskWriterThread->start();
connect(ui->refreshRemovablesButton,SIGNAL(clicked()),this,SLOT(refreshRemovablesList()));
refreshRemovablesList();
connect(manager, SIGNAL(downloadComplete(QByteArray)), this, SLOT(handleFinishedDownload(QByteArray)));
connect(manager, SIGNAL(partialData(QByteArray,qlonglong)),
this, SLOT(handlePartialData(QByteArray,qlonglong)));
connect(ui->linksButton, SIGNAL(clicked()), this, SLOT(updateDevices()));
connect(ui->downloadButton, SIGNAL(clicked()), this, SLOT(downloadImage()));
connect(ui->cancelDownloadButton, SIGNAL(clicked()), this, SLOT(reset()));
connect(ui->cancelDownloadButton, SIGNAL(clicked()), this, SLOT(resetProgressBars()));
connect(ui->cancelDownloadButton, SIGNAL(clicked()), manager, SLOT(cancelDownload()));
connect(ui->cancelFlashButton, SIGNAL(clicked()), this, SLOT(reset()));
connect(ui->cancelFlashButton, SIGNAL(clicked()), this, SLOT(resetProgressBars()));
connect(ui->cancelFlashButton, SIGNAL(clicked()), diskWriter, SLOT(cancelWrite()), Qt::DirectConnection) ;
connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(getImageFileNameFromUser()));
connect(ui->writeButton, SIGNAL(clicked()), this, SLOT(writeImageToDevice()));
connect(ui->hdmiOutputButton, SIGNAL(clicked()), this, SLOT(selectVideoOutput()));
connect(ui->sdtvOutputButton, SIGNAL(clicked()), this, SLOT(selectVideoOutput()));
connect(ui->sdtvMode_0, SIGNAL(clicked()), this, SLOT(selectVideoOutput()));
connect(ui->sdtvMode_1, SIGNAL(clicked()), this, SLOT(selectVideoOutput()));
connect(ui->sdtvMode_2, SIGNAL(clicked()), this, SLOT(selectVideoOutput()));
connect(ui->sdtvMode_3, SIGNAL(clicked()), this, SLOT(selectVideoOutput()));
connect(ui->deviceSelectBox, SIGNAL(currentIndexChanged(int)), this, SLOT(getDeviceReleases(int)));
connect(ui->releaseLinks, SIGNAL(currentIndexChanged(int)), ui->releaseNotes, SLOT(setCurrentIndex(int)));
connect(ui->releaseLinks, SIGNAL(currentIndexChanged(QString)), this, SLOT(savePreferredReleaseVersion(QString)));
connect(ui->removableDevicesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(savePreferredRemovableDevice(int)));
ui->videoGroupBox->setVisible(configHandler->implemented());
adjustSize();
ui->hdmiOutputButton->setChecked(true);
setImageFileName("");
ui->writeButton->setEnabled(false);
updateDevices();
}
Installer::~Installer()
{
delete ui;
diskWriter->cancelWrite();
diskWriterThread->quit();
diskWriterThread->wait();
delete diskWriterThread;
delete devEnumerator;
delete configHandler;
}
void Installer::refreshRemovablesList()
{
qDebug() << "Refreshing removable devices list";
QVariant previouslySelectedDevice;
if (ui->removableDevicesComboBox->count() == 0) {
previouslySelectedDevice = settings.value("preferred/removableDevice");
}
else {
previouslySelectedDevice = ui->removableDevicesComboBox->currentText();
}
ui->removableDevicesComboBox->clear();
QStringList devNames = devEnumerator->getRemovableDeviceNames();
QStringList friendlyNames = devEnumerator->getUserFriendlyNames(devNames);
for (int i = 0; i < devNames.size(); i++) {
ui->removableDevicesComboBox->addItem(friendlyNames[i], devNames[i]);
}
int idx = ui->removableDevicesComboBox->findData(previouslySelectedDevice,
Qt::UserRole,
Qt::MatchFixedString);
if (idx >= 0) {
ui->removableDevicesComboBox->setCurrentIndex(idx);
} else {
ui->removableDevicesComboBox->setCurrentIndex(ui->removableDevicesComboBox->count()-1);
}
}
void Installer::parseAndSetSupportedDevices(const QByteArray &data)
{
qDebug() << "Devices:" << data;
SimpleJsonParser parser(data);
QString previouslySelectedDevice;
if (ui->deviceSelectBox->count() == 0) {
previouslySelectedDevice = settings.value("preferred/device").toString();
}
else {
previouslySelectedDevice = ui->deviceSelectBox->currentText();
}
ui->deviceSelectBox->clear();
JsonArray devices = parser.getJsonArray();
for (JsonArray::const_iterator it = devices.constBegin();
it != devices.constEnd(); it++) {
QString deviceName = (*it)["name"];
QString deviceId = (*it)["id"];
ui->deviceSelectBox->insertItem(0, deviceName ,deviceId);
}
int idx = ui->deviceSelectBox->findText(previouslySelectedDevice,
Qt::MatchFixedString);
if (idx >= 0) {
ui->deviceSelectBox->setCurrentIndex(idx);
}
settings.setValue("preferred/device", ui->deviceSelectBox->currentText());
getDeviceReleases(ui->deviceSelectBox->currentIndex());
}
void Installer::parseAndSetLinks(const QByteArray &data)
{
SimpleJsonParser parser(data);
qDebug()<< "Links:" << data;
QString previouslySelectedRelease;
if (ui->releaseLinks->count() == 0) {
previouslySelectedRelease = settings.value("preferred/release").toString();
}
else {
previouslySelectedRelease = ui->releaseLinks->currentText();
}
ui->releaseLinks->clear();
/* Clear all release notes */
while (ui->releaseNotes->count()) {
QWidget* widget = ui->releaseNotes->widget(0);
ui->releaseNotes->removeWidget(widget);
widget->deleteLater();
}
JsonArray releases = parser.getJsonArray();
for (JsonArray::const_iterator it = releases.constBegin();
it != releases.constEnd(); it++) {
QString version = (*it)["version"];
QString url = (*it)["install_url"];
QString notes = (*it)["notes"];
QString localchecksum = (*it)["install_sum"];
checksumMap[version] = localchecksum;
ui->releaseLinks->insertItem(0, version, url);
/* Add release note */
QPlainTextEdit* releaseNotesEdit = new QPlainTextEdit(notes);
releaseNotesEdit->setReadOnly(true);
ui->releaseNotes->insertWidget(0, releaseNotesEdit);
}
int idx = ui->releaseLinks->findText(previouslySelectedRelease,
Qt::MatchFixedString);
if (idx >= 0) {
ui->releaseLinks->setCurrentIndex(idx);
ui->releaseNotes->setCurrentIndex(idx);
}
reset();
}
void Installer::reset(const QString &message)
{
state = STATE_IDLE;
bytesDownloaded = 0;
if (imageFile.isOpen()) {
imageFile.close();
}
ui->deviceSelectBox->blockSignals(false);
ui->deviceSelectBox->setEnabled(true);
ui->releaseLinks->blockSignals(false);
ui->releaseLinks->setEnabled(true);
ui->linksButton->setEnabled(true);
ui->downloadButton->setEnabled(true);
ui->writeButton->setEnabled( !ui->fileNameLabel->text().isEmpty());
ui->loadButton->setEnabled(true);
ui->hdmiOutputButton->setEnabled(true);
ui->sdtvOutputButton->setEnabled(false);
ui->cancelDownloadButton->setEnabled(false);
ui->cancelFlashButton->setEnabled(false);
ui->refreshRemovablesButton->setEnabled(true);
ui->removableDevicesComboBox->setEnabled(true);
ui->messageBar->setText(message);
}
void Installer::resetProgressBars()
{
ui->downloadProgressBar->setValue(0);
ui->flashProgressBar->setValue(0);
}
void Installer::savePreferredReleaseVersion(const QString& version)
{
settings.setValue("preferred/release", version);
}
void Installer::savePreferredRemovableDevice(int idx)
{
settings.setValue("preferred/removableDevice", ui->removableDevicesComboBox->itemData(idx).toString());
}
void Installer::disableControls()
{
ui->deviceSelectBox->setEnabled(false);
ui->deviceSelectBox->blockSignals(true);
ui->releaseLinks->setEnabled(false);
ui->releaseLinks->blockSignals(true);
ui->linksButton->setEnabled(false);
ui->downloadButton->setEnabled(false);
ui->writeButton->setEnabled(false);
ui->loadButton->setEnabled(false);
ui->hdmiOutputButton->setEnabled(false);
ui->sdtvOutputButton->setEnabled(false);
ui->refreshRemovablesButton->setEnabled(false);
ui->removableDevicesComboBox->setEnabled(false);
}
bool Installer::isChecksumValid()
{
QByteArray referenceSum, downloadSum;
QCryptographicHash c(QCryptographicHash::Md5);
// Calculate the md5 sum of the downloaded file
// TODO: Calculate sum as we download (make it work)
imageFile.open(QFile::ReadOnly);
while (!imageFile.atEnd()) {
c.addData(imageFile.read(4096));
}
downloadSum = c.result().toHex();
imageFile.close();
qDebug() << selectedVersion;
checksum = checksumMap[selectedVersion];
qDebug() << checksum;
if (checksum.isEmpty() || downloadSum != checksum.toUtf8()) {
qDebug() << "checksum:" << checksum.toUtf8();
qDebug() << "downloadsum:" << downloadSum;
return false;
}
return true;
}
// From http://www.gamedev.net/topic/591402-gzip-uncompressed-file-size/
// Might not be portable!
unsigned int Installer::getUncompressedImageSize()
{
FILE *file;
unsigned int len;
unsigned char bufSize[4];
unsigned int fileSize;
file = fopen(imageFileName.toStdString().c_str(), "rb");
if (file == NULL)
return 0;
if (fseek(file, -4, SEEK_END) != 0)
return 0;
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
fileSize = (unsigned int) ((bufSize[3] << 24) | (bufSize[2] << 16) | (bufSize[1] << 8) | bufSize[0]);
qDebug() << "Uncompressed FileSize:" << fileSize;
fclose(file);
return fileSize;
}
void Installer::setImageFileName(QString filename)
{
if (imageFile.isOpen()) {
qDebug() << "Tried to change filename while imageFile was open!";
return;
}
imageFileName = filename;
imageFile.setFileName(imageFileName);
/* Remove full path for display */
int idx = filename.lastIndexOf('/');
if (idx > 0) {
filename.remove(0, idx+1);
}
ui->fileNameLabel->setText(filename);
}
QString Installer::getDefaultSaveDir()
{
static QString defaultDir;
if (defaultDir.isEmpty()) {
defaultDir = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
if (defaultDir.isEmpty()) {
defaultDir = QDir::homePath();
}
}
return defaultDir;
}
void Installer::handleFinishedDownload(const QByteArray &data)
{
switch (state) {
case STATE_GET_SUPPORTED_DEVICES:
parseAndSetSupportedDevices(data);
break;
case STATE_GETTING_LINKS:
parseAndSetLinks(data);
break;
case STATE_GETTING_URL:{
/* This should be it! */
downloadUrl.append(data);
downloadUrl = downloadUrl.trimmed();
qDebug() << "Got url" << downloadUrl;
int idx = ui->releaseLinks->findData(downloadUrl);
if (idx >= 0) {
ui->releaseLinks->setCurrentIndex(idx);
ui->releaseNotes->setCurrentIndex(idx);
}
reset();
ui->downloadButton->click();
break;
}
case STATE_DOWNLOADING_IMAGE:
break;
default:
break;
}
}
void Installer::handlePartialData(const QByteArray &data, qlonglong total)
{
if (state == STATE_GETTING_URL) {
downloadUrl.append(data);
return;
}
if (state != STATE_DOWNLOADING_IMAGE) {
/* What to do? */
qDebug() << "Got unexpected data!";
return;
}
imageFile.write(data);
imageHash.addData(data);
bytesDownloaded += data.size();
// Update progress bar
ui->downloadProgressBar->setMaximum(total);
ui->downloadProgressBar->setValue(bytesDownloaded);
qDebug() << bytesDownloaded << "/" << total << "=" << (qreal)bytesDownloaded/total * 100 << "%";
if (bytesDownloaded == total) {
imageFile.close();
ui->messageBar->setText("Download complete, verifying checksum...");
if (isChecksumValid()) {
reset("Download complete, verifying checksum... Done!");
}
else {
reset("Wrong md5 sum! Please re-download.");
}
}
}
void Installer::updateDevices()
{
state = STATE_GET_SUPPORTED_DEVICES;
disableControls();
ui->cancelDownloadButton->setEnabled(true);
ui->messageBar->setText("Getting supported RasPlex devices");
QUrl url("http://"+m_serverUrl+"/devices");
manager->get(url);
}
void Installer::getDeviceReleases(int index)
{
state = STATE_GETTING_LINKS;
disableControls();
ui->cancelDownloadButton->setEnabled(true);
#if defined( Q_OS_WIN)
QString PLATFORM = "windows";
#elif defined(Q_OS_LINUX)
QString PLATFORM = "linux";
#elif defined(Q_OS_MAC)
QString PLATFORM = "osx";
#endif
QString deviceName = ui->deviceSelectBox->itemText(index);
settings.setValue("preferred/device", deviceName);
ui->messageBar->setText("Getting releases for "+deviceName);
QString deviceId = ui->deviceSelectBox->itemData(index).toString();
QUrl url("http://"+m_serverUrl+"/install?platform="+PLATFORM+"&device="+deviceId);
manager->get(url);
}
void Installer::downloadImage()
{
state = STATE_DOWNLOADING_IMAGE;
disableControls();
ui->cancelDownloadButton->setEnabled(true);
selectedVersion = ui->releaseLinks->itemText(ui->releaseLinks->currentIndex());
QUrl url = ui->releaseLinks->itemData(ui->releaseLinks->currentIndex()).toUrl();
qDebug() << "Downloading" << url;
// Handle special releases
if ( selectedVersion == "bleeding" ||
selectedVersion == "current" ||
selectedVersion == "experimental") {
ui->messageBar->setText("Getting URL");
downloadUrl.clear();
state = STATE_GETTING_URL;
}
else {
// Try to find file name in url
QString newFileName = url.toString().section('/',-1,-1);
QString saveDir = settings.value("preferred/savedir", getDefaultSaveDir()).toString();
qDebug() << saveDir + "/" + newFileName;
saveDir = QFileDialog::getExistingDirectory(this, tr("Directory To Store Image"),
saveDir,
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
newFileName = saveDir + QDir::separator() + newFileName;
if (!newFileName.endsWith(".img.gz")) {
newFileName += ".img.gz";
}
if (saveDir.isEmpty() || newFileName.isEmpty()) {
reset();
return;
}
qDebug() << "Downloading to" << newFileName;
if (imageFile.isOpen())
imageFile.close();
setImageFileName(newFileName);
if (!imageFile.open(QFile::WriteOnly | QFile::Truncate)) {
reset("Failed to open file for writing!");
return;
}
ui->messageBar->setText("Downloading image... please be patient.");
ui->cancelDownloadButton->setEnabled(true);
imageHash.reset();
settings.setValue("preferred/savedir", saveDir);
savePreferredReleaseVersion(selectedVersion);
}
manager->get(url);
}
void Installer::getImageFileNameFromUser()
{
QString loadDir = settings.value("preferred/savedir", getDefaultSaveDir()).toString();
QString filename = QFileDialog::getOpenFileName(this, "Open rasplex image", loadDir,
"Compressed raw image (*img.gz)");
if (filename.isEmpty()) {
return;
}
setImageFileName(filename);
ui->writeButton->setEnabled(true);
qDebug() << imageFileName;
}
void Installer::writeImageToDevice()
{
disableControls();
ui->cancelFlashButton->setEnabled(true);
int idx = ui->removableDevicesComboBox->currentIndex();
QString destination = ui->removableDevicesComboBox->itemData(idx).toString();
QMessageBox::StandardButton ok = QMessageBox::warning(this, tr("Confirm write"),
"Are you sure you want to write to?\n"
+ destination +
"\n\nThis might destroy your data!",
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ok != QMessageBox::Yes) {
reset();
return;
}
if (destination.isNull()) {
reset();
return;
}
ui->flashProgressBar->setValue(0);
ui->flashProgressBar->setMaximum(getUncompressedImageSize());
ui->messageBar->setText("Writing image to "+destination);
// DiskWriter will re-open the image file.
if (imageFile.isOpen()) {
imageFile.close();
}
state = STATE_WRITING_IMAGE;
emit proceedToWriteImageToDevice(imageFileName, destination);
}
void Installer::selectVideoOutput()
{
if (!configHandler->implemented()) {
return;
}
int idx = ui->removableDevicesComboBox->currentIndex();
if (!configHandler->mount(ui->removableDevicesComboBox->itemData(idx).toString())) {
return;
}
/*
if (ui->hdmiOutputButton->isChecked()) {
configHandler->changeSetting("hdmi_force_hotplug", 1);
}
else {
configHandler->changeSetting("hdmi_force_hotplug", 0);
if (ui->sdtvMode_0->isChecked()) {
configHandler->changeSetting("sdtv_mode", 0);
} else if (ui->sdtvMode_1->isChecked()) {
configHandler->changeSetting("sdtv_mode", 1);
} else if (ui->sdtvMode_2->isChecked()) {
configHandler->changeSetting("sdtv_mode", 2);
} else if (ui->sdtvMode_3->isChecked()) {
configHandler->changeSetting("sdtv_mode", 3);
} else {
// Shouldn't be possible!
}
}
*/
ui->messageBar->setText("Settings changed.");
configHandler->unMount();
}
void Installer::writingFinished()
{
// Make sure the config is updated
selectVideoOutput();
ui->flashProgressBar->setValue(ui->flashProgressBar->maximum());
reset("Writing done!");
}
void Installer::writingSyncing()
{
if (state == STATE_WRITING_IMAGE)
ui->messageBar->setText("Syncing file system.");
}