Account for the fact that some web-sites send "HTTP 200 OK" successfully, but then...
[LameXP.git] / src / Dialog_Update.cpp
blob47a43e02ed60ef289a72ca5dc17c41fe51972c70
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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 NULL
67 static const char *update_mirrors_back[] =
69 "http://mplayer.savedonthe.net/",
70 "http://www.tricksoft.de/",
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://www.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; U; Linux x86_64; en-US; rv:1.9.2.12) Gecko/20101101 IceCat/3.6.12 (like Firefox/3.6.12)";
149 static BOOL getInternetConnectedState(void)
151 DWORD lpdwFlags = NULL;
152 BOOL result = InternetGetConnectedState(&lpdwFlags, NULL);
153 return result;
156 ///////////////////////////////////////////////////////////////////////////////
158 class UpdateInfo
160 public:
161 UpdateInfo(void) { resetInfo(); }
163 void resetInfo(void)
165 m_buildNo = 0;
166 m_buildDate.setDate(1900, 1, 1);
167 m_downloadSite.clear();
168 m_downloadAddress.clear();
169 m_downloadFilename.clear();
170 m_downloadFilecode.clear();
173 unsigned int m_buildNo;
174 QDate m_buildDate;
175 QString m_downloadSite;
176 QString m_downloadAddress;
177 QString m_downloadFilename;
178 QString m_downloadFilecode;
181 ///////////////////////////////////////////////////////////////////////////////
183 UpdateDialog::UpdateDialog(SettingsModel *settings, QWidget *parent)
185 QDialog(parent),
186 m_binaryWGet(lamexp_lookup_tool("wget.exe")),
187 m_binaryGnuPG(lamexp_lookup_tool("gpgv.exe")),
188 m_binaryUpdater(lamexp_lookup_tool("wupdate.exe")),
189 m_binaryKeys(lamexp_lookup_tool("gpgv.gpg")),
190 m_updateInfo(NULL),
191 m_settings(settings),
192 m_logFile(new QStringList()),
193 m_betaUpdates(settings ? (settings->autoUpdateCheckBeta() || lamexp_version_demo()) : lamexp_version_demo()),
194 m_success(false),
195 m_updateReadyToInstall(false)
197 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryUpdater.isEmpty() || m_binaryKeys.isEmpty())
199 throw "Tools not initialized correctly!";
202 //Init the dialog, from the .ui file
203 setupUi(this);
204 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
206 //Disable "X" button
207 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
208 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
210 //Init animation
211 m_animator = new QMovie(":/images/Loading3.gif");
212 labelAnimationCenter->setMovie(m_animator);
213 m_animator->start();
215 //Indicate beta updates
216 if(m_betaUpdates)
218 setWindowTitle(windowTitle().append(" [Beta]"));
221 //Enable button
222 connect(retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
223 connect(installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
224 connect(infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
225 connect(logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
227 //Enable progress bar
228 connect(progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
231 UpdateDialog::~UpdateDialog(void)
233 if(m_animator) m_animator->stop();
235 LAMEXP_DELETE(m_updateInfo);
236 LAMEXP_DELETE(m_logFile);
237 LAMEXP_DELETE(m_animator);
239 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
240 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
243 void UpdateDialog::showEvent(QShowEvent *event)
245 QDialog::showEvent(event);
247 labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), lamexp_version_date().toString(Qt::ISODate)));
248 labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
250 installButton->setEnabled(false);
251 closeButton->setEnabled(false);
252 retryButton->setEnabled(false);
253 logButton->setEnabled(false);
254 retryButton->hide();
255 logButton->hide();
256 infoLabel->hide();
257 hintLabel->hide();
258 hintIcon->hide();
259 frameAnimation->hide();
261 int counter = 2;
262 for(int i = 0; known_hosts[i]; i++) counter++;
263 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
264 for(int i = 0; update_mirrors_back[i]; i++) counter++;
266 progressBar->setMaximum(counter);
267 progressBar->setValue(0);
269 QTimer::singleShot(0, this, SLOT(updateInit()));
272 void UpdateDialog::closeEvent(QCloseEvent *event)
274 if(!closeButton->isEnabled())
276 event->ignore();
278 else
280 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
281 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
285 void UpdateDialog::keyPressEvent(QKeyEvent *e)
287 if(e->key() == Qt::Key_F11)
289 if(closeButton->isEnabled()) logButtonClicked();
291 else if((e->key() == Qt::Key_F12) && e->modifiers().testFlag(Qt::ControlModifier))
293 if(closeButton->isEnabled())
295 testKnownWebSites();
296 logButtonClicked();
299 else
301 QDialog::keyPressEvent(e);
305 bool UpdateDialog::winEvent(MSG *message, long *result)
307 return WinSevenTaskbar::handleWinEvent(message, result);
310 void UpdateDialog::updateInit(void)
312 setMinimumSize(size());
313 setMaximumHeight(height());
314 QApplication::processEvents();
315 checkForUpdates();
318 void UpdateDialog::checkForUpdates(void)
320 bool success = false;
321 int connectionScore = 0;
323 // ----- Initialization ----- //
325 m_updateInfo = new UpdateInfo;
327 progressBar->setValue(0);
328 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
329 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
330 installButton->setEnabled(false);
331 closeButton->setEnabled(false);
332 retryButton->setEnabled(false);
333 logButton->setEnabled(false);
334 if(infoLabel->isVisible()) infoLabel->hide();
335 if(hintLabel->isVisible()) hintLabel->hide();
336 if(hintIcon->isVisible()) hintIcon->hide();
337 frameAnimation->show();
339 QApplication::processEvents();
340 QApplication::setOverrideCursor(Qt::WaitCursor);
342 // ----- Test Internet Connection ----- //
344 statusLabel->setText(tr("Testing your internet connection, please wait..."));
346 m_logFile->clear();
347 m_logFile->append("Checking internet connection...");
349 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
350 while(!connectedState.isFinished())
352 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
355 if(!connectedState.result())
357 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
358 if(!retryButton->isVisible()) retryButton->show();
359 if(!logButton->isVisible()) logButton->show();
360 closeButton->setEnabled(true);
361 retryButton->setEnabled(true);
362 logButton->setEnabled(true);
363 if(frameAnimation->isVisible()) frameAnimation->hide();
364 statusLabel->setText(tr("It appears that the computer currently is offline!"));
365 progressBar->setValue(progressBar->maximum());
366 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
367 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
368 hintIcon->show();
369 hintLabel->show();
370 LAMEXP_DELETE(m_updateInfo);
371 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
372 QApplication::restoreOverrideCursor();
373 progressBar->setValue(progressBar->maximum());
374 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
375 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
376 return;
379 // ----- Test Known Hosts Connectivity ----- //
381 QStringList hostList;
382 for(int i = 0; known_hosts[i]; i++)
384 hostList << QString::fromLatin1(known_hosts[i]);
387 qsrand(time(NULL));
388 while(!hostList.isEmpty())
390 progressBar->setValue(progressBar->value() + 1);
391 QString currentHost = hostList.takeAt(qrand() % hostList.count());
392 if(connectionScore < MIN_CONNSCORE)
394 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
395 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
396 bool httpOk = false;
397 if(getFile(currentHost, outFile, 0, &httpOk))
399 connectionScore++;
401 if(httpOk)
403 connectionScore++;
405 QFile::remove(outFile);
407 else
409 QApplication::processEvents();
410 Sleep(8);
414 if(connectionScore < MIN_CONNSCORE)
416 if(!retryButton->isVisible()) retryButton->show();
417 if(!logButton->isVisible()) logButton->show();
418 closeButton->setEnabled(true);
419 retryButton->setEnabled(true);
420 logButton->setEnabled(true);
421 if(frameAnimation->isVisible()) frameAnimation->hide();
422 statusLabel->setText(tr("Network connectivity test has failed!"));
423 progressBar->setValue(progressBar->maximum());
424 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
425 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
426 hintIcon->show();
427 hintLabel->show();
428 LAMEXP_DELETE(m_updateInfo);
429 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
430 QApplication::restoreOverrideCursor();
431 progressBar->setValue(progressBar->maximum());
432 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
433 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
434 return;
437 // ----- Build Mirror List ----- //
439 statusLabel->setText(tr("Checking for new updates online, please wait..."));
440 m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
442 QStringList mirrorList;
443 for(int index = 0; update_mirrors_prim[index]; index++)
445 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
448 qsrand(time(NULL));
449 for(int i = 0; i < 64; i++)
451 mirrorList.swap(i % mirrorList.count(), qrand() % mirrorList.count());
454 for(int index = 0; update_mirrors_back[index]; index++)
456 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
459 // ----- Fetch Update Info From Server ----- //
461 while(!mirrorList.isEmpty())
463 QString currentMirror = mirrorList.takeFirst();
464 progressBar->setValue(progressBar->value() + 1);
465 if(!success)
467 if(tryUpdateMirror(m_updateInfo, currentMirror))
469 success = true;
472 else
474 QApplication::processEvents();
475 Sleep(15);
479 QApplication::restoreOverrideCursor();
480 progressBar->setValue(progressBar->maximum());
482 if(!success)
484 if(!retryButton->isVisible()) retryButton->show();
485 if(!logButton->isVisible()) logButton->show();
486 closeButton->setEnabled(true);
487 retryButton->setEnabled(true);
488 logButton->setEnabled(true);
489 if(frameAnimation->isVisible()) frameAnimation->hide();
490 statusLabel->setText(tr("Failed to fetch update information from server!"));
491 progressBar->setValue(progressBar->maximum());
492 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
493 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
494 hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
495 hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
496 hintIcon->show();
497 hintLabel->show();
498 LAMEXP_DELETE(m_updateInfo);
499 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
500 return;
503 // ----- Download New Program Version ----- //
505 labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
506 infoLabel->show();
507 infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), m_updateInfo->m_downloadSite));
508 QApplication::processEvents();
510 if(m_updateInfo->m_buildNo > lamexp_version_build())
512 installButton->setEnabled(true);
513 statusLabel->setText(tr("A new version of LameXP is available!"));
514 hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
515 hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
516 if(frameAnimation->isVisible()) frameAnimation->hide();
517 hintIcon->show();
518 hintLabel->show();
519 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
520 MessageBeep(MB_ICONINFORMATION);
522 else if(m_updateInfo->m_buildNo == lamexp_version_build())
524 statusLabel->setText(tr("No new updates available at this time."));
525 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
526 hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
527 if(frameAnimation->isVisible()) frameAnimation->hide();
528 hintIcon->show();
529 hintLabel->show();
530 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
531 MessageBeep(MB_ICONINFORMATION);
533 else
535 statusLabel->setText(tr("Your version appears to be newer than the latest release."));
536 hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
537 hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
538 if(frameAnimation->isVisible()) frameAnimation->hide();
539 hintIcon->show();
540 hintLabel->show();
541 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
542 MessageBeep(MB_ICONEXCLAMATION);
545 closeButton->setEnabled(true);
546 if(retryButton->isVisible()) retryButton->hide();
547 if(logButton->isVisible()) logButton->hide();
548 if(frameAnimation->isVisible()) frameAnimation->hide();
550 m_success = true;
553 bool UpdateDialog::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
555 bool success = false;
556 m_logFile->append(QStringList() << "" << "Trying mirror:" << url);
558 QString randPart = lamexp_rand_str();
559 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
560 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
562 m_logFile->append(QStringList() << "" << "Downloading update info:");
563 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
565 m_logFile->append(QStringList() << "" << "Downloading signature:");
566 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
568 if(ok1 && ok2)
570 m_logFile->append(QStringList() << "" << "Download okay, checking signature:");
571 if(checkSignature(outFileVersionInfo, outFileSignature))
573 m_logFile->append(QStringList() << "" << "Signature okay, parsing info:");
574 success = parseVersionInfo(outFileVersionInfo, updateInfo);
576 else
578 m_logFile->append(QStringList() << "" << "Bad signature, take care!");
581 else
583 m_logFile->append(QStringList() << "" << "Download has failed!");
586 QFile::remove(outFileVersionInfo);
587 QFile::remove(outFileSignature);
589 return success;
592 bool UpdateDialog::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
594 QFileInfo output(outFile);
595 output.setCaching(false);
596 if(httpOk) *httpOk = false;
598 if(output.exists())
600 QFile::remove(output.canonicalFilePath());
601 if(output.exists())
603 return false;
607 QProcess process;
608 process.setProcessChannelMode(QProcess::MergedChannels);
609 process.setReadChannel(QProcess::StandardOutput);
610 process.setWorkingDirectory(output.absolutePath());
612 QStringList args;
613 args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
614 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
615 args << "-O" << output.fileName() << url;
617 QEventLoop loop;
618 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
619 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
620 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
622 QTimer timer;
623 timer.setSingleShot(true);
624 timer.setInterval(25000);
625 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
627 process.start(m_binaryWGet, args);
629 if(!process.waitForStarted())
631 return false;
634 timer.start();
636 while(process.state() == QProcess::Running)
638 loop.exec();
639 if(!timer.isActive())
641 qWarning("WGet process timed out <-- killing!");
642 process.kill();
643 process.waitForFinished();
644 m_logFile->append("TIMEOUT !!!");
645 return false;
647 while(process.canReadLine())
649 QString line = QString::fromLatin1(process.readLine()).simplified();
650 m_logFile->append(line);
651 if(line.contains("200 OK", Qt::CaseSensitive))
653 if(httpOk) *httpOk = true;
658 timer.stop();
659 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
661 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
662 return (process.exitCode() == 0) && output.exists() && output.isFile();
665 bool UpdateDialog::checkSignature(const QString &file, const QString &signature)
667 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
669 qWarning("CheckSignature: File and signature should be in same folder!");
670 return false;
672 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
674 qWarning("CheckSignature: File and keyring should be in same folder!");
675 return false;
678 QProcess process;
679 process.setProcessChannelMode(QProcess::MergedChannels);
680 process.setReadChannel(QProcess::StandardOutput);
681 process.setWorkingDirectory(QFileInfo(file).absolutePath());
683 QEventLoop loop;
684 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
685 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
686 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
688 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
690 if(!process.waitForStarted())
692 return false;
695 while(process.state() == QProcess::Running)
697 loop.exec();
698 while(process.canReadLine())
700 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
704 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
705 return (process.exitCode() == 0);
708 bool UpdateDialog::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
710 QRegExp value("^(\\w+)=(.+)$");
711 QRegExp section("^\\[(.+)\\]$");
713 QDate updateInfoDate;
714 updateInfo->resetInfo();
716 QFile data(file);
717 if(!data.open(QIODevice::ReadOnly))
719 qWarning("Cannot open update info file for reading!");
720 return false;
723 bool inHeader = false;
724 bool inSection = false;
726 while(!data.atEnd())
728 QString line = QString::fromLatin1(data.readLine()).trimmed();
729 if(section.indexIn(line) >= 0)
731 m_logFile->append(QString("Sec: [%1]").arg(section.cap(1)));
732 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
733 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
734 continue;
736 if(inSection && (value.indexIn(line) >= 0))
738 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
739 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
741 bool ok = false;
742 unsigned int temp = value.cap(2).toUInt(&ok);
743 if(ok) updateInfo->m_buildNo = temp;
745 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
747 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
748 if(temp.isValid()) updateInfo->m_buildDate = temp;
750 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
752 updateInfo->m_downloadSite = value.cap(2).trimmed();
754 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
756 updateInfo->m_downloadAddress = value.cap(2).trimmed();
758 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
760 updateInfo->m_downloadFilename = value.cap(2).trimmed();
762 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
764 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
767 if(inHeader && (value.indexIn(line) >= 0))
769 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
770 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
772 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
773 if(temp.isValid()) updateInfoDate = temp;
778 if(!updateInfoDate.isValid())
780 updateInfo->resetInfo();
781 m_logFile->append("WARNING: Version info timestamp is missing!");
782 return false;
784 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < QDate::currentDate())
786 updateInfo->resetInfo();
787 m_logFile->append(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
788 return false;
790 else if(QDate::currentDate() < updateInfoDate)
792 m_logFile->append("Version info is from the future, take care!");
793 qWarning("Version info is from the future, take care!");
796 bool complete = true;
798 if(!(updateInfo->m_buildNo > 0)) complete = false;
799 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
800 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
801 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
802 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
803 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
805 if(!complete)
807 m_logFile->append("WARNING: Version info is incomplete!");
810 return complete;
813 void UpdateDialog::linkActivated(const QString &link)
815 QDesktopServices::openUrl(QUrl(link));
818 void UpdateDialog::applyUpdate(void)
820 installButton->setEnabled(false);
821 closeButton->setEnabled(false);
822 retryButton->setEnabled(false);
824 if(m_updateInfo)
826 statusLabel->setText(tr("Update is being downloaded, please be patient..."));
827 frameAnimation->show();
828 if(hintLabel->isVisible()) hintLabel->hide();
829 if(hintIcon->isVisible()) hintIcon->hide();
830 int oldMax = progressBar->maximum();
831 int oldMin = progressBar->minimum();
832 progressBar->setRange(0, 0);
833 QApplication::processEvents();
835 QProcess process;
836 QStringList args;
837 QEventLoop loop;
839 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
840 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
842 args << QString("/Location=%1").arg(m_updateInfo->m_downloadAddress);
843 args << QString("/Filename=%1").arg(m_updateInfo->m_downloadFilename);
844 args << QString("/TicketID=%1").arg(m_updateInfo->m_downloadFilecode);
845 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
846 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
847 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(m_updateInfo->m_buildNo));
849 QApplication::setOverrideCursor(Qt::WaitCursor);
850 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
851 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
853 process.start(m_binaryUpdater, args);
854 loop.exec();
855 QApplication::restoreOverrideCursor();
857 hintLabel->show();
858 hintIcon->show();
859 progressBar->setRange(oldMin, oldMax);
860 progressBar->setValue(oldMax);
861 frameAnimation->hide();
863 if(process.exitCode() == 0)
865 statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
866 m_updateReadyToInstall = true;
867 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
868 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
869 accept();
871 else
873 statusLabel->setText(tr("Update failed. Please try again or download manually!"));
874 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
875 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
876 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), 100, 100);
880 installButton->setEnabled(true);
881 closeButton->setEnabled(true);
884 void UpdateDialog::logButtonClicked(void)
886 LogViewDialog *logView = new LogViewDialog(this);
887 logView->exec(*m_logFile);
888 LAMEXP_DELETE(logView);
891 void UpdateDialog::progressBarValueChanged(int value)
893 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), value, progressBar->maximum());
896 void UpdateDialog::testKnownWebSites(void)
898 int connectionScore = 0;
900 // ----- Initialization ----- //
902 progressBar->setValue(0);
903 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
904 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
905 installButton->setEnabled(false);
906 closeButton->setEnabled(false);
907 retryButton->setEnabled(false);
908 logButton->setEnabled(false);
909 if(infoLabel->isVisible()) infoLabel->hide();
910 if(hintLabel->isVisible()) hintLabel->hide();
911 if(hintIcon->isVisible()) hintIcon->hide();
912 frameAnimation->show();
914 QApplication::processEvents();
915 QApplication::setOverrideCursor(Qt::WaitCursor);
917 // ----- Test Internet Connection ----- //
919 statusLabel->setText("Testing all known hosts, this may take a few minutes...");
921 m_logFile->clear();
922 m_logFile->append("Checking internet connection...");
924 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
925 while(!connectedState.isFinished())
927 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
930 if(!connectedState.result())
932 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
933 if(!retryButton->isVisible()) retryButton->show();
934 if(!logButton->isVisible()) logButton->show();
935 closeButton->setEnabled(true);
936 retryButton->setEnabled(true);
937 logButton->setEnabled(true);
938 if(frameAnimation->isVisible()) frameAnimation->hide();
939 statusLabel->setText(tr("It appears that the computer currently is offline!"));
940 progressBar->setValue(progressBar->maximum());
941 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
942 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
943 hintIcon->show();
944 hintLabel->show();
945 LAMEXP_DELETE(m_updateInfo);
946 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
947 QApplication::restoreOverrideCursor();
948 progressBar->setValue(progressBar->maximum());
949 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
950 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
951 return;
954 // ----- Test Known Hosts Connectivity ----- //
956 QStringList hostList;
957 for(int i = 0; known_hosts[i]; i++)
959 hostList << QString::fromLatin1(known_hosts[i]);
962 int hostCount = hostList.count();
963 while(!hostList.isEmpty())
965 progressBar->setValue(progressBar->value() + 1);
966 QString currentHost = hostList.takeFirst();
967 qDebug("Testing: %s", currentHost.toLatin1().constData());
968 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
969 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
970 bool httpOk = false;
971 if(getFile(currentHost, outFile, 0, &httpOk))
973 connectionScore++;
975 else
977 if(httpOk)
979 qWarning("Connectivity test was slow on the following site:\n%s", currentHost.toLatin1().constData());
980 connectionScore++;
982 else
984 qWarning("Connectivity test failed on the following site:\n%s", currentHost.toLatin1().constData());
987 QFile::remove(outFile);
990 if(connectionScore < hostCount)
992 if(!retryButton->isVisible()) retryButton->show();
993 if(!logButton->isVisible()) logButton->show();
994 closeButton->setEnabled(true);
995 retryButton->setEnabled(true);
996 logButton->setEnabled(true);
997 if(frameAnimation->isVisible()) frameAnimation->hide();
998 statusLabel->setText(tr("Network connectivity test has failed!"));
999 progressBar->setValue(progressBar->maximum());
1000 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
1001 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
1002 hintIcon->show();
1003 hintLabel->show();
1004 LAMEXP_DELETE(m_updateInfo);
1005 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1006 QApplication::restoreOverrideCursor();
1007 progressBar->setValue(progressBar->maximum());
1008 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
1009 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
1010 return;
1013 // ----- Done ----- //
1015 QApplication::restoreOverrideCursor();
1016 progressBar->setValue(progressBar->maximum());
1018 statusLabel->setText("Test completed.");
1019 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
1020 hintLabel->setText("Congratulations, the test has completed.");
1021 if(frameAnimation->isVisible()) frameAnimation->hide();
1022 hintIcon->show();
1023 hintLabel->show();
1024 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
1025 MessageBeep(MB_ICONINFORMATION);
1027 closeButton->setEnabled(true);
1028 if(retryButton->isVisible()) retryButton->hide();
1029 if(logButton->isVisible()) logButton->hide();
1030 if(frameAnimation->isVisible()) frameAnimation->hide();