Bump version.
[LameXP.git] / src / Dialog_Update.cpp
blobcb97b17514b36f6d2afa66e0dc235e1b7ddf7d40
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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 "Dialog_Update.h"
24 #include "Global.h"
25 #include "Resource.h"
26 #include "Dialog_LogView.h"
27 #include "Model_Settings.h"
28 #include "WinSevenTaskbar.h"
30 #include <QClipboard>
31 #include <QFileDialog>
32 #include <QTimer>
33 #include <QProcess>
34 #include <QDate>
35 #include <QRegExp>
36 #include <QDesktopServices>
37 #include <QUrl>
38 #include <QCloseEvent>
39 #include <QMovie>
40 #include <QtConcurrentRun>
42 #include <time.h>
43 #include <MMSystem.h>
44 #include <WinInet.h>
46 ///////////////////////////////////////////////////////////////////////////////
48 static const char *header_id = "!Update";
49 static const char *section_id = "LameXP";
51 static const char *mirror_url_postfix[] =
53 "update.ver",
54 "update_beta.ver",
55 NULL
58 static const char *update_mirrors_prim[] =
60 "http://mulder.brhack.net/",
61 "http://mulder.bplaced.net/",
62 "http://lamexp.sourceforge.net/",
63 "http://free.pages.at/borschdfresser/",
64 "http://www.tricksoft.de/",
65 NULL
68 static const char *update_mirrors_back[] =
70 "http://mplayer.savedonthe.net/",
71 "http://mulder.dummwiedeutsch.de/",
72 "http://mplayer.somestuff.org/",
73 NULL
76 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites
78 "http://www.163.com/",
79 "http://www.360buy.com/",
80 "http://www.amazon.com/",
81 "http://www.aol.com/",
82 "http://www.apache.org/",
83 "http://www.apple.com/",
84 "http://www.adobe.com/",
85 "http://www.avidemux.org/",
86 "http://www.babylon.com/",
87 "http://www.baidu.com/",
88 "http://www.bbc.co.uk/",
89 "http://www.bing.com/",
90 "http://www.cnet.com/",
91 "http://cnzz.com/",
92 "http://www.ebay.com/",
93 "http://www.equation.com/",
94 "http://fc2.com/",
95 "http://www.ffmpeg.org/",
96 "http://www.flickr.com/",
97 "http://www.gitorious.org/",
98 "http://www.gnome.org/",
99 "http://www.gnu.org/",
100 "http://go.com/",
101 "http://code.google.com/",
102 "http://www.heise.de/",
103 "http://www.huffingtonpost.co.uk/",
104 "http://www.iana.org/",
105 "http://www.imdb.com/",
106 "http://www.imgburn.com/",
107 "http://imgur.com/",
108 "http://www.kernel.org/",
109 "http://www.libav.org/",
110 "http://www.linkedin.com/",
111 "http://www.livedoor.com/",
112 "http://www.livejournal.com/",
113 "http://mail.ru/",
114 "http://www.mediafire.com/",
115 "http://www.mozilla.org/",
116 "http://mplayerhq.hu/",
117 "http://www.msn.com/?st=1",
118 "http://oss.netfarm.it/",
119 "http://www.nytimes.com/",
120 "http://www.opera.com/",
121 "http://www.quakelive.com/",
122 "http://www.seamonkey-project.org/",
123 "http://www.sina.com.cn/",
124 "http://www.sohu.com/",
125 "http://www.soso.com/",
126 "http://sourceforge.net/",
127 "http://www.spiegel.de/",
128 "http://tdm-gcc.tdragon.net/",
129 "http://www.tdrsmusic.com/",
130 "http://www.ubuntu.com/",
131 "http://twitter.com/",
132 "http://www.uol.com.br/",
133 "http://www.videohelp.com/",
134 "http://www.videolan.org/",
135 "http://www.weibo.com/",
136 "http://www.wikipedia.org/",
137 "http://wordpress.com/",
138 "http://us.yahoo.com/",
139 "http://www.yandex.ru/",
140 "http://www.youtube.com/",
141 "http://www.zedo.com/",
142 NULL
145 static const int MIN_CONNSCORE = 8;
146 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
147 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
149 static BOOL getInternetConnectedState(void)
151 DWORD lpdwFlags = NULL;
152 BOOL result = InternetGetConnectedState(&lpdwFlags, NULL);
153 return result;
156 static BOOL CALLBACK focusUpdaterWindow(HWND hwnd, LPARAM lParam)
158 DWORD processId = *reinterpret_cast<WORD*>(lParam);
159 DWORD windowProcessId = NULL;
160 GetWindowThreadProcessId(hwnd, &windowProcessId);
161 if(windowProcessId == processId)
163 SwitchToThisWindow(hwnd, TRUE);
164 SetForegroundWindow(hwnd);
165 return FALSE;
168 return TRUE;
171 ///////////////////////////////////////////////////////////////////////////////
173 class UpdateInfo
175 public:
176 UpdateInfo(void) { resetInfo(); }
178 void resetInfo(void)
180 m_buildNo = 0;
181 m_buildDate.setDate(1900, 1, 1);
182 m_downloadSite.clear();
183 m_downloadAddress.clear();
184 m_downloadFilename.clear();
185 m_downloadFilecode.clear();
188 unsigned int m_buildNo;
189 QDate m_buildDate;
190 QString m_downloadSite;
191 QString m_downloadAddress;
192 QString m_downloadFilename;
193 QString m_downloadFilecode;
196 ///////////////////////////////////////////////////////////////////////////////
198 UpdateDialog::UpdateDialog(SettingsModel *settings, QWidget *parent)
200 QDialog(parent),
201 m_binaryWGet(lamexp_lookup_tool("wget.exe")),
202 m_binaryGnuPG(lamexp_lookup_tool("gpgv.exe")),
203 m_binaryUpdater(lamexp_lookup_tool("wupdate.exe")),
204 m_binaryKeys(lamexp_lookup_tool("gpgv.gpg")),
205 m_updateInfo(NULL),
206 m_settings(settings),
207 m_logFile(new QStringList()),
208 m_betaUpdates(settings ? (settings->autoUpdateCheckBeta() || lamexp_version_demo()) : lamexp_version_demo()),
209 m_success(false),
210 m_updateReadyToInstall(false),
211 m_updaterProcess(NULL)
213 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryUpdater.isEmpty() || m_binaryKeys.isEmpty())
215 throw "Tools not initialized correctly!";
218 //Init the dialog, from the .ui file
219 setupUi(this);
220 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
222 //Disable "X" button
223 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
224 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
226 //Init animation
227 m_animator = new QMovie(":/images/Loading3.gif");
228 labelAnimationCenter->setMovie(m_animator);
229 m_animator->start();
231 //Indicate beta updates
232 if(m_betaUpdates)
234 setWindowTitle(windowTitle().append(" [Beta]"));
237 //Enable button
238 connect(retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
239 connect(installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
240 connect(infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
241 connect(logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
243 //Enable progress bar
244 connect(progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
247 UpdateDialog::~UpdateDialog(void)
249 if(m_animator) m_animator->stop();
251 LAMEXP_DELETE(m_updateInfo);
252 LAMEXP_DELETE(m_logFile);
253 LAMEXP_DELETE(m_animator);
255 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
256 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
259 void UpdateDialog::showEvent(QShowEvent *event)
261 QDialog::showEvent(event);
263 labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), lamexp_version_date().toString(Qt::ISODate)));
264 labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
266 installButton->setEnabled(false);
267 closeButton->setEnabled(false);
268 retryButton->setEnabled(false);
269 logButton->setEnabled(false);
270 retryButton->hide();
271 logButton->hide();
272 infoLabel->hide();
273 hintLabel->hide();
274 hintIcon->hide();
275 frameAnimation->hide();
277 int counter = MIN_CONNSCORE + 2;
278 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
279 for(int i = 0; update_mirrors_back[i]; i++) counter++;
281 progressBar->setMaximum(counter);
282 progressBar->setValue(0);
284 m_updaterProcess = NULL;
286 QTimer::singleShot(0, this, SLOT(updateInit()));
289 void UpdateDialog::closeEvent(QCloseEvent *event)
291 if(!closeButton->isEnabled())
293 event->ignore();
295 else
297 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
298 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
302 void UpdateDialog::keyPressEvent(QKeyEvent *e)
304 if(e->key() == Qt::Key_F11)
306 if(closeButton->isEnabled()) logButtonClicked();
308 else if((e->key() == Qt::Key_F12) && e->modifiers().testFlag(Qt::ControlModifier))
310 if(closeButton->isEnabled())
312 testKnownWebSites();
313 logButtonClicked();
316 else
318 QDialog::keyPressEvent(e);
322 bool UpdateDialog::event(QEvent *e)
324 if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
326 EnumWindows(focusUpdaterWindow, reinterpret_cast<LPARAM>(&m_updaterProcess));
328 return QDialog::event(e);
331 bool UpdateDialog::winEvent(MSG *message, long *result)
333 return WinSevenTaskbar::handleWinEvent(message, result);
336 void UpdateDialog::updateInit(void)
338 setMinimumSize(size());
339 setMaximumHeight(height());
340 QApplication::processEvents();
341 checkForUpdates();
344 void UpdateDialog::checkForUpdates(void)
346 bool success = false;
347 int connectionScore = 0;
349 // ----- Initialization ----- //
351 m_updateInfo = new UpdateInfo;
353 progressBar->setValue(0);
354 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
355 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
356 installButton->setEnabled(false);
357 closeButton->setEnabled(false);
358 retryButton->setEnabled(false);
359 logButton->setEnabled(false);
360 if(infoLabel->isVisible()) infoLabel->hide();
361 if(hintLabel->isVisible()) hintLabel->hide();
362 if(hintIcon->isVisible()) hintIcon->hide();
363 frameAnimation->show();
365 QApplication::processEvents();
366 QApplication::setOverrideCursor(Qt::WaitCursor);
368 // ----- Test Internet Connection ----- //
370 statusLabel->setText(tr("Testing your internet connection, please wait..."));
372 m_logFile->clear();
373 m_logFile->append("Checking internet connection...");
375 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
376 while(!connectedState.isFinished())
378 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
381 if(!connectedState.result())
383 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
384 if(!retryButton->isVisible()) retryButton->show();
385 if(!logButton->isVisible()) logButton->show();
386 closeButton->setEnabled(true);
387 retryButton->setEnabled(true);
388 logButton->setEnabled(true);
389 if(frameAnimation->isVisible()) frameAnimation->hide();
390 statusLabel->setText(tr("It appears that the computer currently is offline!"));
391 progressBar->setValue(progressBar->maximum());
392 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
393 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
394 hintIcon->show();
395 hintLabel->show();
396 LAMEXP_DELETE(m_updateInfo);
397 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
398 QApplication::restoreOverrideCursor();
399 progressBar->setValue(progressBar->maximum());
400 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
401 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
402 return;
405 progressBar->setValue(1);
406 QApplication::processEvents();
408 // ----- Test Known Hosts Connectivity ----- //
410 QStringList hostList;
411 for(int i = 0; known_hosts[i]; i++)
413 hostList << QString::fromLatin1(known_hosts[i]);
416 qsrand(time(NULL));
417 while(!hostList.isEmpty())
419 QString currentHost = hostList.takeAt(qrand() % hostList.count());
420 if(connectionScore < MIN_CONNSCORE)
422 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
423 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
424 bool httpOk = false;
425 if(getFile(currentHost, outFile, 0, &httpOk))
427 connectionScore++;
428 progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
429 QApplication::processEvents();
430 Sleep(125);
432 if(httpOk)
434 connectionScore++;
435 progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
436 QApplication::processEvents();
437 Sleep(125);
439 QFile::remove(outFile);
443 if(connectionScore < MIN_CONNSCORE)
445 if(!retryButton->isVisible()) retryButton->show();
446 if(!logButton->isVisible()) logButton->show();
447 closeButton->setEnabled(true);
448 retryButton->setEnabled(true);
449 logButton->setEnabled(true);
450 if(frameAnimation->isVisible()) frameAnimation->hide();
451 statusLabel->setText(tr("Network connectivity test has failed!"));
452 progressBar->setValue(progressBar->maximum());
453 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
454 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
455 hintIcon->show();
456 hintLabel->show();
457 LAMEXP_DELETE(m_updateInfo);
458 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
459 QApplication::restoreOverrideCursor();
460 progressBar->setValue(progressBar->maximum());
461 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
462 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
463 return;
466 // ----- Build Mirror List ----- //
468 statusLabel->setText(tr("Checking for new updates online, please wait..."));
469 m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
471 QStringList mirrorList;
472 for(int index = 0; update_mirrors_prim[index]; index++)
474 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
477 qsrand(time(NULL));
478 for(int i = 0; i < 4375; i++)
480 mirrorList.swap(i % mirrorList.count(), qrand() % mirrorList.count());
483 for(int index = 0; update_mirrors_back[index]; index++)
485 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
488 // ----- Fetch Update Info From Server ----- //
490 while(!mirrorList.isEmpty())
492 QString currentMirror = mirrorList.takeFirst();
493 progressBar->setValue(progressBar->value() + 1);
494 if(!success)
496 if(tryUpdateMirror(m_updateInfo, currentMirror))
498 success = true;
501 else
503 QApplication::processEvents();
504 Sleep(125);
508 QApplication::restoreOverrideCursor();
509 progressBar->setValue(progressBar->maximum());
511 if(!success)
513 if(!retryButton->isVisible()) retryButton->show();
514 if(!logButton->isVisible()) logButton->show();
515 closeButton->setEnabled(true);
516 retryButton->setEnabled(true);
517 logButton->setEnabled(true);
518 if(frameAnimation->isVisible()) frameAnimation->hide();
519 statusLabel->setText(tr("Failed to fetch update information from server!"));
520 progressBar->setValue(progressBar->maximum());
521 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
522 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
523 hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
524 hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
525 hintIcon->show();
526 hintLabel->show();
527 LAMEXP_DELETE(m_updateInfo);
528 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
529 return;
532 // ----- Download New Program Version ----- //
534 labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
535 infoLabel->show();
536 infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), m_updateInfo->m_downloadSite));
537 QApplication::processEvents();
539 if(m_updateInfo->m_buildNo > lamexp_version_build())
541 installButton->setEnabled(true);
542 statusLabel->setText(tr("A new version of LameXP is available!"));
543 hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
544 hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
545 if(frameAnimation->isVisible()) frameAnimation->hide();
546 hintIcon->show();
547 hintLabel->show();
548 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
549 MessageBeep(MB_ICONINFORMATION);
551 else if(m_updateInfo->m_buildNo == lamexp_version_build())
553 statusLabel->setText(tr("No new updates available at this time."));
554 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
555 hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
556 if(frameAnimation->isVisible()) frameAnimation->hide();
557 hintIcon->show();
558 hintLabel->show();
559 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
560 MessageBeep(MB_ICONINFORMATION);
562 else
564 statusLabel->setText(tr("Your version appears to be newer than the latest release."));
565 hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
566 hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
567 if(frameAnimation->isVisible()) frameAnimation->hide();
568 hintIcon->show();
569 hintLabel->show();
570 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
571 MessageBeep(MB_ICONEXCLAMATION);
574 closeButton->setEnabled(true);
575 if(retryButton->isVisible()) retryButton->hide();
576 if(logButton->isVisible()) logButton->hide();
577 if(frameAnimation->isVisible()) frameAnimation->hide();
579 m_success = true;
582 bool UpdateDialog::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
584 bool success = false;
585 m_logFile->append(QStringList() << "" << "Trying mirror:" << url);
587 QString randPart = lamexp_rand_str();
588 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
589 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
591 m_logFile->append(QStringList() << "" << "Downloading update info:");
592 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
594 m_logFile->append(QStringList() << "" << "Downloading signature:");
595 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
597 if(ok1 && ok2)
599 m_logFile->append(QStringList() << "" << "Download okay, checking signature:");
600 if(checkSignature(outFileVersionInfo, outFileSignature))
602 m_logFile->append(QStringList() << "" << "Signature okay, parsing info:");
603 success = parseVersionInfo(outFileVersionInfo, updateInfo);
605 else
607 m_logFile->append(QStringList() << "" << "Bad signature, take care!");
610 else
612 m_logFile->append(QStringList() << "" << "Download has failed!");
615 QFile::remove(outFileVersionInfo);
616 QFile::remove(outFileSignature);
618 return success;
621 bool UpdateDialog::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
623 QFileInfo output(outFile);
624 output.setCaching(false);
625 if(httpOk) *httpOk = false;
627 if(output.exists())
629 QFile::remove(output.canonicalFilePath());
630 if(output.exists())
632 return false;
636 QProcess process;
637 process.setProcessChannelMode(QProcess::MergedChannels);
638 process.setReadChannel(QProcess::StandardOutput);
639 process.setWorkingDirectory(output.absolutePath());
641 QStringList args;
642 args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
643 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
644 args << "-O" << output.fileName() << url;
646 QEventLoop loop;
647 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
648 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
649 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
651 QTimer timer;
652 timer.setSingleShot(true);
653 timer.setInterval(25000);
654 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
656 const QRegExp httpResponseOK("200 OK$");
658 process.start(m_binaryWGet, args);
660 if(!process.waitForStarted())
662 return false;
665 timer.start();
667 while(process.state() == QProcess::Running)
669 loop.exec();
670 bool bTimeOut = (!timer.isActive());
671 while(process.canReadLine())
673 QString line = QString::fromLatin1(process.readLine()).simplified();
674 if(line.contains(httpResponseOK))
676 line.append(" [OK]");
677 if(httpOk) *httpOk = true;
679 m_logFile->append(line);
681 if(bTimeOut)
683 qWarning("WGet process timed out <-- killing!");
684 process.kill();
685 process.waitForFinished();
686 m_logFile->append("!!! TIMEOUT !!!");
687 return false;
691 timer.stop();
692 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
694 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
695 return (process.exitCode() == 0) && output.exists() && output.isFile();
698 bool UpdateDialog::checkSignature(const QString &file, const QString &signature)
700 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
702 qWarning("CheckSignature: File and signature should be in same folder!");
703 return false;
705 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
707 qWarning("CheckSignature: File and keyring should be in same folder!");
708 return false;
711 QProcess process;
712 process.setProcessChannelMode(QProcess::MergedChannels);
713 process.setReadChannel(QProcess::StandardOutput);
714 process.setWorkingDirectory(QFileInfo(file).absolutePath());
716 QEventLoop loop;
717 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
718 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
719 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
721 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
723 if(!process.waitForStarted())
725 return false;
728 while(process.state() == QProcess::Running)
730 loop.exec();
731 while(process.canReadLine())
733 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
737 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
738 return (process.exitCode() == 0);
741 bool UpdateDialog::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
743 QRegExp value("^(\\w+)=(.+)$");
744 QRegExp section("^\\[(.+)\\]$");
746 QDate updateInfoDate;
747 updateInfo->resetInfo();
749 QFile data(file);
750 if(!data.open(QIODevice::ReadOnly))
752 qWarning("Cannot open update info file for reading!");
753 return false;
756 bool inHeader = false;
757 bool inSection = false;
759 while(!data.atEnd())
761 QString line = QString::fromLatin1(data.readLine()).trimmed();
762 if(section.indexIn(line) >= 0)
764 m_logFile->append(QString("Sec: [%1]").arg(section.cap(1)));
765 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
766 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
767 continue;
769 if(inSection && (value.indexIn(line) >= 0))
771 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
772 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
774 bool ok = false;
775 unsigned int temp = value.cap(2).toUInt(&ok);
776 if(ok) updateInfo->m_buildNo = temp;
778 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
780 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
781 if(temp.isValid()) updateInfo->m_buildDate = temp;
783 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
785 updateInfo->m_downloadSite = value.cap(2).trimmed();
787 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
789 updateInfo->m_downloadAddress = value.cap(2).trimmed();
791 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
793 updateInfo->m_downloadFilename = value.cap(2).trimmed();
795 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
797 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
800 if(inHeader && (value.indexIn(line) >= 0))
802 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
803 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
805 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
806 if(temp.isValid()) updateInfoDate = temp;
811 if(!updateInfoDate.isValid())
813 updateInfo->resetInfo();
814 m_logFile->append("WARNING: Version info timestamp is missing!");
815 return false;
817 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < QDate::currentDate())
819 updateInfo->resetInfo();
820 m_logFile->append(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
821 return false;
823 else if(QDate::currentDate() < updateInfoDate)
825 m_logFile->append("Version info is from the future, take care!");
826 qWarning("Version info is from the future, take care!");
829 bool complete = true;
831 if(!(updateInfo->m_buildNo > 0)) complete = false;
832 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
833 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
834 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
835 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
836 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
838 if(!complete)
840 m_logFile->append("WARNING: Version info is incomplete!");
843 return complete;
846 void UpdateDialog::linkActivated(const QString &link)
848 QDesktopServices::openUrl(QUrl(link));
851 void UpdateDialog::applyUpdate(void)
853 installButton->setEnabled(false);
854 closeButton->setEnabled(false);
855 retryButton->setEnabled(false);
857 if(m_updateInfo)
859 statusLabel->setText(tr("Update is being downloaded, please be patient..."));
860 frameAnimation->show();
861 if(hintLabel->isVisible()) hintLabel->hide();
862 if(hintIcon->isVisible()) hintIcon->hide();
863 int oldMax = progressBar->maximum();
864 int oldMin = progressBar->minimum();
865 progressBar->setRange(0, 0);
866 QApplication::processEvents();
868 QProcess process;
869 QStringList args;
870 QEventLoop loop;
872 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
873 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
875 args << QString("/Location=%1").arg(m_updateInfo->m_downloadAddress);
876 args << QString("/Filename=%1").arg(m_updateInfo->m_downloadFilename);
877 args << QString("/TicketID=%1").arg(m_updateInfo->m_downloadFilecode);
878 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
879 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
880 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(m_updateInfo->m_buildNo));
882 QApplication::setOverrideCursor(Qt::WaitCursor);
883 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
884 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
886 process.start(m_binaryUpdater, args);
887 bool updateStarted = process.waitForStarted();
888 if(updateStarted)
890 m_updaterProcess = process.pid()->dwProcessId;
891 loop.exec();
893 m_updaterProcess = NULL;
894 QApplication::restoreOverrideCursor();
896 hintLabel->show();
897 hintIcon->show();
898 progressBar->setRange(oldMin, oldMax);
899 progressBar->setValue(oldMax);
900 frameAnimation->hide();
902 if(updateStarted && (process.exitCode() == 0))
904 statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
905 m_updateReadyToInstall = true;
906 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
907 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
908 accept();
910 else
912 statusLabel->setText(tr("Update failed. Please try again or download manually!"));
913 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
914 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
915 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), 100, 100);
919 installButton->setEnabled(true);
920 closeButton->setEnabled(true);
923 void UpdateDialog::logButtonClicked(void)
925 LogViewDialog *logView = new LogViewDialog(this);
926 logView->exec(*m_logFile);
927 LAMEXP_DELETE(logView);
930 void UpdateDialog::progressBarValueChanged(int value)
932 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), value, progressBar->maximum());
935 void UpdateDialog::testKnownWebSites(void)
937 int connectionScore = 0;
939 // ----- Initialization ----- //
941 progressBar->setValue(0);
942 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
943 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
944 installButton->setEnabled(false);
945 closeButton->setEnabled(false);
946 retryButton->setEnabled(false);
947 logButton->setEnabled(false);
948 if(infoLabel->isVisible()) infoLabel->hide();
949 if(hintLabel->isVisible()) hintLabel->hide();
950 if(hintIcon->isVisible()) hintIcon->hide();
951 frameAnimation->show();
953 QApplication::processEvents();
954 QApplication::setOverrideCursor(Qt::WaitCursor);
956 // ----- Test Internet Connection ----- //
958 statusLabel->setText("Testing all known hosts, this may take a few minutes...");
960 m_logFile->clear();
961 m_logFile->append("Checking internet connection...");
963 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
964 while(!connectedState.isFinished())
966 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
969 if(!connectedState.result())
971 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
972 if(!retryButton->isVisible()) retryButton->show();
973 if(!logButton->isVisible()) logButton->show();
974 closeButton->setEnabled(true);
975 retryButton->setEnabled(true);
976 logButton->setEnabled(true);
977 if(frameAnimation->isVisible()) frameAnimation->hide();
978 statusLabel->setText(tr("It appears that the computer currently is offline!"));
979 progressBar->setValue(progressBar->maximum());
980 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
981 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
982 hintIcon->show();
983 hintLabel->show();
984 LAMEXP_DELETE(m_updateInfo);
985 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
986 QApplication::restoreOverrideCursor();
987 progressBar->setValue(progressBar->maximum());
988 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
989 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
990 return;
993 // ----- Test Known Hosts Connectivity ----- //
995 QStringList hostList;
996 for(int i = 0; known_hosts[i]; i++)
998 hostList << QString::fromLatin1(known_hosts[i]);
1001 qDebug("[Known Hosts]");
1003 int hostCount = hostList.count();
1004 while(!hostList.isEmpty())
1006 QString currentHost = hostList.takeFirst();
1007 progressBar->setValue(qRound((static_cast<double>(progressBar->maximum() - 1) / static_cast<double>(hostCount)) * static_cast<double>(connectionScore)) + 1);
1008 qDebug("Testing: %s", currentHost.toLatin1().constData());
1009 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
1010 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
1011 bool httpOk = false;
1012 if(getFile(currentHost, outFile, 0, &httpOk))
1014 connectionScore++;
1016 else
1018 if(httpOk)
1020 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
1021 connectionScore++;
1023 else
1025 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
1028 QFile::remove(outFile);
1031 if(connectionScore < hostCount)
1033 if(!retryButton->isVisible()) retryButton->show();
1034 if(!logButton->isVisible()) logButton->show();
1035 closeButton->setEnabled(true);
1036 retryButton->setEnabled(true);
1037 logButton->setEnabled(true);
1038 if(frameAnimation->isVisible()) frameAnimation->hide();
1039 statusLabel->setText("At least one host could not be reached!");
1040 progressBar->setValue(progressBar->maximum());
1041 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
1042 hintLabel->setText("Please make sure your internet connection is working properly and try again.");
1043 hintIcon->show();
1044 hintLabel->show();
1045 LAMEXP_DELETE(m_updateInfo);
1046 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1047 QApplication::restoreOverrideCursor();
1048 progressBar->setValue(progressBar->maximum());
1049 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
1050 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
1051 return;
1054 // ----- Done ----- //
1056 QApplication::restoreOverrideCursor();
1057 progressBar->setValue(progressBar->maximum());
1059 statusLabel->setText("Test completed.");
1060 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
1061 hintLabel->setText("Congratulations, the test has completed.");
1062 if(frameAnimation->isVisible()) frameAnimation->hide();
1063 hintIcon->show();
1064 hintLabel->show();
1065 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
1066 MessageBeep(MB_ICONINFORMATION);
1068 closeButton->setEnabled(true);
1069 if(retryButton->isVisible()) retryButton->hide();
1070 if(logButton->isVisible()) logButton->hide();
1071 if(frameAnimation->isVisible()) frameAnimation->hide();