1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2018 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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"
27 #include "model_sysinfo.h"
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>
38 #include <QCloseEvent>
40 #include <QMessageBox>
41 #include <QDesktopServices>
47 #include <QElapsedTimer>
49 ///////////////////////////////////////////////////////////////////////////////
51 static const char *const DIGEST_KEY = "~Dv/bW3/7t>6?RXVwkaZk-hmS0#O4JS/5YQAO>\\8hvr0B~7[n!X~KMYruemu:MDq";
53 const UpdaterDialog::binary_t UpdaterDialog::BINARIES[] =
55 { "wget.exe", "35d70bf8a1799956b5de3975ff99088a4444a2d17202059afb63949b297e2cc81e5e49e2b95df1c4e26b49ab7430399c293bf805a0b250d686c6f4dd994a0764", 1 },
56 { "mcat.exe", "8328dbdc505e8816a5d17929678cdcbb573eca0ab107a7da66dca9a94044b404619e2fcc15f8d66950bf0c1fc3af94c31661035cbb5133a4ec721f4c4825a7c9", 1 },
57 { "gpgv.exe", "21219d89c1b5e0755264adb2484035309f486be05a15cb1b33d326badfafa3c84879cf15fa0dcc3fef1f02d5f3e581842117ea348b37a89e25674f683fcea5e7", 1 },
58 { "gpgv.gpg", "1a2f528e551b9abfb064f08674fdd421d3abe403469ddfee2beafd007775a6c684212a6274dc2b41a0b20dd5c2200021c91320e737f7a90b2ac5a40a6221d93f", 0 },
59 { "wupd.exe", "018a8d0d848407fb0cb530b4540c6f025fd4c280885becd37f83feed8aeb3af6f8e8e0d45066a36549efac7e64706ac1ef09aaa5c75ab8d12c4a70f41518a894", 1 },
63 #define UPDATE_TEXT(N, TEXT) ui->label_phase##N->setText((TEXT))
64 #define UPDATE_ICON(N, ICON) ui->icon_phase##N->setPixmap(QIcon(":/buttons/" ICON ".png").pixmap(16, 16))
66 #define SHOW_ANIMATION(FLAG) do \
68 ui->frameAnimation->setVisible((FLAG)); \
69 ui->labelInfo->setVisible(!(FLAG)); \
70 ui->labelUrl->setVisible(!(FLAG)); \
71 ui->labelBuildNo->setVisible(!(FLAG)); \
72 if((FLAG)) m_animator->start(); else m_animator->stop(); \
76 static inline QString getBin(const QMap<QString, QSharedPointer<QFile>> &binaries, const QString &nameName)
78 const QSharedPointer<QFile> file = binaries.value(nameName);
79 return file.isNull() ? QString() : file->fileName();
82 static void qFileDeleter(QFile *const file)
91 ///////////////////////////////////////////////////////////////////////////////
92 // Constructor & Destructor
93 ///////////////////////////////////////////////////////////////////////////////
95 UpdaterDialog::UpdaterDialog(QWidget *parent, const SysinfoModel *sysinfo, const char *const updateUrl)
98 ui(new Ui::UpdaterDialog()),
100 m_updateUrl(updateUrl),
101 m_status(MUtils::UpdateChecker::UpdateStatus_NotStartedYet),
103 m_updaterProcess(NULL),
107 //Init the dialog, from the .ui file
109 setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
112 MUtils::GUI::scale_widget(this);
113 setFixedSize(size());
116 connect(ui->buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
117 connect(ui->buttonDownload, SIGNAL(clicked()), this, SLOT(installUpdate()));
118 connect(ui->buttonRetry, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
121 connect(ui->labelUrl, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString)));
124 m_animator.reset(new QMovie(":/images/loading.gif"));
125 ui->labelLoadingCenter->setMovie(m_animator.data());
128 ui->buttonCancel->setEnabled(false);
129 ui->buttonRetry->hide();
130 ui->buttonDownload->hide();
131 ui->labelCancel->hide();
134 SHOW_ANIMATION(true);
137 UpdaterDialog::~UpdaterDialog(void)
139 if(!m_thread.isNull())
141 if(!m_thread->wait(5000))
143 m_thread->terminate();
150 ///////////////////////////////////////////////////////////////////////////////
152 ///////////////////////////////////////////////////////////////////////////////
154 bool UpdaterDialog::event(QEvent *e)
156 if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
158 MUtils::GUI::bring_to_front(m_updaterProcess);
160 return QDialog::event(e);
163 void UpdaterDialog::showEvent(QShowEvent *event)
168 QTimer::singleShot(16, this, SLOT(initUpdate()));
172 void UpdaterDialog::closeEvent(QCloseEvent *e)
174 if(!ui->buttonCancel->isEnabled())
180 void UpdaterDialog::keyPressEvent(QKeyEvent *event)
182 switch (event->key())
185 if ((!m_thread.isNull()) && m_thread->isRunning())
187 if (m_status >= MUtils::UpdateChecker::UpdateStatus_FetchingUpdates)
189 UPDATE_TEXT(2, tr("Cancellation requested..."));
193 UPDATE_TEXT(1, tr("Cancellation requested..."));
200 const QString logFilePath = MUtils::make_temp_file(MUtils::temp_folder(), "txt", true);
201 if (!logFilePath.isEmpty())
203 qWarning("Write log to: '%s'", MUTILS_UTF8(logFilePath));
204 QFile logFile(logFilePath);
205 if (logFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
207 logFile.write("\xEF\xBB\xBF");
208 for (QStringList::ConstIterator iter = m_logFile.constBegin(); iter != m_logFile.constEnd(); iter++)
210 logFile.write(iter->toUtf8());
211 logFile.write("\r\n");
214 QDesktopServices::openUrl(QUrl::fromLocalFile(logFile.fileName()));
220 QDialog::keyPressEvent(event);
224 ///////////////////////////////////////////////////////////////////////////////
226 ///////////////////////////////////////////////////////////////////////////////
228 void UpdaterDialog::initUpdate(void)
233 ui->buttonCancel->setEnabled(true);
234 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("-", "−"));
235 if(QMessageBox::critical(this, tr("File Error"), message, tr("Download Latest Version"), tr("Discard")) == 0)
237 QDesktopServices::openUrl(QUrl(QString::fromLatin1(m_updateUrl)));
243 //Make sure user does have admin access
244 if(!MUtils::OS::user_is_admin())
246 qWarning("User is not in the \"admin\" group, cannot update!");
248 message += QString("<nobr>%1</nobr><br>").arg(tr("Sorry, but only users in the \"Administrators\" group can install updates."));
249 message += QString("<nobr>%1</nobr>").arg(tr("Please start application from an administrator account and try again!"));
250 if(QMessageBox::critical(this, this->windowTitle(), message, tr("Discard"), tr("Ignore")) != 1)
252 ui->buttonCancel->setEnabled(true);
258 //Create and setup thread
261 m_thread.reset(new MUtils::UpdateChecker(getBin(m_binaries, "wget.exe"), getBin(m_binaries, "mcat.exe"), getBin(m_binaries, "gpgv.exe"), getBin(m_binaries, "gpgv.gpg"), "Simple x264 Launcher", x264_version_build(), false));
262 connect(m_thread.data(), SIGNAL(statusChanged(int)), this, SLOT(threadStatusChanged(int)));
263 connect(m_thread.data(), SIGNAL(finished()), this, SLOT(threadFinished()));
264 connect(m_thread.data(), SIGNAL(terminated()), this, SLOT(threadFinished()));
265 connect(m_thread.data(), SIGNAL(messageLogged(QString)), this, SLOT(threadMessageLogged(QString)));
269 QTimer::singleShot(16, this, SLOT(checkForUpdates()));
272 void UpdaterDialog::checkForUpdates(void)
274 if((!m_thread) || m_thread->isRunning())
276 qWarning("Update in progress, cannot check for updates now!");
280 ui->retranslateUi(this);
281 ui->labelBuildNo->setText(tr("Installed build is #%1 | Latest build is #%2").arg(QString::number(x264_version_build()), tr("N/A")));
284 ui->buttonCancel->setEnabled(false);
285 ui->buttonRetry->hide();
286 ui->buttonDownload->hide();
289 ui->labelInfo->hide();
290 ui->labelUrl->hide();
291 ui->labelCancel->show();
294 threadStatusChanged(MUtils::UpdateChecker::UpdateStatus_NotStartedYet);
297 SHOW_ANIMATION(true);
300 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
301 QApplication::setOverrideCursor(Qt::WaitCursor);
307 m_elapsed.reset(new QElapsedTimer());
310 //Start the updater thread
311 QTimer::singleShot(125, m_thread.data(), SLOT(start()));
314 void UpdaterDialog::threadStatusChanged(int status)
316 const int prevStatus = m_status;
317 switch(m_status = status)
319 case MUtils::UpdateChecker::UpdateStatus_NotStartedYet:
320 UPDATE_ICON(1, "clock");
321 UPDATE_ICON(2, "clock");
322 UPDATE_ICON(3, "clock");
324 case MUtils::UpdateChecker::UpdateStatus_CheckingConnection:
325 UPDATE_ICON(1, "play");
327 case MUtils::UpdateChecker::UpdateStatus_FetchingUpdates:
328 UPDATE_ICON(1, "shield_green");
329 UPDATE_TEXT(1, tr("Internet connection is working."));
330 UPDATE_ICON(2, "play");
332 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection:
333 UPDATE_ICON(1, "shield_error");
334 UPDATE_TEXT(1, tr("Computer is currently offline!"));
335 UPDATE_ICON(2, "shield_grey");
336 UPDATE_ICON(3, "shield_grey");
338 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed:
339 UPDATE_ICON(1, "shield_error");
340 UPDATE_TEXT(1, tr("Internet connectivity test failed!"));
341 UPDATE_ICON(2, "shield_grey");
342 UPDATE_ICON(3, "shield_grey");
344 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo:
345 UPDATE_ICON(2, "shield_error");
346 UPDATE_TEXT(2, tr("Failed to download the update information!"));
347 UPDATE_ICON(3, "shield_grey");
349 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
350 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
351 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
352 UPDATE_ICON(2, "shield_green");
353 UPDATE_TEXT(2, tr("Update information received successfully."));
354 UPDATE_ICON(3, "play");
356 case MUtils::UpdateChecker::UpdateStatus_CancelledByUser:
357 if (prevStatus >= MUtils::UpdateChecker::UpdateStatus_FetchingUpdates)
359 UPDATE_ICON(2, "shield_error");
360 UPDATE_TEXT(2, tr("Operation was cancelled by the user!"));
361 UPDATE_ICON(3, "shield_grey");
365 UPDATE_ICON(1, "shield_error");
366 UPDATE_TEXT(1, tr("Operation was cancelled by the user!"));
367 UPDATE_ICON(2, "shield_grey");
368 UPDATE_ICON(3, "shield_grey");
372 MUTILS_THROW("Unknown status code!");
376 void UpdaterDialog::threadFinished(void)
378 m_success = m_thread->getSuccess();
379 ui->labelCancel->hide();
380 QTimer::singleShot((m_success ? 500 : 0), this, SLOT(updateFinished()));
383 void UpdaterDialog::updateFinished(void)
385 //Query the timer, if available
386 if (!m_elapsed.isNull())
388 const quint64 elapsed = m_elapsed->restart();
389 qDebug("Update check completed after %.2f seconds.", double(elapsed) / 1000.0);
393 QApplication::restoreOverrideCursor();
395 //If update was successfull, process final updater state
396 if(m_thread->getSuccess())
400 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
401 UPDATE_ICON(3, "shield_exclamation");
402 UPDATE_TEXT(3, tr("A newer version is available!"));
403 ui->buttonDownload->show();
405 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
406 UPDATE_ICON(3, "shield_green");
407 UPDATE_TEXT(3, tr("Your version is up-to-date."));
409 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
410 UPDATE_ICON(3, "shield_blue");
411 UPDATE_TEXT(3, tr("You are using a pre-release version!"));
414 qWarning("Update thread succeeded with unexpected status code: %d", m_status);
418 //Show update info or retry button
421 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
422 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
423 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
424 SHOW_ANIMATION(false);
425 ui->labelBuildNo->setText(tr("Installed build is #%1 | Latest build is #%2").arg(QString::number(x264_version_build()), QString::number(m_thread->getUpdateInfo()->getBuildNo())));
426 ui->labelUrl->setText(QString("<a href=\"%1\">%1</a>").arg(m_thread->getUpdateInfo()->getDownloadSite()));
428 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection:
429 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed:
430 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo:
431 case MUtils::UpdateChecker::UpdateStatus_CancelledByUser:
433 ui->buttonRetry->show();
436 qWarning("Update thread finished with unexpected status code: %d", m_status);
439 //Re-enbale cancel button
440 ui->buttonCancel->setEnabled(true);
444 void UpdaterDialog::threadMessageLogged(const QString &message)
446 m_logFile << message;
449 void UpdaterDialog::openUrl(const QString &url)
451 qDebug("Open URL: %s", url.toLatin1().constData());
452 QDesktopServices::openUrl(QUrl(url));
455 void UpdaterDialog::installUpdate(void)
457 if(!((m_thread) && m_thread->getSuccess()))
459 qWarning("Cannot download/install update at this point!");
463 QApplication::setOverrideCursor(Qt::WaitCursor);
464 ui->buttonDownload->hide();
465 ui->buttonCancel->setEnabled(false);
466 SHOW_ANIMATION(true);
468 const MUtils::UpdateCheckerInfo *updateInfo = m_thread->getUpdateInfo();
474 MUtils::init_process(process, MUtils::temp_folder(), false);
476 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
477 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
479 args << QString("/Location=%1").arg(updateInfo->getDownloadAddress());
480 args << QString("/Filename=%1").arg(updateInfo->getDownloadFilename());
481 args << QString("/TicketID=%1").arg(updateInfo->getDownloadFilecode());
482 args << QString("/CheckSum=%1").arg(updateInfo->getDownloadChecksum());
483 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
484 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
485 args << QString("/AppTitle=Simple x264 Launcher (Build #%1)").arg(QString::number(updateInfo->getBuildNo()));
487 process.start(getBin(m_binaries, "wupd.exe"), args);
488 if(!process.waitForStarted())
490 QApplication::restoreOverrideCursor();
491 SHOW_ANIMATION(false);
492 QMessageBox::critical(this, tr("Update Failed"), tr("Sorry, failed to launch web-update program!"));
493 ui->buttonDownload->show();
494 ui->buttonCancel->setEnabled(true);
498 m_updaterProcess = MUtils::OS::process_id(&process);
499 loop.exec(QEventLoop::ExcludeUserInputEvents);
501 if(!process.waitForFinished())
504 process.waitForFinished();
507 m_updaterProcess = NULL;
508 QApplication::restoreOverrideCursor();
509 ui->buttonDownload->show();
510 ui->buttonCancel->setEnabled(true);
511 SHOW_ANIMATION(false);
513 if(process.exitCode() == 0)
515 done(READY_TO_INSTALL_UPDATE);
519 ///////////////////////////////////////////////////////////////////////////////
521 ///////////////////////////////////////////////////////////////////////////////
523 bool UpdaterDialog::checkBinaries(void)
525 qDebug("[File Verification]");
526 for(size_t i = 0; BINARIES[i].name; i++)
528 const QString name = QString::fromLatin1(BINARIES[i].name);
529 if (!m_binaries.contains(name))
531 QScopedPointer<QFile> binary(new QFile(QString("%1/toolset/common/%2").arg(m_sysinfo->getAppPath(), name)));
532 if (binary->open(QIODevice::ReadOnly))
534 if (checkFileHash(binary->fileName(), BINARIES[i].hash))
536 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
537 m_binaries.insert(name, QSharedPointer<QFile>(binary.take(), qFileDeleter));
541 qWarning("Verification of '%s' has failed!", MUTILS_UTF8(name));
548 qWarning("File '%s' could not be opened!", MUTILS_UTF8(name));
553 qDebug("File check completed.\n");
557 bool UpdaterDialog::checkFileHash(const QString &filePath, const char *expectedHash)
559 qDebug("Checking file: %s", MUTILS_UTF8(filePath));
560 QScopedPointer<MUtils::Hash::Hash> checksum(MUtils::Hash::create(MUtils::Hash::HASH_BLAKE2_512, DIGEST_KEY));
561 QFile file(filePath);
562 if(file.open(QIODevice::ReadOnly))
564 checksum->update(file);
565 const QByteArray fileHash = checksum->digest();
566 if((strlen(expectedHash) != fileHash.size()) || (memcmp(fileHash.constData(), expectedHash, fileHash.size()) != 0))
568 qWarning("\nFile appears to be corrupted:\n%s\n", filePath.toUtf8().constData());
569 qWarning("Expected Hash: %s\nDetected Hash: %s\n", expectedHash, fileHash.constData());
576 qWarning("Failed to open file:\n%s\n", filePath.toUtf8().constData());