OSDN Git Service

86ec9b7116ffaee113a6c85e1f4f69eb1d502c1f
[x264-launcher/x264-launcher.git] / src / win_updater.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2015 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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "win_updater.h"
23 #include "uic_win_updater.h"
24
25 #include "global.h"
26 #include "model_sysinfo.h"
27 #include "thread_updater.h"
28 #include "checksum.h"
29
30 #include <QMovie>
31 #include <QCloseEvent>
32 #include <QTimer>
33 #include <QMessageBox>
34 #include <QDesktopServices>
35 #include <QUrl>
36 #include <QProcess>
37 #include <QFileInfo>
38 #include <QDir>
39 #include <QMap>
40
41 ///////////////////////////////////////////////////////////////////////////////
42
43 const UpdaterDialog::binary_t UpdaterDialog::BINARIES[] =
44 {
45         { "wget.exe", "7b522345239bcb95b5b0f7f50a883ba5957894a1feb769763e38ed789a8a0f63fead0155f54b9ffd0f1cdc5dfd855d207a6e7a8e4fd192589a8838ce646c504e", 1 },
46         { "gpgv.exe", "97eebd656ad2799cbb69250ea9434b5afc8bcf578097703594277451f4e752166464a077ba71d5960824fa71e52f2a9e94c6368ae70a93d86a10720b3fced2fd", 1 },
47         { "gpgv.gpg", "58e0f0e462bbd0b5aa4f638801c1097da7da4b3eb38c8c88ad1db23705c0f11e174b083fa55fe76bd3ba196341c967833a6f3427d6f63ad8565900745535d8fa", 0 },
48         { "wupd.exe", "1156dd9aa47df35dfeb68cb9bea26cf5236c1bf4c29c22676b450e827aa8e4419858d2b9a2c9e94747ad43704a145724ec5b0280d16922e52c6c47e324739571", 1 },
49         { NULL, NULL, 0 }
50 };
51
52 #define UPDATE_TEXT(N, TEXT) ui->label_phase##N->setText((TEXT))
53 #define UPDATE_ICON(N, ICON) ui->icon_phase##N->setPixmap(QIcon(":/buttons/" ICON ".png").pixmap(16, 16))
54
55 #define SHOW_ANIMATION(FLAG) do  \
56 { \
57         ui->frameAnimation->setVisible((FLAG)); \
58         ui->labelInfo->setVisible(!(FLAG)); \
59         ui->labelUrl->setVisible(!(FLAG)); \
60         ui->labelBuildNo->setVisible(!(FLAG)); \
61         if((FLAG)) m_animator->start(); else m_animator->stop(); \
62 } \
63 while(0)
64
65
66 ///////////////////////////////////////////////////////////////////////////////
67 // Constructor & Destructor
68 ///////////////////////////////////////////////////////////////////////////////
69
70 UpdaterDialog::UpdaterDialog(QWidget *parent, const SysinfoModel *sysinfo, const char *const updateUrl)
71 :
72         QDialog(parent),
73         ui(new Ui::UpdaterDialog()),
74         m_sysinfo(sysinfo),
75         m_updateUrl(updateUrl),
76         m_status(UpdateCheckThread::UpdateStatus_NotStartedYet),
77         m_thread(NULL),
78         m_updaterProcess(NULL),
79         m_success(false),
80         m_firstShow(true)
81 {
82         //Init the dialog, from the .ui file
83         ui->setupUi(this);
84         setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
85
86         //Fix size
87         setFixedSize(size());
88
89         //Enable buttons
90         connect(ui->buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
91         connect(ui->buttonDownload, SIGNAL(clicked()), this, SLOT(installUpdate()));
92         connect(ui->buttonRetry, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
93         
94         //Enable info label
95         connect(ui->labelUrl, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString)));
96         
97         //Init animation
98         m_animator = new QMovie(":/images/loading.gif");
99         ui->labelLoadingCenter->setMovie(m_animator);
100
101         //Init buttons
102         ui->buttonCancel->setEnabled(false);
103         ui->buttonRetry->hide();
104         ui->buttonDownload->hide();
105
106         //Start animation
107         SHOW_ANIMATION(true);
108 }
109
110 UpdaterDialog::~UpdaterDialog(void)
111 {
112         if(m_thread)
113         {
114                 if(!m_thread->wait(1000))
115                 {
116                         m_thread->terminate();
117                         m_thread->wait();
118                 }
119         }
120
121         if((!m_keysFile.isEmpty()) && QFile::exists(m_keysFile))
122         {
123                 QFile::setPermissions(m_keysFile, QFile::ReadOwner | QFile::WriteOwner);
124                 QFile::remove(m_keysFile);
125                 m_keysFile.clear();
126         }
127
128         X264_DELETE(m_thread);
129         X264_DELETE(m_animator);
130
131         delete ui;
132 }
133
134 ///////////////////////////////////////////////////////////////////////////////
135 // Public Functions
136 ///////////////////////////////////////////////////////////////////////////////
137
138 /*None yet*/
139
140 ///////////////////////////////////////////////////////////////////////////////
141 // Events
142 ///////////////////////////////////////////////////////////////////////////////
143
144 bool UpdaterDialog::event(QEvent *e)
145 {
146         if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
147         {
148                 x264_bring_process_to_front(m_updaterProcess);
149         }
150         return QDialog::event(e);
151 }
152
153 void UpdaterDialog::showEvent(QShowEvent *event)
154 {
155         if(m_firstShow)
156         {
157                 m_firstShow = false;
158                 QTimer::singleShot(16, this, SLOT(initUpdate()));
159         }
160 }
161
162 void UpdaterDialog::closeEvent(QCloseEvent *e)
163 {
164         if(!ui->buttonCancel->isEnabled())
165         {
166                 e->ignore();
167         }
168 }
169
170 void UpdaterDialog::keyPressEvent(QKeyEvent *event)
171 {
172         if(event->key() == Qt::Key_F11)
173         {
174                 QFile logFile(QString("%1/%2.log").arg(x264_temp_directory(), x264_rand_str()));
175                 if(logFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
176                 {
177                         logFile.write("\xEF\xBB\xBF");
178                         for(QStringList::ConstIterator iter = m_logFile.constBegin(); iter != m_logFile.constEnd(); iter++)
179                         {
180                                 logFile.write(iter->toUtf8());
181                                 logFile.write("\r\n");
182                         }
183                         logFile.close();
184                         QDesktopServices::openUrl(QUrl::fromLocalFile(logFile.fileName()));
185                 }
186         }
187 }
188
189 ///////////////////////////////////////////////////////////////////////////////
190 // Slots
191 ///////////////////////////////////////////////////////////////////////////////
192
193 void UpdaterDialog::initUpdate(void)
194 {
195         //Check binary files
196         QString wgetBin, gpgvBin;
197         if(!checkBinaries(wgetBin, gpgvBin))
198         {
199                 ui->buttonCancel->setEnabled(true);
200                 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;"));
201                 if(QMessageBox::critical(this, tr("File Error"), message, tr("Download Latest Version"), tr("Discard")) == 0)
202                 {
203                         QDesktopServices::openUrl(QUrl(QString::fromLatin1(m_updateUrl)));
204                 }
205                 close(); return;
206         }
207
208         //Make sure user does have admin access
209         if(!x264_user_is_admin())
210         {
211                 qWarning("User is not in the \"admin\" group, cannot update!");
212                 QString message;
213                 message += QString("<nobr>%1</nobr><br>").arg(tr("Sorry, but only users in the \"Administrators\" group can install updates."));
214                 message += QString("<nobr>%1</nobr>").arg(tr("Please start application from an administrator account and try again!"));
215                 if(QMessageBox::critical(this, this->windowTitle(), message, tr("Discard"), tr("Ignore")) != 1)
216                 {
217                         ui->buttonCancel->setEnabled(true);
218                         close(); return;
219                 }
220         }
221         
222         //Create and setup thread
223         if(!m_thread)
224         {
225                 m_thread = new UpdateCheckThread(wgetBin, gpgvBin, m_keysFile, false);
226                 connect(m_thread, SIGNAL(statusChanged(int)), this, SLOT(threadStatusChanged(int)));
227                 connect(m_thread, SIGNAL(finished()), this, SLOT(threadFinished()));
228                 connect(m_thread, SIGNAL(terminated()), this, SLOT(threadFinished()));
229                 connect(m_thread, SIGNAL(messageLogged(QString)), this, SLOT(threadMessageLogged(QString)));
230         }
231
232         //Begin updater run
233         QTimer::singleShot(16, this, SLOT(checkForUpdates()));
234 }
235
236 void UpdaterDialog::checkForUpdates(void)
237 {
238         if((!m_thread) || m_thread->isRunning())
239         {
240                 qWarning("Update in progress, cannot check for updates now!");
241         }
242
243         //Clear texts
244         ui->retranslateUi(this);
245         ui->labelBuildNo->setText(tr("Installed build is #%1  |  Latest build is #%2").arg(QString::number(x264_version_build()), tr("N/A")));
246
247         //Init buttons
248         ui->buttonCancel->setEnabled(false);
249         ui->buttonRetry->hide();
250         ui->buttonDownload->hide();
251
252         //Hide labels
253         ui->labelInfo->hide();
254         ui->labelUrl->hide();
255
256         //Update status
257         threadStatusChanged(UpdateCheckThread::UpdateStatus_NotStartedYet);
258
259         //Start animation
260         SHOW_ANIMATION(true);
261
262         //Update cursor
263         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
264         QApplication::setOverrideCursor(Qt::WaitCursor);
265
266         //Clear log
267         m_logFile.clear();
268
269         //Start the updater thread
270         QTimer::singleShot(250, m_thread, SLOT(start()));
271 }
272
273 void UpdaterDialog::threadStatusChanged(int status)
274 {
275         switch(m_status = status)
276         {
277         case UpdateCheckThread::UpdateStatus_NotStartedYet:
278                 UPDATE_ICON(1, "clock");
279                 UPDATE_ICON(2, "clock");
280                 UPDATE_ICON(3, "clock");
281                 break;
282         case UpdateCheckThread::UpdateStatus_CheckingConnection:
283                 UPDATE_ICON(1, "play");
284                 break;
285         case UpdateCheckThread::UpdateStatus_FetchingUpdates:
286                 UPDATE_ICON(1, "shield_green");
287                 UPDATE_TEXT(1, tr("Internet connection is working."));
288                 UPDATE_ICON(2, "play");
289                 break;
290         case UpdateCheckThread::UpdateStatus_ErrorNoConnection:
291                 UPDATE_ICON(1, "shield_error");
292                 UPDATE_TEXT(1, tr("Computer is currently offline!"));
293                 UPDATE_ICON(2, "shield_grey");
294                 UPDATE_ICON(3, "shield_grey");
295                 break;
296         case UpdateCheckThread::UpdateStatus_ErrorConnectionTestFailed:
297                 UPDATE_ICON(1, "shield_error");
298                 UPDATE_TEXT(1, tr("Internet connectivity test failed!"));
299                 UPDATE_ICON(2, "shield_grey");
300                 UPDATE_ICON(3, "shield_grey");
301                 break;
302         case UpdateCheckThread::UpdateStatus_ErrorFetchUpdateInfo:
303                 UPDATE_ICON(2, "shield_error");
304                 UPDATE_TEXT(2, tr("Failed to download the update information!"));
305                 UPDATE_ICON(3, "shield_grey");
306                 break;
307         case UpdateCheckThread::UpdateStatus_CompletedUpdateAvailable:
308         case UpdateCheckThread::UpdateStatus_CompletedNoUpdates:
309         case UpdateCheckThread::UpdateStatus_CompletedNewVersionOlder:
310                 UPDATE_ICON(2, "shield_green");
311                 UPDATE_TEXT(2, tr("Update information received successfully."));
312                 UPDATE_ICON(3, "play");
313                 break;
314         default:
315                 THROW("Unknown status code!");
316         }
317 }
318
319 void UpdaterDialog::threadFinished(void)
320 {
321         m_success = m_thread->getSuccess();
322         QTimer::singleShot((m_success ? 1000 : 0), this, SLOT(updateFinished()));
323 }
324
325 void UpdaterDialog::updateFinished(void)
326 {
327         //Restore cursor
328         QApplication::restoreOverrideCursor();
329
330         //If update was successfull, process final updater state
331         if(m_thread->getSuccess())
332         {
333                 switch(m_status)
334                 {
335                 case UpdateCheckThread::UpdateStatus_CompletedUpdateAvailable:
336                         UPDATE_ICON(3, "shield_exclamation");
337                         UPDATE_TEXT(3, tr("A newer version is available!"));
338                         ui->buttonDownload->show();
339                         break;
340                 case UpdateCheckThread::UpdateStatus_CompletedNoUpdates:
341                         UPDATE_ICON(3, "shield_green");
342                         UPDATE_TEXT(3, tr("Your version is up-to-date."));
343                         break;
344                 case UpdateCheckThread::UpdateStatus_CompletedNewVersionOlder:
345                         UPDATE_ICON(3, "shield_blue");
346                         UPDATE_TEXT(3, tr("You are using a pre-release version!"));
347                         break;
348                 default:
349                         qWarning("Update thread succeeded with unexpected status code: %d", m_status);
350                 }
351         }
352
353         //Show update info or retry button
354         switch(m_status)
355         {
356         case UpdateCheckThread::UpdateStatus_CompletedUpdateAvailable:
357         case UpdateCheckThread::UpdateStatus_CompletedNoUpdates:
358         case UpdateCheckThread::UpdateStatus_CompletedNewVersionOlder:
359                 SHOW_ANIMATION(false);
360                 ui->labelBuildNo->setText(tr("Installed build is #%1  |  Latest build is #%2").arg(QString::number(x264_version_build()), QString::number(m_thread->getUpdateInfo()->m_buildNo)));
361                 ui->labelUrl->setText(QString("<a href=\"%1\">%1</a>").arg(m_thread->getUpdateInfo()->m_downloadSite));
362                 break;
363         case UpdateCheckThread::UpdateStatus_ErrorNoConnection:
364         case UpdateCheckThread::UpdateStatus_ErrorConnectionTestFailed:
365         case UpdateCheckThread::UpdateStatus_ErrorFetchUpdateInfo:
366                 m_animator->stop();
367                 ui->buttonRetry->show();
368                 break;
369         default:
370                 qWarning("Update thread finished with unexpected status code: %d", m_status);
371         }
372
373         //Re-enbale cancel button
374         ui->buttonCancel->setEnabled(true);
375         
376 }
377
378 void UpdaterDialog::threadMessageLogged(const QString &message)
379 {
380         m_logFile << message;
381 }
382
383 void UpdaterDialog::openUrl(const QString &url)
384 {
385         qDebug("Open URL: %s", url.toLatin1().constData());
386         QDesktopServices::openUrl(QUrl(url));
387 }
388
389 void UpdaterDialog::installUpdate(void)
390 {
391         if(!((m_thread) && m_thread->getSuccess()))
392         {
393                 qWarning("Cannot download/install update at this point!");
394                 return;
395         }
396
397         QApplication::setOverrideCursor(Qt::WaitCursor);
398         ui->buttonDownload->hide();
399         ui->buttonCancel->setEnabled(false);
400         SHOW_ANIMATION(true);
401
402         const UpdateInfo *updateInfo = m_thread->getUpdateInfo();
403
404         QProcess process;
405         QStringList args;
406         QEventLoop loop;
407
408         x264_init_process(process, x264_temp_directory(), false);
409
410         connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
411         connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
412
413         args << QString("/Location=%1").arg(updateInfo->m_downloadAddress);
414         args << QString("/Filename=%1").arg(updateInfo->m_downloadFilename);
415         args << QString("/TicketID=%1").arg(updateInfo->m_downloadFilecode);
416         args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath())); 
417         args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
418         args << QString("/AppTitle=Simple x264 Launcher (Build #%1)").arg(QString::number(updateInfo->m_buildNo));
419
420         process.start(m_wupdFile, args);
421         if(!process.waitForStarted())
422         {
423                 QApplication::restoreOverrideCursor();
424                 SHOW_ANIMATION(false);
425                 QMessageBox::critical(this, tr("Update Failed"), tr("Sorry, failed to launch web-update program!"));
426                 ui->buttonDownload->show();
427                 ui->buttonCancel->setEnabled(true);
428                 return;
429         }
430
431         m_updaterProcess = x264_process_id(process);
432         loop.exec(QEventLoop::ExcludeUserInputEvents);
433         
434         if(!process.waitForFinished())
435         {
436                 process.kill();
437                 process.waitForFinished();
438         }
439
440         m_updaterProcess = NULL;
441         QApplication::restoreOverrideCursor();
442         ui->buttonDownload->show();
443         ui->buttonCancel->setEnabled(true);
444         SHOW_ANIMATION(false);
445
446         if(process.exitCode() == 0)
447         {
448                 done(READY_TO_INSTALL_UPDATE);
449         }
450 }
451
452 ///////////////////////////////////////////////////////////////////////////////
453 // Private Functions
454 ///////////////////////////////////////////////////////////////////////////////
455
456 bool UpdaterDialog::checkBinaries(QString &wgetBin, QString &gpgvBin)
457 {
458         qDebug("[File Verification]");
459         QMap<QString, QString> binaries;
460
461         m_keysFile.clear();
462         m_wupdFile.clear();
463         wgetBin.clear();
464         gpgvBin.clear();
465
466         bool okay = true;
467
468         for(size_t i = 0; BINARIES[i].name; i++)
469         {
470                 const QString binPath = QString("%1/toolset/common/%2").arg(m_sysinfo->getAppPath(), QString::fromLatin1(BINARIES[i].name));
471                 if(okay = okay && checkFileHash(binPath, BINARIES[i].hash))
472                 {
473                         binaries.insert(BINARIES[i].name, binPath);
474                 }
475                 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
476         }
477
478         if(okay)
479         {
480                 wgetBin = binaries.value("wget.exe");
481                 gpgvBin = binaries.value("gpgv.exe");
482
483                 m_wupdFile = binaries.value("wupd.exe");
484                 m_keysFile = QString("%1/%2.gpg").arg(x264_temp_directory(), x264_rand_str());
485
486                 if(okay = QFile::copy(binaries.value("gpgv.gpg"), m_keysFile))
487                 {
488                         QFile::setPermissions(m_keysFile, QFile::ReadOwner);
489                 }
490                 qDebug("%s\n", okay ? "Completed." : "Failed to copy GPG file!");
491         }
492
493         return okay;
494 }
495
496 bool UpdaterDialog::checkFileHash(const QString &filePath, const char *expectedHash)
497 {
498         qDebug("Checking file: %s", filePath.toUtf8().constData());
499         QBlake2Checksum checksum2;
500         QFile file(filePath);
501         if(file.open(QIODevice::ReadOnly))
502         {
503                 checksum2.update(file);
504                 const QByteArray fileHash = checksum2.finalize();
505                 if((strlen(expectedHash) != fileHash.size()) || (memcmp(fileHash.constData(), expectedHash, fileHash.size()) != 0))
506                 {
507                         qWarning("\nFile appears to be corrupted:\n%s\n", filePath.toUtf8().constData());
508                         qWarning("Expected Hash: %s\nDetected Hash: %s\n", expectedHash, fileHash.constData());
509                         return false;
510                 }
511                 return true;
512         }
513         else
514         {
515                 qWarning("Failed to open file:\n%s\n", filePath.toUtf8().constData());
516                 return false;
517         }
518 }