Some code refactoring regarding the QWaitCondition/QMutex in FileAnalyzer_Task.
[LameXP.git] / src / Dialog_Update.cpp
blobb695548ffb91da0be7cebde38d7fe4a88837f944
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_firstShow(true),
211 m_updateReadyToInstall(false),
212 m_updaterProcess(NULL)
214 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryUpdater.isEmpty() || m_binaryKeys.isEmpty())
216 throw "Tools not initialized correctly!";
219 //Init the dialog, from the .ui file
220 setupUi(this);
221 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
223 //Disable "X" button
224 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
225 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
227 //Init animation
228 m_animator = new QMovie(":/images/Loading3.gif");
229 labelAnimationCenter->setMovie(m_animator);
230 m_animator->start();
232 //Indicate beta updates
233 if(m_betaUpdates)
235 setWindowTitle(windowTitle().append(" [Beta]"));
238 //Enable button
239 connect(retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
240 connect(installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
241 connect(infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
242 connect(logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
244 //Enable progress bar
245 connect(progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
248 UpdateDialog::~UpdateDialog(void)
250 if(m_animator) m_animator->stop();
252 LAMEXP_DELETE(m_updateInfo);
253 LAMEXP_DELETE(m_logFile);
254 LAMEXP_DELETE(m_animator);
256 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
257 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
260 void UpdateDialog::showEvent(QShowEvent *event)
262 QDialog::showEvent(event);
264 if(m_firstShow)
266 labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), lamexp_version_date().toString(Qt::ISODate)));
267 labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
269 installButton->setEnabled(false);
270 closeButton->setEnabled(false);
271 retryButton->setEnabled(false);
272 logButton->setEnabled(false);
273 retryButton->hide();
274 logButton->hide();
275 infoLabel->hide();
276 hintLabel->hide();
277 hintIcon->hide();
278 frameAnimation->hide();
280 int counter = MIN_CONNSCORE + 2;
281 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
282 for(int i = 0; update_mirrors_back[i]; i++) counter++;
284 progressBar->setMaximum(counter);
285 progressBar->setValue(0);
287 m_updaterProcess = NULL;
289 QTimer::singleShot(0, this, SLOT(updateInit()));
290 m_firstShow = false;
294 void UpdateDialog::closeEvent(QCloseEvent *event)
296 if(!closeButton->isEnabled())
298 event->ignore();
300 else
302 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
303 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
307 void UpdateDialog::keyPressEvent(QKeyEvent *e)
309 if(e->key() == Qt::Key_F11)
311 if(closeButton->isEnabled()) logButtonClicked();
313 else if((e->key() == Qt::Key_F12) && e->modifiers().testFlag(Qt::ControlModifier))
315 if(closeButton->isEnabled())
317 testKnownWebSites();
318 logButtonClicked();
321 else
323 QDialog::keyPressEvent(e);
327 bool UpdateDialog::event(QEvent *e)
329 if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
331 EnumWindows(focusUpdaterWindow, reinterpret_cast<LPARAM>(&m_updaterProcess));
333 return QDialog::event(e);
336 bool UpdateDialog::winEvent(MSG *message, long *result)
338 return WinSevenTaskbar::handleWinEvent(message, result);
341 void UpdateDialog::updateInit(void)
343 setMinimumSize(size());
344 setMaximumHeight(height());
345 QApplication::processEvents();
346 checkForUpdates();
349 void UpdateDialog::checkForUpdates(void)
351 bool success = false;
352 int connectionScore = 0;
354 // ----- Initialization ----- //
356 m_updateInfo = new UpdateInfo;
358 progressBar->setValue(0);
359 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
360 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
361 installButton->setEnabled(false);
362 closeButton->setEnabled(false);
363 retryButton->setEnabled(false);
364 logButton->setEnabled(false);
365 if(infoLabel->isVisible()) infoLabel->hide();
366 if(hintLabel->isVisible()) hintLabel->hide();
367 if(hintIcon->isVisible()) hintIcon->hide();
368 frameAnimation->show();
370 QApplication::processEvents();
371 QApplication::setOverrideCursor(Qt::WaitCursor);
373 // ----- Test Internet Connection ----- //
375 statusLabel->setText(tr("Testing your internet connection, please wait..."));
377 m_logFile->clear();
378 m_logFile->append("Checking internet connection...");
380 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
381 while(!connectedState.isFinished())
383 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
386 if(!connectedState.result())
388 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
389 if(!retryButton->isVisible()) retryButton->show();
390 if(!logButton->isVisible()) logButton->show();
391 closeButton->setEnabled(true);
392 retryButton->setEnabled(true);
393 logButton->setEnabled(true);
394 if(frameAnimation->isVisible()) frameAnimation->hide();
395 statusLabel->setText(tr("It appears that the computer currently is offline!"));
396 progressBar->setValue(progressBar->maximum());
397 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
398 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
399 hintIcon->show();
400 hintLabel->show();
401 LAMEXP_DELETE(m_updateInfo);
402 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
403 QApplication::restoreOverrideCursor();
404 progressBar->setValue(progressBar->maximum());
405 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
406 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
407 return;
410 progressBar->setValue(1);
411 QApplication::processEvents();
413 // ----- Test Known Hosts Connectivity ----- //
415 QStringList hostList;
416 for(int i = 0; known_hosts[i]; i++)
418 hostList << QString::fromLatin1(known_hosts[i]);
421 qsrand(time(NULL));
422 while(!hostList.isEmpty())
424 QString currentHost = hostList.takeAt(qrand() % hostList.count());
425 if(connectionScore < MIN_CONNSCORE)
427 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
428 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
429 bool httpOk = false;
430 if(getFile(currentHost, outFile, 0, &httpOk))
432 connectionScore++;
433 progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
434 QApplication::processEvents();
435 Sleep(125);
437 if(httpOk)
439 connectionScore++;
440 progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
441 QApplication::processEvents();
442 Sleep(125);
444 QFile::remove(outFile);
448 if(connectionScore < MIN_CONNSCORE)
450 if(!retryButton->isVisible()) retryButton->show();
451 if(!logButton->isVisible()) logButton->show();
452 closeButton->setEnabled(true);
453 retryButton->setEnabled(true);
454 logButton->setEnabled(true);
455 if(frameAnimation->isVisible()) frameAnimation->hide();
456 statusLabel->setText(tr("Network connectivity test has failed!"));
457 progressBar->setValue(progressBar->maximum());
458 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
459 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
460 hintIcon->show();
461 hintLabel->show();
462 LAMEXP_DELETE(m_updateInfo);
463 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
464 QApplication::restoreOverrideCursor();
465 progressBar->setValue(progressBar->maximum());
466 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
467 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
468 return;
471 // ----- Build Mirror List ----- //
473 statusLabel->setText(tr("Checking for new updates online, please wait..."));
474 m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
476 QStringList mirrorList;
477 for(int index = 0; update_mirrors_prim[index]; index++)
479 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
482 qsrand(time(NULL));
483 for(int i = 0; i < 4375; i++)
485 mirrorList.swap(i % mirrorList.count(), qrand() % mirrorList.count());
488 for(int index = 0; update_mirrors_back[index]; index++)
490 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
493 // ----- Fetch Update Info From Server ----- //
495 while(!mirrorList.isEmpty())
497 QString currentMirror = mirrorList.takeFirst();
498 progressBar->setValue(progressBar->value() + 1);
499 if(!success)
501 if(tryUpdateMirror(m_updateInfo, currentMirror))
503 success = true;
506 else
508 QApplication::processEvents();
509 Sleep(125);
513 QApplication::restoreOverrideCursor();
514 progressBar->setValue(progressBar->maximum());
516 if(!success)
518 if(!retryButton->isVisible()) retryButton->show();
519 if(!logButton->isVisible()) logButton->show();
520 closeButton->setEnabled(true);
521 retryButton->setEnabled(true);
522 logButton->setEnabled(true);
523 if(frameAnimation->isVisible()) frameAnimation->hide();
524 statusLabel->setText(tr("Failed to fetch update information from server!"));
525 progressBar->setValue(progressBar->maximum());
526 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
527 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
528 hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
529 hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
530 hintIcon->show();
531 hintLabel->show();
532 LAMEXP_DELETE(m_updateInfo);
533 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
534 return;
537 // ----- Download New Program Version ----- //
539 labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
540 infoLabel->show();
541 infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), m_updateInfo->m_downloadSite));
542 QApplication::processEvents();
544 if(m_updateInfo->m_buildNo > lamexp_version_build())
546 installButton->setEnabled(true);
547 statusLabel->setText(tr("A new version of LameXP is available!"));
548 hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
549 hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
550 if(frameAnimation->isVisible()) frameAnimation->hide();
551 hintIcon->show();
552 hintLabel->show();
553 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
554 MessageBeep(MB_ICONINFORMATION);
556 else if(m_updateInfo->m_buildNo == lamexp_version_build())
558 statusLabel->setText(tr("No new updates available at this time."));
559 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
560 hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
561 if(frameAnimation->isVisible()) frameAnimation->hide();
562 hintIcon->show();
563 hintLabel->show();
564 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
565 MessageBeep(MB_ICONINFORMATION);
567 else
569 statusLabel->setText(tr("Your version appears to be newer than the latest release."));
570 hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
571 hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
572 if(frameAnimation->isVisible()) frameAnimation->hide();
573 hintIcon->show();
574 hintLabel->show();
575 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
576 MessageBeep(MB_ICONEXCLAMATION);
579 closeButton->setEnabled(true);
580 if(retryButton->isVisible()) retryButton->hide();
581 if(logButton->isVisible()) logButton->hide();
582 if(frameAnimation->isVisible()) frameAnimation->hide();
584 m_success = true;
587 bool UpdateDialog::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
589 bool success = false;
590 m_logFile->append(QStringList() << "" << "Trying mirror:" << url);
592 QString randPart = lamexp_rand_str();
593 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
594 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
596 m_logFile->append(QStringList() << "" << "Downloading update info:");
597 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
599 m_logFile->append(QStringList() << "" << "Downloading signature:");
600 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
602 if(ok1 && ok2)
604 m_logFile->append(QStringList() << "" << "Download okay, checking signature:");
605 if(checkSignature(outFileVersionInfo, outFileSignature))
607 m_logFile->append(QStringList() << "" << "Signature okay, parsing info:");
608 success = parseVersionInfo(outFileVersionInfo, updateInfo);
610 else
612 m_logFile->append(QStringList() << "" << "Bad signature, take care!");
615 else
617 m_logFile->append(QStringList() << "" << "Download has failed!");
620 QFile::remove(outFileVersionInfo);
621 QFile::remove(outFileSignature);
623 return success;
626 bool UpdateDialog::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
628 QFileInfo output(outFile);
629 output.setCaching(false);
630 if(httpOk) *httpOk = false;
632 if(output.exists())
634 QFile::remove(output.canonicalFilePath());
635 if(output.exists())
637 return false;
641 QProcess process;
642 process.setProcessChannelMode(QProcess::MergedChannels);
643 process.setReadChannel(QProcess::StandardOutput);
644 process.setWorkingDirectory(output.absolutePath());
646 QStringList args;
647 args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
648 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
649 args << "-O" << output.fileName() << url;
651 QEventLoop loop;
652 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
653 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
654 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
656 QTimer timer;
657 timer.setSingleShot(true);
658 timer.setInterval(25000);
659 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
661 const QRegExp httpResponseOK("200 OK$");
663 process.start(m_binaryWGet, args);
665 if(!process.waitForStarted())
667 return false;
670 timer.start();
672 while(process.state() == QProcess::Running)
674 loop.exec();
675 bool bTimeOut = (!timer.isActive());
676 while(process.canReadLine())
678 QString line = QString::fromLatin1(process.readLine()).simplified();
679 if(line.contains(httpResponseOK))
681 line.append(" [OK]");
682 if(httpOk) *httpOk = true;
684 m_logFile->append(line);
686 if(bTimeOut)
688 qWarning("WGet process timed out <-- killing!");
689 process.kill();
690 process.waitForFinished();
691 m_logFile->append("!!! TIMEOUT !!!");
692 return false;
696 timer.stop();
697 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
699 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
700 return (process.exitCode() == 0) && output.exists() && output.isFile();
703 bool UpdateDialog::checkSignature(const QString &file, const QString &signature)
705 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
707 qWarning("CheckSignature: File and signature should be in same folder!");
708 return false;
710 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
712 qWarning("CheckSignature: File and keyring should be in same folder!");
713 return false;
716 QProcess process;
717 process.setProcessChannelMode(QProcess::MergedChannels);
718 process.setReadChannel(QProcess::StandardOutput);
719 process.setWorkingDirectory(QFileInfo(file).absolutePath());
721 QEventLoop loop;
722 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
723 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
724 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
726 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
728 if(!process.waitForStarted())
730 return false;
733 while(process.state() == QProcess::Running)
735 loop.exec();
736 while(process.canReadLine())
738 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
742 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
743 return (process.exitCode() == 0);
746 bool UpdateDialog::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
748 QRegExp value("^(\\w+)=(.+)$");
749 QRegExp section("^\\[(.+)\\]$");
751 QDate updateInfoDate;
752 updateInfo->resetInfo();
754 QFile data(file);
755 if(!data.open(QIODevice::ReadOnly))
757 qWarning("Cannot open update info file for reading!");
758 return false;
761 bool inHeader = false;
762 bool inSection = false;
764 while(!data.atEnd())
766 QString line = QString::fromLatin1(data.readLine()).trimmed();
767 if(section.indexIn(line) >= 0)
769 m_logFile->append(QString("Sec: [%1]").arg(section.cap(1)));
770 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
771 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
772 continue;
774 if(inSection && (value.indexIn(line) >= 0))
776 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
777 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
779 bool ok = false;
780 unsigned int temp = value.cap(2).toUInt(&ok);
781 if(ok) updateInfo->m_buildNo = temp;
783 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
785 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
786 if(temp.isValid()) updateInfo->m_buildDate = temp;
788 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
790 updateInfo->m_downloadSite = value.cap(2).trimmed();
792 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
794 updateInfo->m_downloadAddress = value.cap(2).trimmed();
796 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
798 updateInfo->m_downloadFilename = value.cap(2).trimmed();
800 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
802 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
805 if(inHeader && (value.indexIn(line) >= 0))
807 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
808 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
810 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
811 if(temp.isValid()) updateInfoDate = temp;
816 if(!updateInfoDate.isValid())
818 updateInfo->resetInfo();
819 m_logFile->append("WARNING: Version info timestamp is missing!");
820 return false;
822 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < QDate::currentDate())
824 updateInfo->resetInfo();
825 m_logFile->append(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
826 return false;
828 else if(QDate::currentDate() < updateInfoDate)
830 m_logFile->append("Version info is from the future, take care!");
831 qWarning("Version info is from the future, take care!");
834 bool complete = true;
836 if(!(updateInfo->m_buildNo > 0)) complete = false;
837 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
838 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
839 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
840 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
841 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
843 if(!complete)
845 m_logFile->append("WARNING: Version info is incomplete!");
848 return complete;
851 void UpdateDialog::linkActivated(const QString &link)
853 QDesktopServices::openUrl(QUrl(link));
856 void UpdateDialog::applyUpdate(void)
858 installButton->setEnabled(false);
859 closeButton->setEnabled(false);
860 retryButton->setEnabled(false);
862 if(m_updateInfo)
864 statusLabel->setText(tr("Update is being downloaded, please be patient..."));
865 frameAnimation->show();
866 if(hintLabel->isVisible()) hintLabel->hide();
867 if(hintIcon->isVisible()) hintIcon->hide();
868 int oldMax = progressBar->maximum();
869 int oldMin = progressBar->minimum();
870 progressBar->setRange(0, 0);
871 QApplication::processEvents();
873 QProcess process;
874 QStringList args;
875 QEventLoop loop;
877 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
878 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
880 args << QString("/Location=%1").arg(m_updateInfo->m_downloadAddress);
881 args << QString("/Filename=%1").arg(m_updateInfo->m_downloadFilename);
882 args << QString("/TicketID=%1").arg(m_updateInfo->m_downloadFilecode);
883 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
884 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
885 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(m_updateInfo->m_buildNo));
887 QApplication::setOverrideCursor(Qt::WaitCursor);
888 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
889 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
891 process.start(m_binaryUpdater, args);
892 bool updateStarted = process.waitForStarted();
893 if(updateStarted)
895 m_updaterProcess = process.pid()->dwProcessId;
896 loop.exec();
898 m_updaterProcess = NULL;
899 QApplication::restoreOverrideCursor();
901 hintLabel->show();
902 hintIcon->show();
903 progressBar->setRange(oldMin, oldMax);
904 progressBar->setValue(oldMax);
905 frameAnimation->hide();
907 if(updateStarted && (process.exitCode() == 0))
909 statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
910 m_updateReadyToInstall = true;
911 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
912 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
913 accept();
915 else
917 statusLabel->setText(tr("Update failed. Please try again or download manually!"));
918 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
919 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
920 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), 100, 100);
924 installButton->setEnabled(true);
925 closeButton->setEnabled(true);
928 void UpdateDialog::logButtonClicked(void)
930 LogViewDialog *logView = new LogViewDialog(this);
931 logView->exec(*m_logFile);
932 LAMEXP_DELETE(logView);
935 void UpdateDialog::progressBarValueChanged(int value)
937 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), value, progressBar->maximum());
940 void UpdateDialog::testKnownWebSites(void)
942 int connectionScore = 0;
944 // ----- Initialization ----- //
946 progressBar->setValue(0);
947 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
948 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
949 installButton->setEnabled(false);
950 closeButton->setEnabled(false);
951 retryButton->setEnabled(false);
952 logButton->setEnabled(false);
953 if(infoLabel->isVisible()) infoLabel->hide();
954 if(hintLabel->isVisible()) hintLabel->hide();
955 if(hintIcon->isVisible()) hintIcon->hide();
956 frameAnimation->show();
958 QApplication::processEvents();
959 QApplication::setOverrideCursor(Qt::WaitCursor);
961 // ----- Test Internet Connection ----- //
963 statusLabel->setText("Testing all known hosts, this may take a few minutes...");
965 m_logFile->clear();
966 m_logFile->append("Checking internet connection...");
968 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
969 while(!connectedState.isFinished())
971 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
974 if(!connectedState.result())
976 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
977 if(!retryButton->isVisible()) retryButton->show();
978 if(!logButton->isVisible()) logButton->show();
979 closeButton->setEnabled(true);
980 retryButton->setEnabled(true);
981 logButton->setEnabled(true);
982 if(frameAnimation->isVisible()) frameAnimation->hide();
983 statusLabel->setText(tr("It appears that the computer currently is offline!"));
984 progressBar->setValue(progressBar->maximum());
985 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
986 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
987 hintIcon->show();
988 hintLabel->show();
989 LAMEXP_DELETE(m_updateInfo);
990 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
991 QApplication::restoreOverrideCursor();
992 progressBar->setValue(progressBar->maximum());
993 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
994 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
995 return;
998 // ----- Test Known Hosts Connectivity ----- //
1000 QStringList hostList;
1001 for(int i = 0; known_hosts[i]; i++)
1003 hostList << QString::fromLatin1(known_hosts[i]);
1006 qDebug("[Known Hosts]");
1008 int hostCount = hostList.count();
1009 while(!hostList.isEmpty())
1011 QString currentHost = hostList.takeFirst();
1012 progressBar->setValue(qRound((static_cast<double>(progressBar->maximum() - 1) / static_cast<double>(hostCount)) * static_cast<double>(connectionScore)) + 1);
1013 qDebug("Testing: %s", currentHost.toLatin1().constData());
1014 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
1015 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
1016 bool httpOk = false;
1017 if(getFile(currentHost, outFile, 0, &httpOk))
1019 connectionScore++;
1021 else
1023 if(httpOk)
1025 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
1026 connectionScore++;
1028 else
1030 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
1033 QFile::remove(outFile);
1036 if(connectionScore < hostCount)
1038 if(!retryButton->isVisible()) retryButton->show();
1039 if(!logButton->isVisible()) logButton->show();
1040 closeButton->setEnabled(true);
1041 retryButton->setEnabled(true);
1042 logButton->setEnabled(true);
1043 if(frameAnimation->isVisible()) frameAnimation->hide();
1044 statusLabel->setText("At least one host could not be reached!");
1045 progressBar->setValue(progressBar->maximum());
1046 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
1047 hintLabel->setText("Please make sure your internet connection is working properly and try again.");
1048 hintIcon->show();
1049 hintLabel->show();
1050 LAMEXP_DELETE(m_updateInfo);
1051 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1052 QApplication::restoreOverrideCursor();
1053 progressBar->setValue(progressBar->maximum());
1054 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
1055 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
1056 return;
1059 // ----- Done ----- //
1061 QApplication::restoreOverrideCursor();
1062 progressBar->setValue(progressBar->maximum());
1064 statusLabel->setText("Test completed.");
1065 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
1066 hintLabel->setText("Congratulations, the test has completed.");
1067 if(frameAnimation->isVisible()) frameAnimation->hide();
1068 hintIcon->show();
1069 hintLabel->show();
1070 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
1071 MessageBeep(MB_ICONINFORMATION);
1073 closeButton->setEnabled(true);
1074 if(retryButton->isVisible()) retryButton->hide();
1075 if(logButton->isVisible()) logButton->hide();
1076 if(frameAnimation->isVisible()) frameAnimation->hide();