1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2017 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 { "netc.exe", "2e890533473134e074d65e1670c4212a06e4f685c4ee202593b0427defdf2f01e4d22cf7b48855436f1c57109c131f3469daa1a523a5a05fc9d23fb41d2e6ea9", 1 },
57 { "gpgv.exe", "a8d4d1702e5fb1eee5a2c22fdaf255816a9199ae48142aeec1c8ce16bbcf61d6d634f1e769e62d05cf52c204ba2611f09c9bb661bc6688b937749d478af3e47d", 1 },
58 { "gpgv.gpg", "1a2f528e551b9abfb064f08674fdd421d3abe403469ddfee2beafd007775a6c684212a6274dc2b41a0b20dd5c2200021c91320e737f7a90b2ac5a40a6221d93f", 0 },
59 { "wupd.exe", "c7fe72259ae781889a18f688321275e3bae39d75fb96c9c650446e177cb3af3d3ea84db2c1590e44bc2440b2ea79f9684e3a14e47e57e6083ec6f98c5bf72a73", 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
, QFile
*> &binaries
, const QString
&nameName
)
78 const QFile
*const file
= binaries
.value(nameName
);
79 return file
? file
->fileName() : QString();
82 ///////////////////////////////////////////////////////////////////////////////
83 // Constructor & Destructor
84 ///////////////////////////////////////////////////////////////////////////////
86 UpdaterDialog::UpdaterDialog(QWidget
*parent
, const SysinfoModel
*sysinfo
, const char *const updateUrl
)
89 ui(new Ui::UpdaterDialog()),
91 m_updateUrl(updateUrl
),
92 m_status(MUtils::UpdateChecker::UpdateStatus_NotStartedYet
),
94 m_updaterProcess(NULL
),
98 //Init the dialog, from the .ui file
100 setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint
));
103 setFixedSize(size());
106 connect(ui
->buttonCancel
, SIGNAL(clicked()), this, SLOT(close()));
107 connect(ui
->buttonDownload
, SIGNAL(clicked()), this, SLOT(installUpdate()));
108 connect(ui
->buttonRetry
, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
111 connect(ui
->labelUrl
, SIGNAL(linkActivated(QString
)), this, SLOT(openUrl(QString
)));
114 m_animator
.reset(new QMovie(":/images/loading.gif"));
115 ui
->labelLoadingCenter
->setMovie(m_animator
.data());
118 ui
->buttonCancel
->setEnabled(false);
119 ui
->buttonRetry
->hide();
120 ui
->buttonDownload
->hide();
121 ui
->labelCancel
->hide();
124 SHOW_ANIMATION(true);
127 UpdaterDialog::~UpdaterDialog(void)
129 if(!m_thread
.isNull())
131 if(!m_thread
->wait(5000))
133 m_thread
->terminate();
141 ///////////////////////////////////////////////////////////////////////////////
143 ///////////////////////////////////////////////////////////////////////////////
147 ///////////////////////////////////////////////////////////////////////////////
149 ///////////////////////////////////////////////////////////////////////////////
151 bool UpdaterDialog::event(QEvent
*e
)
153 if((e
->type() == QEvent::ActivationChange
) && (m_updaterProcess
!= NULL
))
155 MUtils::GUI::bring_to_front(m_updaterProcess
);
157 return QDialog::event(e
);
160 void UpdaterDialog::showEvent(QShowEvent
*event
)
165 QTimer::singleShot(16, this, SLOT(initUpdate()));
169 void UpdaterDialog::closeEvent(QCloseEvent
*e
)
171 if(!ui
->buttonCancel
->isEnabled())
177 void UpdaterDialog::keyPressEvent(QKeyEvent
*event
)
179 switch (event
->key())
182 if ((!m_thread
.isNull()) && m_thread
->isRunning())
184 if (m_status
>= MUtils::UpdateChecker::UpdateStatus_FetchingUpdates
)
186 UPDATE_TEXT(2, tr("Cancellation requested..."));
190 UPDATE_TEXT(1, tr("Cancellation requested..."));
197 const QString logFilePath
= MUtils::make_temp_file(MUtils::temp_folder(), "txt", true);
198 if (!logFilePath
.isEmpty())
200 qWarning("Write log to: '%s'", MUTILS_UTF8(logFilePath
));
201 QFile
logFile(logFilePath
);
202 if (logFile
.open(QIODevice::WriteOnly
| QIODevice::Truncate
))
204 logFile
.write("\xEF\xBB\xBF");
205 for (QStringList::ConstIterator iter
= m_logFile
.constBegin(); iter
!= m_logFile
.constEnd(); iter
++)
207 logFile
.write(iter
->toUtf8());
208 logFile
.write("\r\n");
211 QDesktopServices::openUrl(QUrl::fromLocalFile(logFile
.fileName()));
217 QDialog::keyPressEvent(event
);
221 ///////////////////////////////////////////////////////////////////////////////
223 ///////////////////////////////////////////////////////////////////////////////
225 void UpdaterDialog::initUpdate(void)
230 ui
->buttonCancel
->setEnabled(true);
231 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("-", "−"));
232 if(QMessageBox::critical(this, tr("File Error"), message
, tr("Download Latest Version"), tr("Discard")) == 0)
234 QDesktopServices::openUrl(QUrl(QString::fromLatin1(m_updateUrl
)));
240 //Make sure user does have admin access
241 if(!MUtils::OS::user_is_admin())
243 qWarning("User is not in the \"admin\" group, cannot update!");
245 message
+= QString("<nobr>%1</nobr><br>").arg(tr("Sorry, but only users in the \"Administrators\" group can install updates."));
246 message
+= QString("<nobr>%1</nobr>").arg(tr("Please start application from an administrator account and try again!"));
247 if(QMessageBox::critical(this, this->windowTitle(), message
, tr("Discard"), tr("Ignore")) != 1)
249 ui
->buttonCancel
->setEnabled(true);
255 //Create and setup thread
258 m_thread
.reset(new MUtils::UpdateChecker(GETBIN(m_binaries
, "wget.exe"), GETBIN(m_binaries
, "netc.exe"), GETBIN(m_binaries
, "gpgv.exe"), GETBIN(m_binaries
, "gpgv.gpg"), "Simple x264 Launcher", x264_version_build(), false));
259 connect(m_thread
.data(), SIGNAL(statusChanged(int)), this, SLOT(threadStatusChanged(int)));
260 connect(m_thread
.data(), SIGNAL(finished()), this, SLOT(threadFinished()));
261 connect(m_thread
.data(), SIGNAL(terminated()), this, SLOT(threadFinished()));
262 connect(m_thread
.data(), SIGNAL(messageLogged(QString
)), this, SLOT(threadMessageLogged(QString
)));
266 QTimer::singleShot(16, this, SLOT(checkForUpdates()));
269 void UpdaterDialog::checkForUpdates(void)
271 if((!m_thread
) || m_thread
->isRunning())
273 qWarning("Update in progress, cannot check for updates now!");
277 ui
->retranslateUi(this);
278 ui
->labelBuildNo
->setText(tr("Installed build is #%1 | Latest build is #%2").arg(QString::number(x264_version_build()), tr("N/A")));
281 ui
->buttonCancel
->setEnabled(false);
282 ui
->buttonRetry
->hide();
283 ui
->buttonDownload
->hide();
286 ui
->labelInfo
->hide();
287 ui
->labelUrl
->hide();
288 ui
->labelCancel
->show();
291 threadStatusChanged(MUtils::UpdateChecker::UpdateStatus_NotStartedYet
);
294 SHOW_ANIMATION(true);
297 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents
);
298 QApplication::setOverrideCursor(Qt::WaitCursor
);
304 m_elapsed
.reset(new QElapsedTimer());
307 //Start the updater thread
308 QTimer::singleShot(125, m_thread
.data(), SLOT(start()));
311 void UpdaterDialog::threadStatusChanged(int status
)
313 const int prevStatus
= m_status
;
314 switch(m_status
= status
)
316 case MUtils::UpdateChecker::UpdateStatus_NotStartedYet
:
317 UPDATE_ICON(1, "clock");
318 UPDATE_ICON(2, "clock");
319 UPDATE_ICON(3, "clock");
321 case MUtils::UpdateChecker::UpdateStatus_CheckingConnection
:
322 UPDATE_ICON(1, "play");
324 case MUtils::UpdateChecker::UpdateStatus_FetchingUpdates
:
325 UPDATE_ICON(1, "shield_green");
326 UPDATE_TEXT(1, tr("Internet connection is working."));
327 UPDATE_ICON(2, "play");
329 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection
:
330 UPDATE_ICON(1, "shield_error");
331 UPDATE_TEXT(1, tr("Computer is currently offline!"));
332 UPDATE_ICON(2, "shield_grey");
333 UPDATE_ICON(3, "shield_grey");
335 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed
:
336 UPDATE_ICON(1, "shield_error");
337 UPDATE_TEXT(1, tr("Internet connectivity test failed!"));
338 UPDATE_ICON(2, "shield_grey");
339 UPDATE_ICON(3, "shield_grey");
341 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo
:
342 UPDATE_ICON(2, "shield_error");
343 UPDATE_TEXT(2, tr("Failed to download the update information!"));
344 UPDATE_ICON(3, "shield_grey");
346 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable
:
347 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates
:
348 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder
:
349 UPDATE_ICON(2, "shield_green");
350 UPDATE_TEXT(2, tr("Update information received successfully."));
351 UPDATE_ICON(3, "play");
353 case MUtils::UpdateChecker::UpdateStatus_CancelledByUser
:
354 if (prevStatus
>= MUtils::UpdateChecker::UpdateStatus_FetchingUpdates
)
356 UPDATE_ICON(2, "shield_error");
357 UPDATE_TEXT(2, tr("Operation was cancelled by the user!"));
358 UPDATE_ICON(3, "shield_grey");
362 UPDATE_ICON(1, "shield_error");
363 UPDATE_TEXT(1, tr("Operation was cancelled by the user!"));
364 UPDATE_ICON(2, "shield_grey");
365 UPDATE_ICON(3, "shield_grey");
369 MUTILS_THROW("Unknown status code!");
373 void UpdaterDialog::threadFinished(void)
375 m_success
= m_thread
->getSuccess();
376 ui
->labelCancel
->hide();
377 QTimer::singleShot((m_success
? 500 : 0), this, SLOT(updateFinished()));
380 void UpdaterDialog::updateFinished(void)
382 //Query the timer, if available
383 if (!m_elapsed
.isNull())
385 const quint64 elapsed
= m_elapsed
->restart();
386 qDebug("Update check completed after %.2f seconds.", double(elapsed
) / 1000.0);
390 QApplication::restoreOverrideCursor();
392 //If update was successfull, process final updater state
393 if(m_thread
->getSuccess())
397 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable
:
398 UPDATE_ICON(3, "shield_exclamation");
399 UPDATE_TEXT(3, tr("A newer version is available!"));
400 ui
->buttonDownload
->show();
402 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates
:
403 UPDATE_ICON(3, "shield_green");
404 UPDATE_TEXT(3, tr("Your version is up-to-date."));
406 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder
:
407 UPDATE_ICON(3, "shield_blue");
408 UPDATE_TEXT(3, tr("You are using a pre-release version!"));
411 qWarning("Update thread succeeded with unexpected status code: %d", m_status
);
415 //Show update info or retry button
418 case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable
:
419 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates
:
420 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder
:
421 SHOW_ANIMATION(false);
422 ui
->labelBuildNo
->setText(tr("Installed build is #%1 | Latest build is #%2").arg(QString::number(x264_version_build()), QString::number(m_thread
->getUpdateInfo()->getBuildNo())));
423 ui
->labelUrl
->setText(QString("<a href=\"%1\">%1</a>").arg(m_thread
->getUpdateInfo()->getDownloadSite()));
425 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection
:
426 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed
:
427 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo
:
428 case MUtils::UpdateChecker::UpdateStatus_CancelledByUser
:
430 ui
->buttonRetry
->show();
433 qWarning("Update thread finished with unexpected status code: %d", m_status
);
436 //Re-enbale cancel button
437 ui
->buttonCancel
->setEnabled(true);
441 void UpdaterDialog::threadMessageLogged(const QString
&message
)
443 m_logFile
<< message
;
446 void UpdaterDialog::openUrl(const QString
&url
)
448 qDebug("Open URL: %s", url
.toLatin1().constData());
449 QDesktopServices::openUrl(QUrl(url
));
452 void UpdaterDialog::installUpdate(void)
454 if(!((m_thread
) && m_thread
->getSuccess()))
456 qWarning("Cannot download/install update at this point!");
460 QApplication::setOverrideCursor(Qt::WaitCursor
);
461 ui
->buttonDownload
->hide();
462 ui
->buttonCancel
->setEnabled(false);
463 SHOW_ANIMATION(true);
465 const MUtils::UpdateCheckerInfo
*updateInfo
= m_thread
->getUpdateInfo();
471 MUtils::init_process(process
, MUtils::temp_folder(), false);
473 connect(&process
, SIGNAL(error(QProcess::ProcessError
)), &loop
, SLOT(quit()));
474 connect(&process
, SIGNAL(finished(int,QProcess::ExitStatus
)), &loop
, SLOT(quit()));
476 args
<< QString("/Location=%1").arg(updateInfo
->getDownloadAddress());
477 args
<< QString("/Filename=%1").arg(updateInfo
->getDownloadFilename());
478 args
<< QString("/TicketID=%1").arg(updateInfo
->getDownloadFilecode());
479 args
<< QString("/CheckSum=%1").arg(updateInfo
->getDownloadChecksum());
480 args
<< QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
481 args
<< QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
482 args
<< QString("/AppTitle=Simple x264 Launcher (Build #%1)").arg(QString::number(updateInfo
->getBuildNo()));
484 process
.start(GETBIN(m_binaries
, "wupd.exe"), args
);
485 if(!process
.waitForStarted())
487 QApplication::restoreOverrideCursor();
488 SHOW_ANIMATION(false);
489 QMessageBox::critical(this, tr("Update Failed"), tr("Sorry, failed to launch web-update program!"));
490 ui
->buttonDownload
->show();
491 ui
->buttonCancel
->setEnabled(true);
495 m_updaterProcess
= MUtils::OS::process_id(&process
);
496 loop
.exec(QEventLoop::ExcludeUserInputEvents
);
498 if(!process
.waitForFinished())
501 process
.waitForFinished();
504 m_updaterProcess
= NULL
;
505 QApplication::restoreOverrideCursor();
506 ui
->buttonDownload
->show();
507 ui
->buttonCancel
->setEnabled(true);
508 SHOW_ANIMATION(false);
510 if(process
.exitCode() == 0)
512 done(READY_TO_INSTALL_UPDATE
);
516 ///////////////////////////////////////////////////////////////////////////////
518 ///////////////////////////////////////////////////////////////////////////////
520 bool UpdaterDialog::checkBinaries(void)
522 qDebug("[File Verification]");
523 for(size_t i
= 0; BINARIES
[i
].name
; i
++)
525 const QString name
= QString::fromLatin1(BINARIES
[i
].name
);
526 if (!m_binaries
.contains(name
))
528 QScopedPointer
<QFile
> binary(new QFile(QString("%1/toolset/common/%2").arg(m_sysinfo
->getAppPath(), name
)));
529 if (binary
->open(QIODevice::ReadOnly
))
531 if (checkFileHash(binary
->fileName(), BINARIES
[i
].hash
))
533 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents
);
534 m_binaries
.insert(name
, binary
.take());
538 qWarning("Verification of '%s' has failed!", MUTILS_UTF8(name
));
544 qWarning("File '%s' could not be opened!", MUTILS_UTF8(name
));
549 qDebug("File check completed.\n");
553 bool UpdaterDialog::checkFileHash(const QString
&filePath
, const char *expectedHash
)
555 qDebug("Checking file: %s", MUTILS_UTF8(filePath
));
556 QScopedPointer
<MUtils::Hash::Hash
> checksum(MUtils::Hash::create(MUtils::Hash::HASH_BLAKE2_512
, DIGEST_KEY
));
557 QFile
file(filePath
);
558 if(file
.open(QIODevice::ReadOnly
))
560 checksum
->update(file
);
561 const QByteArray fileHash
= checksum
->digest();
562 if((strlen(expectedHash
) != fileHash
.size()) || (memcmp(fileHash
.constData(), expectedHash
, fileHash
.size()) != 0))
564 qWarning("\nFile appears to be corrupted:\n%s\n", filePath
.toUtf8().constData());
565 qWarning("Expected Hash: %s\nDetected Hash: %s\n", expectedHash
, fileHash
.constData());
572 qWarning("Failed to open file:\n%s\n", filePath
.toUtf8().constData());
577 void UpdaterDialog::closeFiles(void)
579 if (!m_binaries
.empty())
581 for (QMap
<QString
, QFile
*>::ConstIterator iter
= m_binaries
.constBegin(); iter
!= m_binaries
.constEnd(); iter
++)
583 if (QFile
*const file
= iter
.value())