Small build script update.
[simple-x264-launcher.git] / src / win_updater.cpp
blobce9a1758d7098f13581be83b524c62e1df251491
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2017 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "win_updater.h"
23 #include "UIC_win_updater.h"
25 //Internal
26 #include "global.h"
27 #include "model_sysinfo.h"
29 //MUtils
30 #include <MUtils/UpdateChecker.h>
31 #include <MUtils/Hash.h>
32 #include <MUtils/GUI.h>
33 #include <MUtils/OSSupport.h>
34 #include <MUtils/Exception.h>
36 //Qt
37 #include <QMovie>
38 #include <QCloseEvent>
39 #include <QTimer>
40 #include <QMessageBox>
41 #include <QDesktopServices>
42 #include <QUrl>
43 #include <QProcess>
44 #include <QFileInfo>
45 #include <QDir>
46 #include <QMap>
48 ///////////////////////////////////////////////////////////////////////////////
50 static const char *const DIGEST_KEY = "~Dv/bW3/7t>6?RXVwkaZk-hmS0#O4JS/5YQAO>\\8hvr0B~7[n!X~KMYruemu:MDq";
52 const UpdaterDialog::binary_t UpdaterDialog::BINARIES[] =
54 { "wget.exe", "35d70bf8a1799956b5de3975ff99088a4444a2d17202059afb63949b297e2cc81e5e49e2b95df1c4e26b49ab7430399c293bf805a0b250d686c6f4dd994a0764", 1 },
55 { "netc.exe", "2e890533473134e074d65e1670c4212a06e4f685c4ee202593b0427defdf2f01e4d22cf7b48855436f1c57109c131f3469daa1a523a5a05fc9d23fb41d2e6ea9", 1 },
56 { "gpgv.exe", "a8d4d1702e5fb1eee5a2c22fdaf255816a9199ae48142aeec1c8ce16bbcf61d6d634f1e769e62d05cf52c204ba2611f09c9bb661bc6688b937749d478af3e47d", 1 },
57 { "gpgv.gpg", "1a2f528e551b9abfb064f08674fdd421d3abe403469ddfee2beafd007775a6c684212a6274dc2b41a0b20dd5c2200021c91320e737f7a90b2ac5a40a6221d93f", 0 },
58 { "wupd.exe", "c7fe72259ae781889a18f688321275e3bae39d75fb96c9c650446e177cb3af3d3ea84db2c1590e44bc2440b2ea79f9684e3a14e47e57e6083ec6f98c5bf72a73", 1 },
59 { NULL, NULL, 0 }
62 #define UPDATE_TEXT(N, TEXT) ui->label_phase##N->setText((TEXT))
63 #define UPDATE_ICON(N, ICON) ui->icon_phase##N->setPixmap(QIcon(":/buttons/" ICON ".png").pixmap(16, 16))
65 #define SHOW_ANIMATION(FLAG) do \
66 { \
67 ui->frameAnimation->setVisible((FLAG)); \
68 ui->labelInfo->setVisible(!(FLAG)); \
69 ui->labelUrl->setVisible(!(FLAG)); \
70 ui->labelBuildNo->setVisible(!(FLAG)); \
71 if((FLAG)) m_animator->start(); else m_animator->stop(); \
72 } \
73 while(0)
76 ///////////////////////////////////////////////////////////////////////////////
77 // Constructor & Destructor
78 ///////////////////////////////////////////////////////////////////////////////
80 UpdaterDialog::UpdaterDialog(QWidget *parent, const SysinfoModel *sysinfo, const char *const updateUrl)
82 QDialog(parent),
83 ui(new Ui::UpdaterDialog()),
84 m_sysinfo(sysinfo),
85 m_updateUrl(updateUrl),
86 m_status(MUtils::UpdateChecker::UpdateStatus_NotStartedYet),
87 m_thread(NULL),
88 m_updaterProcess(NULL),
89 m_success(false),
90 m_firstShow(true)
92 //Init the dialog, from the .ui file
93 ui->setupUi(this);
94 setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
96 //Fix size
97 setFixedSize(size());
99 //Enable buttons
100 connect(ui->buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
101 connect(ui->buttonDownload, SIGNAL(clicked()), this, SLOT(installUpdate()));
102 connect(ui->buttonRetry, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
104 //Enable info label
105 connect(ui->labelUrl, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString)));
107 //Init animation
108 m_animator.reset(new QMovie(":/images/loading.gif"));
109 ui->labelLoadingCenter->setMovie(m_animator.data());
111 //Init buttons
112 ui->buttonCancel->setEnabled(false);
113 ui->buttonRetry->hide();
114 ui->buttonDownload->hide();
116 //Start animation
117 SHOW_ANIMATION(true);
120 UpdaterDialog::~UpdaterDialog(void)
122 if(!m_thread.isNull())
124 if(!m_thread->wait(5000))
126 m_thread->terminate();
127 m_thread->wait();
131 cleanFiles();
132 delete ui;
135 ///////////////////////////////////////////////////////////////////////////////
136 // Public Functions
137 ///////////////////////////////////////////////////////////////////////////////
139 /*None yet*/
141 ///////////////////////////////////////////////////////////////////////////////
142 // Events
143 ///////////////////////////////////////////////////////////////////////////////
145 bool UpdaterDialog::event(QEvent *e)
147 if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
149 MUtils::GUI::bring_to_front(m_updaterProcess);
151 return QDialog::event(e);
154 void UpdaterDialog::showEvent(QShowEvent *event)
156 if(m_firstShow)
158 m_firstShow = false;
159 QTimer::singleShot(16, this, SLOT(initUpdate()));
163 void UpdaterDialog::closeEvent(QCloseEvent *e)
165 if(!ui->buttonCancel->isEnabled())
167 e->ignore();
171 void UpdaterDialog::keyPressEvent(QKeyEvent *event)
173 if(event->key() == Qt::Key_F11)
175 const QString logFilePath = MUtils::make_temp_file(MUtils::temp_folder(), "log", true);
176 if (!logFilePath.isEmpty())
178 QFile logFile(logFilePath);
179 if (logFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
181 logFile.write("\xEF\xBB\xBF");
182 for (QStringList::ConstIterator iter = m_logFile.constBegin(); iter != m_logFile.constEnd(); iter++)
184 logFile.write(iter->toUtf8());
185 logFile.write("\r\n");
187 logFile.close();
188 QDesktopServices::openUrl(QUrl::fromLocalFile(logFile.fileName()));
194 ///////////////////////////////////////////////////////////////////////////////
195 // Slots
196 ///////////////////////////////////////////////////////////////////////////////
198 void UpdaterDialog::initUpdate(void)
200 //Clean up files from previous attempt
201 if(!m_binaries.isEmpty())
203 cleanFiles();
206 //Check binary files
207 if(!checkBinaries())
209 ui->buttonCancel->setEnabled(true);
210 const QString message = QString("%1<br><br><nobr><a href=\"%2\">%3</a></nobr><br>").arg(tr("At least one file required by the web-update tool is missing or corrupted.<br>Please re-install this application and then try again!"), QString::fromLatin1(m_updateUrl), QString::fromLatin1(m_updateUrl).replace("-", "&minus;"));
211 if(QMessageBox::critical(this, tr("File Error"), message, tr("Download Latest Version"), tr("Discard")) == 0)
213 QDesktopServices::openUrl(QUrl(QString::fromLatin1(m_updateUrl)));
215 close(); return;
218 //Make sure user does have admin access
219 if(!MUtils::OS::user_is_admin())
221 qWarning("User is not in the \"admin\" group, cannot update!");
222 QString message;
223 message += QString("<nobr>%1</nobr><br>").arg(tr("Sorry, but only users in the \"Administrators\" group can install updates."));
224 message += QString("<nobr>%1</nobr>").arg(tr("Please start application from an administrator account and try again!"));
225 if(QMessageBox::critical(this, this->windowTitle(), message, tr("Discard"), tr("Ignore")) != 1)
227 ui->buttonCancel->setEnabled(true);
228 close(); return;
232 //Create and setup thread
233 if(!m_thread)
235 m_thread.reset(new MUtils::UpdateChecker(m_binaries.value("wget.exe"), m_binaries.value("netc.exe"), m_binaries.value("gpgv.exe"), m_binaries.value("gpgv.gpg"), "Simple x264 Launcher", x264_version_build(), false));
236 connect(m_thread.data(), SIGNAL(statusChanged(int)), this, SLOT(threadStatusChanged(int)));
237 connect(m_thread.data(), SIGNAL(finished()), this, SLOT(threadFinished()));
238 connect(m_thread.data(), SIGNAL(terminated()), this, SLOT(threadFinished()));
239 connect(m_thread.data(), SIGNAL(messageLogged(QString)), this, SLOT(threadMessageLogged(QString)));
242 //Begin updater run
243 QTimer::singleShot(16, this, SLOT(checkForUpdates()));
246 void UpdaterDialog::checkForUpdates(void)
248 if((!m_thread) || m_thread->isRunning())
250 qWarning("Update in progress, cannot check for updates now!");
253 //Clear texts
254 ui->retranslateUi(this);
255 ui->labelBuildNo->setText(tr("Installed build is #%1 | Latest build is #%2").arg(QString::number(x264_version_build()), tr("N/A")));
257 //Init buttons
258 ui->buttonCancel->setEnabled(false);
259 ui->buttonRetry->hide();
260 ui->buttonDownload->hide();
262 //Hide labels
263 ui->labelInfo->hide();
264 ui->labelUrl->hide();
266 //Update status
267 threadStatusChanged(MUtils::UpdateChecker::UpdateStatus_NotStartedYet);
269 //Start animation
270 SHOW_ANIMATION(true);
272 //Update cursor
273 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
274 QApplication::setOverrideCursor(Qt::WaitCursor);
276 //Clear log
277 m_logFile.clear();
279 //Start the updater thread
280 QTimer::singleShot(250, m_thread.data(), SLOT(start()));
283 void UpdaterDialog::threadStatusChanged(int status)
285 switch(m_status = status)
287 case MUtils::UpdateChecker::UpdateStatus_NotStartedYet:
288 UPDATE_ICON(1, "clock");
289 UPDATE_ICON(2, "clock");
290 UPDATE_ICON(3, "clock");
291 break;
292 case MUtils::UpdateChecker::UpdateStatus_CheckingConnection:
293 UPDATE_ICON(1, "play");
294 break;
295 case MUtils::UpdateChecker::UpdateStatus_FetchingUpdates:
296 UPDATE_ICON(1, "shield_green");
297 UPDATE_TEXT(1, tr("Internet connection is working."));
298 UPDATE_ICON(2, "play");
299 break;
300 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection:
301 UPDATE_ICON(1, "shield_error");
302 UPDATE_TEXT(1, tr("Computer is currently offline!"));
303 UPDATE_ICON(2, "shield_grey");
304 UPDATE_ICON(3, "shield_grey");
305 break;
306 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed:
307 UPDATE_ICON(1, "shield_error");
308 UPDATE_TEXT(1, tr("Internet connectivity test failed!"));
309 UPDATE_ICON(2, "shield_grey");
310 UPDATE_ICON(3, "shield_grey");
311 break;
312 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo:
313 UPDATE_ICON(2, "shield_error");
314 UPDATE_TEXT(2, tr("Failed to download the update information!"));
315 UPDATE_ICON(3, "shield_grey");
316 break;
317 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
318 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
319 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
320 UPDATE_ICON(2, "shield_green");
321 UPDATE_TEXT(2, tr("Update information received successfully."));
322 UPDATE_ICON(3, "play");
323 break;
324 default:
325 MUTILS_THROW("Unknown status code!");
329 void UpdaterDialog::threadFinished(void)
331 m_success = m_thread->getSuccess();
332 QTimer::singleShot((m_success ? 1000 : 0), this, SLOT(updateFinished()));
335 void UpdaterDialog::updateFinished(void)
337 //Restore cursor
338 QApplication::restoreOverrideCursor();
340 //If update was successfull, process final updater state
341 if(m_thread->getSuccess())
343 switch(m_status)
345 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
346 UPDATE_ICON(3, "shield_exclamation");
347 UPDATE_TEXT(3, tr("A newer version is available!"));
348 ui->buttonDownload->show();
349 break;
350 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
351 UPDATE_ICON(3, "shield_green");
352 UPDATE_TEXT(3, tr("Your version is up-to-date."));
353 break;
354 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
355 UPDATE_ICON(3, "shield_blue");
356 UPDATE_TEXT(3, tr("You are using a pre-release version!"));
357 break;
358 default:
359 qWarning("Update thread succeeded with unexpected status code: %d", m_status);
363 //Show update info or retry button
364 switch(m_status)
366 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
367 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
368 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
369 SHOW_ANIMATION(false);
370 ui->labelBuildNo->setText(tr("Installed build is #%1 | Latest build is #%2").arg(QString::number(x264_version_build()), QString::number(m_thread->getUpdateInfo()->getBuildNo())));
371 ui->labelUrl->setText(QString("<a href=\"%1\">%1</a>").arg(m_thread->getUpdateInfo()->getDownloadSite()));
372 break;
373 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection:
374 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed:
375 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo:
376 m_animator->stop();
377 ui->buttonRetry->show();
378 break;
379 default:
380 qWarning("Update thread finished with unexpected status code: %d", m_status);
383 //Re-enbale cancel button
384 ui->buttonCancel->setEnabled(true);
388 void UpdaterDialog::threadMessageLogged(const QString &message)
390 m_logFile << message;
393 void UpdaterDialog::openUrl(const QString &url)
395 qDebug("Open URL: %s", url.toLatin1().constData());
396 QDesktopServices::openUrl(QUrl(url));
399 void UpdaterDialog::installUpdate(void)
401 if(!((m_thread) && m_thread->getSuccess()))
403 qWarning("Cannot download/install update at this point!");
404 return;
407 QApplication::setOverrideCursor(Qt::WaitCursor);
408 ui->buttonDownload->hide();
409 ui->buttonCancel->setEnabled(false);
410 SHOW_ANIMATION(true);
412 const MUtils::UpdateCheckerInfo *updateInfo = m_thread->getUpdateInfo();
414 QProcess process;
415 QStringList args;
416 QEventLoop loop;
418 MUtils::init_process(process, MUtils::temp_folder(), false);
420 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
421 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
423 args << QString("/Location=%1").arg(updateInfo->getDownloadAddress());
424 args << QString("/Filename=%1").arg(updateInfo->getDownloadFilename());
425 args << QString("/TicketID=%1").arg(updateInfo->getDownloadFilecode());
426 args << QString("/CheckSum=%1").arg(updateInfo->getDownloadChecksum());
427 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
428 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
429 args << QString("/AppTitle=Simple x264 Launcher (Build #%1)").arg(QString::number(updateInfo->getBuildNo()));
431 process.start(m_binaries.value("wupd.exe"), args);
432 if(!process.waitForStarted())
434 QApplication::restoreOverrideCursor();
435 SHOW_ANIMATION(false);
436 QMessageBox::critical(this, tr("Update Failed"), tr("Sorry, failed to launch web-update program!"));
437 ui->buttonDownload->show();
438 ui->buttonCancel->setEnabled(true);
439 return;
442 m_updaterProcess = MUtils::OS::process_id(&process);
443 loop.exec(QEventLoop::ExcludeUserInputEvents);
445 if(!process.waitForFinished())
447 process.kill();
448 process.waitForFinished();
451 m_updaterProcess = NULL;
452 QApplication::restoreOverrideCursor();
453 ui->buttonDownload->show();
454 ui->buttonCancel->setEnabled(true);
455 SHOW_ANIMATION(false);
457 if(process.exitCode() == 0)
459 done(READY_TO_INSTALL_UPDATE);
463 ///////////////////////////////////////////////////////////////////////////////
464 // Private Functions
465 ///////////////////////////////////////////////////////////////////////////////
467 bool UpdaterDialog::checkBinaries(void)
469 qDebug("[File Verification]");
470 m_binaries.clear();
472 //Validate hashes first
473 const QString tempPath = MUtils::temp_folder();
474 for(size_t i = 0; BINARIES[i].name; i++)
476 const QString orgName = QString::fromLatin1(BINARIES[i].name);
477 const QString binPath = QString("%1/toolset/common/%2").arg(m_sysinfo->getAppPath(), orgName);
478 const QString outPath = MUtils::make_unique_file(tempPath, QFileInfo(orgName).baseName(), QFileInfo(orgName).suffix());
479 if(!checkFileHash(binPath, BINARIES[i].hash))
481 qWarning("Verification of '%s' has failed!", MUTILS_UTF8(orgName));
482 return false;
484 if(outPath.isEmpty() || (!QFile::copy(binPath, outPath)))
486 qWarning("Copying of '%s' has failed!", MUTILS_UTF8(orgName));
487 return false;
489 QFile::setPermissions(outPath, QFile::ReadOwner);
490 m_binaries.insert(BINARIES[i].name, outPath);
491 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
494 return true;
497 bool UpdaterDialog::checkFileHash(const QString &filePath, const char *expectedHash)
499 qDebug("Checking file: %s", filePath.toUtf8().constData());
500 QScopedPointer<MUtils::Hash::Hash> checksum(MUtils::Hash::create(MUtils::Hash::HASH_BLAKE2_512, DIGEST_KEY));
501 QFile file(filePath);
502 if(file.open(QIODevice::ReadOnly))
504 checksum->update(file);
505 const QByteArray fileHash = checksum->digest();
506 if((strlen(expectedHash) != fileHash.size()) || (memcmp(fileHash.constData(), expectedHash, fileHash.size()) != 0))
508 qWarning("\nFile appears to be corrupted:\n%s\n", filePath.toUtf8().constData());
509 qWarning("Expected Hash: %s\nDetected Hash: %s\n", expectedHash, fileHash.constData());
510 return false;
512 return true;
514 else
516 qWarning("Failed to open file:\n%s\n", filePath.toUtf8().constData());
517 return false;
521 void UpdaterDialog::cleanFiles(void)
523 const QStringList keys = m_binaries.keys();
524 foreach(const QString &key, keys)
526 const QString fileName = m_binaries.value(key);
527 QFile::setPermissions(fileName, QFile::ReadOwner | QFile::WriteOwner);
528 if(!QFile::remove(fileName))
530 qWarning("Failed to remove file: %s", MUTILS_UTF8(fileName));
532 m_binaries.remove(key);