More code refactoring: Moved most of the Win32 API dependencies into wrapper function...
[LameXP.git] / src / Dialog_Update.cpp
blob6d6f77e0cdaeeae732fa0abccafc682ab7c68996
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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 //UIC includes
25 #include "..\tmp\UIC_UpdateDialog.h"
27 //LameXP includes
28 #include "Global.h"
29 #include "Resource.h"
30 #include "Dialog_LogView.h"
31 #include "Model_Settings.h"
32 #include "WinSevenTaskbar.h"
34 //Qt includes
35 #include <QClipboard>
36 #include <QFileDialog>
37 #include <QTimer>
38 #include <QProcess>
39 #include <QDate>
40 #include <QRegExp>
41 #include <QDesktopServices>
42 #include <QUrl>
43 #include <QCloseEvent>
44 #include <QMovie>
45 #include <QtConcurrentRun>
47 ///////////////////////////////////////////////////////////////////////////////
49 static const char *header_id = "!Update";
50 static const char *section_id = "LameXP";
52 static const char *mirror_url_postfix[] =
54 "update.ver",
55 "update_beta.ver",
56 NULL
59 static const char *update_mirrors_prim[] =
61 "http://muldersoft.com/", // "http://mulder.brhack.net/",
62 "http://mulder.bplaced.net/",
63 "http://mulder.cwsurf.de/",
64 "http://mulder.6te.net/",
65 "http://mulder.webuda.com/",
66 "http://mulder.byethost13.com/",
67 "http://muldersoft.kilu.de/",
68 "http://muldersoft.zxq.net/",
69 "http://lamexp.sourceforge.net/",
70 "http://lordmulder.github.com/LameXP/",
71 "http://lord_mulder.bitbucket.org/",
72 "http://www.tricksoft.de/",
73 NULL
76 static const char *update_mirrors_back[] =
78 "http://mplayer.savedonthe.net/",
79 "http://www.rarewares.org/",
80 "http://lord_mulder.doom9.net/",
81 NULL
84 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
86 "http://www.163.com/",
87 "http://www.ac3filter.net/",
88 "http://www.amazon.com/",
89 "http://www.aol.com/",
90 "http://www.apache.org/",
91 "http://www.apple.com/",
92 "http://www.adobe.com/",
93 "http://www.avidemux.org/",
94 "http://www.babylon.com/",
95 "http://www.baidu.com/",
96 "http://www.bbc.co.uk/",
97 "http://www.bing.com/",
98 "http://www.cnet.com/",
99 "http://cnzz.com/",
100 "http://codecs.com/",
101 "http://qt.digia.com/",
102 "http://www.ebay.com/",
103 "http://www.equation.com/",
104 "http://fc2.com/",
105 "http://www.ffmpeg.org/",
106 "http://www.flickr.com/",
107 "http://www.gitorious.org/",
108 "http://git-scm.com/",
109 "http://www.gnome.org/",
110 "http://www.gnu.org/",
111 "http://go.com/",
112 "http://code.google.com/",
113 "http://www.heise.de/",
114 "http://www.huffingtonpost.co.uk/",
115 "http://www.iana.org/",
116 "http://www.imdb.com/",
117 "http://www.imgburn.com/",
118 "http://imgur.com/",
119 "http://en.jd.com/", //http://en.360buy.com/
120 "http://mirrors.kernel.org/",
121 "http://www.libav.org/",
122 "http://www.linkedin.com/",
123 "http://www.livedoor.com/",
124 "http://www.livejournal.com/",
125 "http://mail.ru/",
126 "http://www.mediafire.com/",
127 "http://www.mozilla.org/en-US/",
128 "http://mplayerhq.hu/",
129 "http://www.msn.com/?st=1",
130 "http://oss.netfarm.it/",
131 "http://www.nytimes.com/",
132 "http://www.opera.com/",
133 "http://www.portablefreeware.com/",
134 "http://qt-project.org/",
135 "http://www.quakelive.com/",
136 "http://www.seamonkey-project.org/",
137 "http://www.sina.com.cn/",
138 "http://www.sohu.com/",
139 "http://www.soso.com/",
140 "http://sourceforge.net/",
141 "http://www.spiegel.de/",
142 "http://tdm-gcc.tdragon.net/",
143 "http://www.tdrsmusic.com/",
144 "http://www.ubuntu.com/",
145 "http://status.twitter.com/",
146 "http://www.uol.com.br/",
147 "http://www.videohelp.com/",
148 "http://www.videolan.org/",
149 "http://www.weibo.com/",
150 "http://www.wikipedia.org/",
151 "http://www.winamp.com/",
152 "http://wordpress.com/",
153 "http://us.yahoo.com/",
154 "http://www.yandex.ru/",
155 "http://www.youtube.com/",
156 "http://www.zedo.com/",
157 "http://ffmpeg.zeranoe.com/",
158 NULL
161 static const int MIN_CONNSCORE = 8;
162 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
163 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
165 ///////////////////////////////////////////////////////////////////////////////
167 class UpdateInfo
169 public:
170 UpdateInfo(void) { resetInfo(); }
172 void resetInfo(void)
174 m_buildNo = 0;
175 m_buildDate.setDate(1900, 1, 1);
176 m_downloadSite.clear();
177 m_downloadAddress.clear();
178 m_downloadFilename.clear();
179 m_downloadFilecode.clear();
182 unsigned int m_buildNo;
183 QDate m_buildDate;
184 QString m_downloadSite;
185 QString m_downloadAddress;
186 QString m_downloadFilename;
187 QString m_downloadFilecode;
190 ///////////////////////////////////////////////////////////////////////////////
192 UpdateDialog::UpdateDialog(SettingsModel *settings, QWidget *parent)
194 QDialog(parent),
195 ui(new Ui::UpdateDialog),
196 m_binaryWGet(lamexp_lookup_tool("wget.exe")),
197 m_binaryGnuPG(lamexp_lookup_tool("gpgv.exe")),
198 m_binaryUpdater(lamexp_lookup_tool("wupdate.exe")),
199 m_binaryKeys(lamexp_lookup_tool("gpgv.gpg")),
200 m_updateInfo(NULL),
201 m_settings(settings),
202 m_logFile(new QStringList()),
203 m_betaUpdates(settings ? (settings->autoUpdateCheckBeta() || lamexp_version_demo()) : lamexp_version_demo()),
204 m_success(false),
205 m_firstShow(true),
206 m_updateReadyToInstall(false),
207 m_updaterProcess(NULL)
209 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryUpdater.isEmpty() || m_binaryKeys.isEmpty())
211 throw "Tools not initialized correctly!";
214 //Init the dialog, from the .ui file
215 ui->setupUi(this);
216 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
218 //Disable "X" button
219 lamexp_enable_close_button(this, false);
221 //Init animation
222 m_animator = new QMovie(":/images/Loading3.gif");
223 ui->labelAnimationCenter->setMovie(m_animator);
224 m_animator->start();
226 //Indicate beta updates
227 if(m_betaUpdates)
229 setWindowTitle(windowTitle().append(" [Beta]"));
232 //Enable button
233 connect(ui->retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
234 connect(ui->installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
235 connect(ui->infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
236 connect(ui->logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
238 //Enable progress bar
239 connect(ui->progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
242 UpdateDialog::~UpdateDialog(void)
244 if(m_animator) m_animator->stop();
246 LAMEXP_DELETE(m_updateInfo);
247 LAMEXP_DELETE(m_logFile);
248 LAMEXP_DELETE(m_animator);
250 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
251 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
253 LAMEXP_DELETE(ui);
256 void UpdateDialog::showEvent(QShowEvent *event)
258 QDialog::showEvent(event);
260 if(m_firstShow)
262 ui->labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), lamexp_version_date().toString(Qt::ISODate)));
263 ui->labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
265 ui->installButton->setEnabled(false);
266 ui->closeButton->setEnabled(false);
267 ui->retryButton->setEnabled(false);
268 ui->logButton->setEnabled(false);
269 ui->retryButton->hide();
270 ui->logButton->hide();
271 ui->infoLabel->hide();
272 ui->hintLabel->hide();
273 ui->hintIcon->hide();
274 ui->frameAnimation->hide();
276 int counter = MIN_CONNSCORE + 2;
277 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
278 for(int i = 0; update_mirrors_back[i]; i++) counter++;
280 ui->progressBar->setMaximum(counter);
281 ui->progressBar->setValue(0);
283 m_updaterProcess = NULL;
285 QTimer::singleShot(0, this, SLOT(updateInit()));
286 m_firstShow = false;
290 void UpdateDialog::closeEvent(QCloseEvent *event)
292 if(!ui->closeButton->isEnabled())
294 event->ignore();
296 else
298 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
299 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
303 void UpdateDialog::keyPressEvent(QKeyEvent *e)
305 if(e->key() == Qt::Key_F11)
307 if(ui->closeButton->isEnabled()) logButtonClicked();
309 else if((e->key() == Qt::Key_F12) && e->modifiers().testFlag(Qt::ControlModifier))
311 if(ui->closeButton->isEnabled())
313 testKnownWebSites();
314 logButtonClicked();
317 else
319 QDialog::keyPressEvent(e);
323 bool UpdateDialog::event(QEvent *e)
325 if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
327 lamexp_bring_process_to_front(m_updaterProcess);
329 return QDialog::event(e);
332 bool UpdateDialog::winEvent(MSG *message, long *result)
334 return WinSevenTaskbar::handleWinEvent(message, result);
337 void UpdateDialog::updateInit(void)
339 setMinimumSize(size());
340 setMaximumHeight(height());
341 QApplication::processEvents();
342 checkForUpdates();
345 void UpdateDialog::checkForUpdates(void)
347 bool success = false;
348 int connectionScore = 0;
350 // ----- Initialization ----- //
352 m_updateInfo = new UpdateInfo;
354 ui->progressBar->setValue(0);
355 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
356 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
357 ui->installButton->setEnabled(false);
358 ui->closeButton->setEnabled(false);
359 ui->retryButton->setEnabled(false);
360 ui->logButton->setEnabled(false);
361 if(ui->infoLabel->isVisible()) ui->infoLabel->hide();
362 if(ui->hintLabel->isVisible()) ui->hintLabel->hide();
363 if(ui->hintIcon->isVisible()) ui->hintIcon->hide();
364 ui->frameAnimation->show();
366 QApplication::processEvents();
367 QApplication::setOverrideCursor(Qt::WaitCursor);
369 // ----- Test Internet Connection ----- //
371 ui->statusLabel->setText(tr("Testing your internet connection, please wait..."));
373 m_logFile->clear();
374 m_logFile->append("Checking internet connection...");
376 QFuture<bool> connectedState = QtConcurrent::run(lamexp_get_connection_state);
377 while(!connectedState.isFinished())
379 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
382 if(!connectedState.result())
384 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
385 if(!ui->retryButton->isVisible()) ui->retryButton->show();
386 if(!ui->logButton->isVisible()) ui->logButton->show();
387 ui->closeButton->setEnabled(true);
388 ui->retryButton->setEnabled(true);
389 ui->logButton->setEnabled(true);
390 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
391 ui->statusLabel->setText(tr("It appears that the computer currently is offline!"));
392 ui->progressBar->setValue(ui->progressBar->maximum());
393 ui->hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
394 ui->hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
395 ui->hintIcon->show();
396 ui->hintLabel->show();
397 LAMEXP_DELETE(m_updateInfo);
398 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_ERROR, true);
399 QApplication::restoreOverrideCursor();
400 ui->progressBar->setValue(ui->progressBar->maximum());
401 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
402 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
403 return;
406 ui->progressBar->setValue(1);
407 QApplication::processEvents();
409 // ----- Test Known Hosts Connectivity ----- //
411 QStringList hostList;
412 for(int i = 0; known_hosts[i]; i++)
414 hostList << QString::fromLatin1(known_hosts[i]);
417 lamexp_seed_rand();
418 while(!hostList.isEmpty())
420 QString currentHost = hostList.takeAt(lamexp_rand() % hostList.count());
421 if(connectionScore < MIN_CONNSCORE)
423 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
424 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
425 bool httpOk = false;
426 if(getFile(currentHost, outFile, 0, &httpOk))
428 connectionScore++;
429 ui->progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
430 QApplication::processEvents();
431 lamexp_sleep(64);
433 if(httpOk)
435 connectionScore++;
436 ui->progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
437 QApplication::processEvents();
438 lamexp_sleep(64);
440 QFile::remove(outFile);
444 if(connectionScore < MIN_CONNSCORE)
446 if(!ui->retryButton->isVisible()) ui->retryButton->show();
447 if(!ui->logButton->isVisible()) ui->logButton->show();
448 ui->closeButton->setEnabled(true);
449 ui->retryButton->setEnabled(true);
450 ui->logButton->setEnabled(true);
451 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
452 ui->statusLabel->setText(tr("Network connectivity test has failed!"));
453 ui->progressBar->setValue(ui->progressBar->maximum());
454 ui->hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
455 ui->hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
456 ui->hintIcon->show();
457 ui->hintLabel->show();
458 LAMEXP_DELETE(m_updateInfo);
459 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_ERROR, true);
460 QApplication::restoreOverrideCursor();
461 ui->progressBar->setValue(ui->progressBar->maximum());
462 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
463 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
464 return;
467 // ----- Build Mirror List ----- //
469 ui->statusLabel->setText(tr("Checking for new updates online, please wait..."));
470 m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
472 QStringList mirrorList;
473 for(int index = 0; update_mirrors_prim[index]; index++)
475 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
478 lamexp_seed_rand();
479 if(const int len = mirrorList.count())
481 const int rounds = len * 1097;
482 for(int i = 0; i < rounds; i++)
484 mirrorList.swap(i % len, lamexp_rand() % len);
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 ui->progressBar->setValue(ui->progressBar->value() + 1);
499 if(!success)
501 if(tryUpdateMirror(m_updateInfo, currentMirror))
503 success = true;
506 else
508 QApplication::processEvents();
509 lamexp_sleep(64);
513 QApplication::restoreOverrideCursor();
514 ui->progressBar->setValue(ui->progressBar->maximum());
516 if(!success)
518 if(!ui->retryButton->isVisible()) ui->retryButton->show();
519 if(!ui->logButton->isVisible()) ui->logButton->show();
520 ui->closeButton->setEnabled(true);
521 ui->retryButton->setEnabled(true);
522 ui->logButton->setEnabled(true);
523 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
524 ui->statusLabel->setText(tr("Failed to fetch update information from server!"));
525 ui->progressBar->setValue(ui->progressBar->maximum());
526 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
527 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
528 ui->hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
529 ui->hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
530 ui->hintIcon->show();
531 ui->hintLabel->show();
532 LAMEXP_DELETE(m_updateInfo);
533 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_ERROR, true);
534 return;
537 // ----- Download New Program Version ----- //
539 ui->labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
540 ui->infoLabel->show();
541 ui->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 ui->installButton->setEnabled(true);
547 ui->statusLabel->setText(tr("A new version of LameXP is available!"));
548 ui->hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
549 ui->hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
550 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
551 ui->hintIcon->show();
552 ui->hintLabel->show();
553 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
554 lamexp_beep(lamexp_beep_info);
556 else if(m_updateInfo->m_buildNo == lamexp_version_build())
558 ui->statusLabel->setText(tr("No new updates available at this time."));
559 ui->hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
560 ui->hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
561 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
562 ui->hintIcon->show();
563 ui->hintLabel->show();
564 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
565 lamexp_beep(lamexp_beep_info);
567 else
569 ui->statusLabel->setText(tr("Your version appears to be newer than the latest release."));
570 ui->hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
571 ui->hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
572 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
573 ui->hintIcon->show();
574 ui->hintLabel->show();
575 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
576 lamexp_beep(lamexp_beep_warning);
579 ui->closeButton->setEnabled(true);
580 if(ui->retryButton->isVisible()) ui->retryButton->hide();
581 if(ui->logButton->isVisible()) ui->logButton->hide();
582 if(ui->frameAnimation->isVisible()) ui->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) < lamexp_current_date_safe())
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(lamexp_current_date_safe() < 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 ui->installButton->setEnabled(false);
859 ui->closeButton->setEnabled(false);
860 ui->retryButton->setEnabled(false);
862 if(m_updateInfo)
864 ui->statusLabel->setText(tr("Update is being downloaded, please be patient..."));
865 ui->frameAnimation->show();
866 if(ui->hintLabel->isVisible()) ui->hintLabel->hide();
867 if(ui->hintIcon->isVisible()) ui->hintIcon->hide();
868 int oldMax = ui->progressBar->maximum();
869 int oldMin = ui->progressBar->minimum();
870 ui->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 = lamexp_process_id(&process);
896 loop.exec();
898 m_updaterProcess = NULL;
899 QApplication::restoreOverrideCursor();
901 ui->hintLabel->show();
902 ui->hintIcon->show();
903 ui->progressBar->setRange(oldMin, oldMax);
904 ui->progressBar->setValue(oldMax);
905 ui->frameAnimation->hide();
907 if(updateStarted && (process.exitCode() == 0))
909 ui->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 ui->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 ui->installButton->setEnabled(true);
925 ui->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, ui->progressBar->maximum());
940 void UpdateDialog::testKnownWebSites(void)
942 int connectionScore = 0;
944 // ----- Initialization ----- //
946 ui->progressBar->setValue(0);
947 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
948 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
949 ui->installButton->setEnabled(false);
950 ui->closeButton->setEnabled(false);
951 ui->retryButton->setEnabled(false);
952 ui->logButton->setEnabled(false);
953 if(ui->infoLabel->isVisible()) ui->infoLabel->hide();
954 if(ui->hintLabel->isVisible()) ui->hintLabel->hide();
955 if(ui->hintIcon->isVisible()) ui->hintIcon->hide();
956 ui->frameAnimation->show();
958 QApplication::processEvents();
959 QApplication::setOverrideCursor(Qt::WaitCursor);
961 // ----- Test Internet Connection ----- //
963 ui->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(lamexp_get_connection_state);
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(!ui->retryButton->isVisible()) ui->retryButton->show();
978 if(!ui->logButton->isVisible()) ui->logButton->show();
979 ui->closeButton->setEnabled(true);
980 ui->retryButton->setEnabled(true);
981 ui->logButton->setEnabled(true);
982 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
983 ui->statusLabel->setText(tr("It appears that the computer currently is offline!"));
984 ui->progressBar->setValue(ui->progressBar->maximum());
985 ui->hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
986 ui->hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
987 ui->hintIcon->show();
988 ui->hintLabel->show();
989 LAMEXP_DELETE(m_updateInfo);
990 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_ERROR, true);
991 QApplication::restoreOverrideCursor();
992 ui->progressBar->setValue(ui->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 ui->progressBar->setValue(qRound((static_cast<double>(ui->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(!ui->retryButton->isVisible()) ui->retryButton->show();
1039 if(!ui->logButton->isVisible()) ui->logButton->show();
1040 ui->closeButton->setEnabled(true);
1041 ui->retryButton->setEnabled(true);
1042 ui->logButton->setEnabled(true);
1043 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
1044 ui->statusLabel->setText("At least one host could not be reached!");
1045 ui->progressBar->setValue(ui->progressBar->maximum());
1046 ui->hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
1047 ui->hintLabel->setText("Please make sure your internet connection is working properly and try again.");
1048 ui->hintIcon->show();
1049 ui->hintLabel->show();
1050 LAMEXP_DELETE(m_updateInfo);
1051 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_ERROR, true);
1052 QApplication::restoreOverrideCursor();
1053 ui->progressBar->setValue(ui->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 ui->progressBar->setValue(ui->progressBar->maximum());
1064 ui->statusLabel->setText("Test completed.");
1065 ui->hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
1066 ui->hintLabel->setText("Congratulations, the test has completed.");
1067 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
1068 ui->hintIcon->show();
1069 ui->hintLabel->show();
1070 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
1071 lamexp_beep(lamexp_beep_info);
1073 ui->closeButton->setEnabled(true);
1074 if(ui->retryButton->isVisible()) ui->retryButton->hide();
1075 if(ui->logButton->isVisible()) ui->logButton->hide();
1076 if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();