Avoid copying the binaries for update checker.
[simple-x264-launcher.git] / src / win_updater.cpp
bloba8bf12de2b61176a29f666c26201b7b749cc9d00
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>
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 },
60 { NULL, NULL, 0 }
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 \
67 { \
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(); \
73 } \
74 while(0)
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)
88 QDialog(parent),
89 ui(new Ui::UpdaterDialog()),
90 m_sysinfo(sysinfo),
91 m_updateUrl(updateUrl),
92 m_status(MUtils::UpdateChecker::UpdateStatus_NotStartedYet),
93 m_thread(NULL),
94 m_updaterProcess(NULL),
95 m_success(false),
96 m_firstShow(true)
98 //Init the dialog, from the .ui file
99 ui->setupUi(this);
100 setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
102 //Fix size
103 setFixedSize(size());
105 //Enable buttons
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()));
110 //Enable info label
111 connect(ui->labelUrl, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString)));
113 //Init animation
114 m_animator.reset(new QMovie(":/images/loading.gif"));
115 ui->labelLoadingCenter->setMovie(m_animator.data());
117 //Init buttons
118 ui->buttonCancel->setEnabled(false);
119 ui->buttonRetry->hide();
120 ui->buttonDownload->hide();
121 ui->labelCancel->hide();
123 //Start animation
124 SHOW_ANIMATION(true);
127 UpdaterDialog::~UpdaterDialog(void)
129 if(!m_thread.isNull())
131 if(!m_thread->wait(5000))
133 m_thread->terminate();
134 m_thread->wait();
137 closeFiles();
138 delete ui;
141 ///////////////////////////////////////////////////////////////////////////////
142 // Public Functions
143 ///////////////////////////////////////////////////////////////////////////////
145 /*None yet*/
147 ///////////////////////////////////////////////////////////////////////////////
148 // Events
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)
162 if(m_firstShow)
164 m_firstShow = false;
165 QTimer::singleShot(16, this, SLOT(initUpdate()));
169 void UpdaterDialog::closeEvent(QCloseEvent *e)
171 if(!ui->buttonCancel->isEnabled())
173 e->ignore();
177 void UpdaterDialog::keyPressEvent(QKeyEvent *event)
179 switch (event->key())
181 case Qt::Key_Escape:
182 if ((!m_thread.isNull()) && m_thread->isRunning())
184 if (m_status >= MUtils::UpdateChecker::UpdateStatus_FetchingUpdates)
186 UPDATE_TEXT(2, tr("Cancellation requested..."));
188 else
190 UPDATE_TEXT(1, tr("Cancellation requested..."));
192 m_thread->cancel();
194 break;
195 case Qt::Key_F11:
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");
210 logFile.close();
211 QDesktopServices::openUrl(QUrl::fromLocalFile(logFile.fileName()));
215 break;
216 default:
217 QDialog::keyPressEvent(event);
221 ///////////////////////////////////////////////////////////////////////////////
222 // Slots
223 ///////////////////////////////////////////////////////////////////////////////
225 void UpdaterDialog::initUpdate(void)
227 //Check binary files
228 if(!checkBinaries())
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("-", "&minus;"));
232 if(QMessageBox::critical(this, tr("File Error"), message, tr("Download Latest Version"), tr("Discard")) == 0)
234 QDesktopServices::openUrl(QUrl(QString::fromLatin1(m_updateUrl)));
236 close();
237 return;
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!");
244 QString message;
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);
250 close();
251 return;
255 //Create and setup thread
256 if(!m_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)));
265 //Begin updater run
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!");
276 //Clear texts
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")));
280 //Init buttons
281 ui->buttonCancel->setEnabled(false);
282 ui->buttonRetry->hide();
283 ui->buttonDownload->hide();
285 //Hide labels
286 ui->labelInfo->hide();
287 ui->labelUrl->hide();
288 ui->labelCancel->show();
290 //Update status
291 threadStatusChanged(MUtils::UpdateChecker::UpdateStatus_NotStartedYet);
293 //Start animation
294 SHOW_ANIMATION(true);
296 //Update cursor
297 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
298 QApplication::setOverrideCursor(Qt::WaitCursor);
300 //Clear log
301 m_logFile.clear();
303 //Init timer
304 m_elapsed.reset(new QElapsedTimer());
305 m_elapsed->start();
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");
320 break;
321 case MUtils::UpdateChecker::UpdateStatus_CheckingConnection:
322 UPDATE_ICON(1, "play");
323 break;
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");
328 break;
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");
334 break;
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");
340 break;
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");
345 break;
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");
352 break;
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");
360 else
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");
367 break;
368 default:
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);
389 //Restore cursor
390 QApplication::restoreOverrideCursor();
392 //If update was successfull, process final updater state
393 if(m_thread->getSuccess())
395 switch(m_status)
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();
401 break;
402 case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
403 UPDATE_ICON(3, "shield_green");
404 UPDATE_TEXT(3, tr("Your version is up-to-date."));
405 break;
406 case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
407 UPDATE_ICON(3, "shield_blue");
408 UPDATE_TEXT(3, tr("You are using a pre-release version!"));
409 break;
410 default:
411 qWarning("Update thread succeeded with unexpected status code: %d", m_status);
415 //Show update info or retry button
416 switch(m_status)
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()));
424 break;
425 case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection:
426 case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed:
427 case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo:
428 case MUtils::UpdateChecker::UpdateStatus_CancelledByUser:
429 m_animator->stop();
430 ui->buttonRetry->show();
431 break;
432 default:
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!");
457 return;
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();
467 QProcess process;
468 QStringList args;
469 QEventLoop loop;
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);
492 return;
495 m_updaterProcess = MUtils::OS::process_id(&process);
496 loop.exec(QEventLoop::ExcludeUserInputEvents);
498 if(!process.waitForFinished())
500 process.kill();
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 ///////////////////////////////////////////////////////////////////////////////
517 // Private Functions
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());
536 else
538 qWarning("Verification of '%s' has failed!", MUTILS_UTF8(name));
539 return false;
542 else
544 qWarning("File '%s' could not be opened!", MUTILS_UTF8(name));
545 return false;
549 qDebug("File check completed.\n");
550 return true;
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());
566 return false;
568 return true;
570 else
572 qWarning("Failed to open file:\n%s\n", filePath.toUtf8().constData());
573 return false;
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())
585 file->close();
586 delete (file);
589 m_binaries.clear();