OSDN Git Service

Set "MinimumRequiredVersion" to 5.1 (WinXP).
[lamexp/LameXP.git] / src / Dialog_Update.cpp
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.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Dialog_Update.h"
23
24 #include "Global.h"
25 #include "Resource.h"
26 #include "Dialog_LogView.h"
27 #include "Model_Settings.h"
28 #include "WinSevenTaskbar.h"
29
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>
41
42 #include <MMSystem.h>
43 #include <WinInet.h>
44
45 ///////////////////////////////////////////////////////////////////////////////
46
47 static const char *header_id = "!Update";
48 static const char *section_id = "LameXP";
49
50 static const char *mirror_url_postfix[] = 
51 {
52         "update.ver",
53         "update_beta.ver",
54         NULL
55 };
56
57 static const char *update_mirrors_prim[] =
58 {
59         "http://mulder.brhack.net/",
60         "http://mulder.bplaced.net/",
61         "http://mulder.cwsurf.de/",
62         "http://mulder.6te.net/",
63         "http://mulder.webuda.com/",
64 //      "http://free.pages.at/borschdfresser/",
65         "http://lamexp.sourceforge.net/",
66         "http://lordmulder.github.com/LameXP/",
67         "http://lord_mulder.bitbucket.org/",
68         "http://www.tricksoft.de/",
69         NULL
70 };
71
72 static const char *update_mirrors_back[] =
73 {
74         "http://mplayer.savedonthe.net/",
75         "http://www.rarewares.org/",
76         "http://lord_mulder.doom9.net/",
77         NULL
78 };
79
80 static const char *known_hosts[] =              //Taken form: http://www.alexa.com/topsites !!!
81 {
82         "http://www.163.com/",
83         "http://www.360buy.com/",
84         "http://www.amazon.com/",
85         "http://www.aol.com/",
86         "http://www.apache.org/",
87         "http://www.apple.com/",
88         "http://www.adobe.com/",
89         "http://www.avidemux.org/",
90         "http://www.babylon.com/",
91         "http://www.baidu.com/",
92         "http://www.bbc.co.uk/",
93         "http://www.bing.com/",
94         "http://www.cnet.com/",
95         "http://cnzz.com/",
96         "http://qt.digia.com/",
97         "http://www.ebay.com/",
98         "http://www.equation.com/",
99         "http://fc2.com/",
100         "http://www.ffmpeg.org/",
101         "http://www.flickr.com/",
102         "http://www.gitorious.org/",
103         "http://git-scm.com/",
104         "http://www.gnome.org/",
105         "http://www.gnu.org/",
106         "http://go.com/",
107         "http://code.google.com/",
108         "http://www.heise.de/",
109         "http://www.huffingtonpost.co.uk/",
110         "http://www.iana.org/",
111         "http://www.imdb.com/",
112         "http://www.imgburn.com/",
113         "http://imgur.com/",
114         "http://www.kernel.org/",
115         "http://www.libav.org/",
116         "http://www.linkedin.com/",
117         "http://www.livedoor.com/",
118         "http://www.livejournal.com/",
119         "http://mail.ru/",
120         "http://www.mediafire.com/",
121         "http://www.mozilla.org/en-US/",
122         "http://mplayerhq.hu/",
123         "http://www.msn.com/?st=1",
124         "http://oss.netfarm.it/",
125         "http://www.nytimes.com/",
126         "http://www.opera.com/",
127         "http://www.quakelive.com/",
128         "http://qt-project.org/",
129         "http://www.seamonkey-project.org/",
130         "http://www.sina.com.cn/",
131         "http://www.sohu.com/",
132         "http://www.soso.com/",
133         "http://sourceforge.net/",
134         "http://www.spiegel.de/",
135         "http://tdm-gcc.tdragon.net/",
136         "http://www.tdrsmusic.com/",
137         "http://www.ubuntu.com/",
138         "http://twitter.com/",
139         "http://www.uol.com.br/",
140         "http://www.videohelp.com/",
141         "http://www.videolan.org/",
142         "http://www.weibo.com/",
143         "http://www.wikipedia.org/",
144         "http://wordpress.com/",
145         "http://us.yahoo.com/",
146         "http://www.yandex.ru/",
147         "http://www.youtube.com/",
148         "http://www.zedo.com/",
149         "http://ffmpeg.zeranoe.com/",
150         NULL
151 };
152
153 static const int MIN_CONNSCORE = 8;
154 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
155 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
156
157 static BOOL getInternetConnectedState(void)
158 {
159         DWORD lpdwFlags = NULL;
160         BOOL result = InternetGetConnectedState(&lpdwFlags, NULL);
161         return result;
162 }
163
164 static BOOL CALLBACK focusUpdaterWindow(HWND hwnd, LPARAM lParam)
165 {
166         DWORD processId = *reinterpret_cast<WORD*>(lParam);
167         DWORD windowProcessId = NULL;
168         GetWindowThreadProcessId(hwnd, &windowProcessId);
169         if(windowProcessId == processId)
170         {
171                 SwitchToThisWindow(hwnd, TRUE);
172                 SetForegroundWindow(hwnd);
173                 return FALSE;
174         }
175
176         return TRUE;
177 }
178
179 ///////////////////////////////////////////////////////////////////////////////
180
181 class UpdateInfo
182 {
183 public:
184         UpdateInfo(void) { resetInfo(); }
185         
186         void resetInfo(void)
187         {
188                 m_buildNo = 0;
189                 m_buildDate.setDate(1900, 1, 1);
190                 m_downloadSite.clear();
191                 m_downloadAddress.clear();
192                 m_downloadFilename.clear();
193                 m_downloadFilecode.clear();
194         }
195
196         unsigned int m_buildNo;
197         QDate m_buildDate;
198         QString m_downloadSite;
199         QString m_downloadAddress;
200         QString m_downloadFilename;
201         QString m_downloadFilecode;
202 };
203
204 ///////////////////////////////////////////////////////////////////////////////
205
206 UpdateDialog::UpdateDialog(SettingsModel *settings, QWidget *parent)
207 :
208         QDialog(parent),
209         m_binaryWGet(lamexp_lookup_tool("wget.exe")),
210         m_binaryGnuPG(lamexp_lookup_tool("gpgv.exe")),
211         m_binaryUpdater(lamexp_lookup_tool("wupdate.exe")),
212         m_binaryKeys(lamexp_lookup_tool("gpgv.gpg")),
213         m_updateInfo(NULL),
214         m_settings(settings),
215         m_logFile(new QStringList()),
216         m_betaUpdates(settings ? (settings->autoUpdateCheckBeta() || lamexp_version_demo()) : lamexp_version_demo()),
217         m_success(false),
218         m_firstShow(true),
219         m_updateReadyToInstall(false),
220         m_updaterProcess(NULL)
221 {
222         if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryUpdater.isEmpty() || m_binaryKeys.isEmpty())
223         {
224                 throw "Tools not initialized correctly!";
225         }
226         
227         //Init the dialog, from the .ui file
228         setupUi(this);
229         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
230
231         //Disable "X" button
232         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
233         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
234
235         //Init animation
236         m_animator = new QMovie(":/images/Loading3.gif");
237         labelAnimationCenter->setMovie(m_animator);
238         m_animator->start();
239
240         //Indicate beta updates
241         if(m_betaUpdates)
242         {
243                 setWindowTitle(windowTitle().append(" [Beta]"));
244         }
245         
246         //Enable button
247         connect(retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
248         connect(installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
249         connect(infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
250         connect(logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
251
252         //Enable progress bar
253         connect(progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
254 }
255
256 UpdateDialog::~UpdateDialog(void)
257 {
258         if(m_animator) m_animator->stop();
259         
260         LAMEXP_DELETE(m_updateInfo);
261         LAMEXP_DELETE(m_logFile);
262         LAMEXP_DELETE(m_animator);
263
264         WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
265         WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
266 }
267
268 void UpdateDialog::showEvent(QShowEvent *event)
269 {
270         QDialog::showEvent(event);
271         
272         if(m_firstShow)
273         {
274                 labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), lamexp_version_date().toString(Qt::ISODate)));
275                 labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
276
277                 installButton->setEnabled(false);
278                 closeButton->setEnabled(false);
279                 retryButton->setEnabled(false);
280                 logButton->setEnabled(false);
281                 retryButton->hide();
282                 logButton->hide();
283                 infoLabel->hide();
284                 hintLabel->hide();
285                 hintIcon->hide();
286                 frameAnimation->hide();
287         
288                 int counter = MIN_CONNSCORE + 2;
289                 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
290                 for(int i = 0; update_mirrors_back[i]; i++) counter++;
291
292                 progressBar->setMaximum(counter);
293                 progressBar->setValue(0);
294
295                 m_updaterProcess = NULL;
296
297                 QTimer::singleShot(0, this, SLOT(updateInit()));
298                 m_firstShow = false;
299         }
300 }
301
302 void UpdateDialog::closeEvent(QCloseEvent *event)
303 {
304         if(!closeButton->isEnabled())
305         {
306                 event->ignore();
307         }
308         else
309         {
310                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
311                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
312         }
313 }
314
315 void UpdateDialog::keyPressEvent(QKeyEvent *e)
316 {
317         if(e->key() == Qt::Key_F11)
318         {
319                 if(closeButton->isEnabled()) logButtonClicked();
320         }
321         else if((e->key() == Qt::Key_F12) && e->modifiers().testFlag(Qt::ControlModifier))
322         {
323                 if(closeButton->isEnabled())
324                 {
325                         testKnownWebSites();
326                         logButtonClicked();
327                 }
328         }
329         else
330         {
331                 QDialog::keyPressEvent(e);
332         }
333 }
334
335 bool UpdateDialog::event(QEvent *e)
336 {
337         if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
338         {
339                 EnumWindows(focusUpdaterWindow, reinterpret_cast<LPARAM>(&m_updaterProcess));
340         }
341         return QDialog::event(e);
342 }
343
344 bool UpdateDialog::winEvent(MSG *message, long *result)
345 {
346         return WinSevenTaskbar::handleWinEvent(message, result);
347 }
348
349 void UpdateDialog::updateInit(void)
350 {
351         setMinimumSize(size());
352         setMaximumHeight(height());
353         QApplication::processEvents();
354         checkForUpdates();
355 }
356
357 void UpdateDialog::checkForUpdates(void)
358 {
359         bool success = false;
360         int connectionScore = 0;
361
362         // ----- Initialization ----- //
363
364         m_updateInfo = new UpdateInfo;
365
366         progressBar->setValue(0);
367         WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
368         WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
369         installButton->setEnabled(false);
370         closeButton->setEnabled(false);
371         retryButton->setEnabled(false);
372         logButton->setEnabled(false);
373         if(infoLabel->isVisible()) infoLabel->hide();
374         if(hintLabel->isVisible()) hintLabel->hide();
375         if(hintIcon->isVisible()) hintIcon->hide();
376         frameAnimation->show();
377
378         QApplication::processEvents();
379         QApplication::setOverrideCursor(Qt::WaitCursor);
380
381         // ----- Test Internet Connection ----- //
382
383         statusLabel->setText(tr("Testing your internet connection, please wait..."));
384
385         m_logFile->clear();
386         m_logFile->append("Checking internet connection...");
387         
388         QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
389         while(!connectedState.isFinished())
390         {
391                 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
392         }
393
394         if(!connectedState.result())
395         {
396                 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
397                 if(!retryButton->isVisible()) retryButton->show();
398                 if(!logButton->isVisible()) logButton->show();
399                 closeButton->setEnabled(true);
400                 retryButton->setEnabled(true);
401                 logButton->setEnabled(true);
402                 if(frameAnimation->isVisible()) frameAnimation->hide();
403                 statusLabel->setText(tr("It appears that the computer currently is offline!"));
404                 progressBar->setValue(progressBar->maximum());
405                 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
406                 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
407                 hintIcon->show();
408                 hintLabel->show();
409                 LAMEXP_DELETE(m_updateInfo);
410                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
411                 QApplication::restoreOverrideCursor();
412                 progressBar->setValue(progressBar->maximum());
413                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
414                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
415                 return;
416         }
417         
418         progressBar->setValue(1);
419         QApplication::processEvents();
420
421         // ----- Test Known Hosts Connectivity ----- //
422
423         QStringList hostList;
424         for(int i = 0; known_hosts[i]; i++)
425         {
426                 hostList << QString::fromLatin1(known_hosts[i]);
427         }
428
429         lamexp_seed_rand();
430         while(!hostList.isEmpty())
431         {
432                 QString currentHost = hostList.takeAt(lamexp_rand() % hostList.count());
433                 if(connectionScore < MIN_CONNSCORE)
434                 {
435                         m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
436                         QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
437                         bool httpOk = false;
438                         if(getFile(currentHost, outFile, 0, &httpOk))
439                         {
440                                 connectionScore++;
441                                 progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
442                                 QApplication::processEvents();
443                                 Sleep(64);
444                         }
445                         if(httpOk)
446                         {
447                                 connectionScore++;
448                                 progressBar->setValue(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
449                                 QApplication::processEvents();
450                                 Sleep(64);
451                         }
452                         QFile::remove(outFile);
453                 }
454         }
455
456         if(connectionScore < MIN_CONNSCORE)
457         {
458                 if(!retryButton->isVisible()) retryButton->show();
459                 if(!logButton->isVisible()) logButton->show();
460                 closeButton->setEnabled(true);
461                 retryButton->setEnabled(true);
462                 logButton->setEnabled(true);
463                 if(frameAnimation->isVisible()) frameAnimation->hide();
464                 statusLabel->setText(tr("Network connectivity test has failed!"));
465                 progressBar->setValue(progressBar->maximum());
466                 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
467                 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
468                 hintIcon->show();
469                 hintLabel->show();
470                 LAMEXP_DELETE(m_updateInfo);
471                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
472                 QApplication::restoreOverrideCursor();
473                 progressBar->setValue(progressBar->maximum());
474                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
475                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
476                 return;
477         }
478
479         // ----- Build Mirror List ----- //
480
481         statusLabel->setText(tr("Checking for new updates online, please wait..."));
482         m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
483
484         QStringList mirrorList;
485         for(int index = 0; update_mirrors_prim[index]; index++)
486         {
487                 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
488         }
489
490         lamexp_seed_rand();
491         if(const int len = mirrorList.count())
492         {
493                 const int rounds = len * 1097;
494                 for(int i = 0; i < rounds; i++)
495                 {
496                         mirrorList.swap(i % len, lamexp_rand() % len);
497                 }
498         }
499
500         for(int index = 0; update_mirrors_back[index]; index++)
501         {
502                 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
503         }
504         
505         // ----- Fetch Update Info From Server ----- //
506
507         while(!mirrorList.isEmpty())
508         {
509                 QString currentMirror = mirrorList.takeFirst();
510                 progressBar->setValue(progressBar->value() + 1);
511                 if(!success)
512                 {
513                         if(tryUpdateMirror(m_updateInfo, currentMirror))
514                         {
515                                 success = true;
516                         }
517                 }
518                 else
519                 {
520                         QApplication::processEvents();
521                         Sleep(64);
522                 }
523         }
524         
525         QApplication::restoreOverrideCursor();
526         progressBar->setValue(progressBar->maximum());
527         
528         if(!success)
529         {
530                 if(!retryButton->isVisible()) retryButton->show();
531                 if(!logButton->isVisible()) logButton->show();
532                 closeButton->setEnabled(true);
533                 retryButton->setEnabled(true);
534                 logButton->setEnabled(true);
535                 if(frameAnimation->isVisible()) frameAnimation->hide();
536                 statusLabel->setText(tr("Failed to fetch update information from server!"));
537                 progressBar->setValue(progressBar->maximum());
538                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
539                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
540                 hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
541                 hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
542                 hintIcon->show();
543                 hintLabel->show();
544                 LAMEXP_DELETE(m_updateInfo);
545                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
546                 return;
547         }
548
549         // ----- Download New Program Version ----- //
550         
551         labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
552         infoLabel->show();
553         infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), m_updateInfo->m_downloadSite));
554         QApplication::processEvents();
555         
556         if(m_updateInfo->m_buildNo > lamexp_version_build())
557         {
558                 installButton->setEnabled(true);
559                 statusLabel->setText(tr("A new version of LameXP is available!"));
560                 hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
561                 hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
562                 if(frameAnimation->isVisible()) frameAnimation->hide();
563                 hintIcon->show();
564                 hintLabel->show();
565                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
566                 MessageBeep(MB_ICONINFORMATION);
567         }
568         else if(m_updateInfo->m_buildNo == lamexp_version_build())
569         {
570                 statusLabel->setText(tr("No new updates available at this time."));
571                 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
572                 hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
573                 if(frameAnimation->isVisible()) frameAnimation->hide();
574                 hintIcon->show();
575                 hintLabel->show();
576                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
577                 MessageBeep(MB_ICONINFORMATION);
578         }
579         else
580         {
581                 statusLabel->setText(tr("Your version appears to be newer than the latest release."));
582                 hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
583                 hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
584                 if(frameAnimation->isVisible()) frameAnimation->hide();
585                 hintIcon->show();
586                 hintLabel->show();
587                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
588                 MessageBeep(MB_ICONEXCLAMATION);
589         }
590
591         closeButton->setEnabled(true);
592         if(retryButton->isVisible()) retryButton->hide();
593         if(logButton->isVisible()) logButton->hide();
594         if(frameAnimation->isVisible()) frameAnimation->hide();
595
596         m_success = true;
597 }
598
599 bool UpdateDialog::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
600 {
601         bool success = false;
602         m_logFile->append(QStringList() << "" << "Trying mirror:" << url);
603
604         QString randPart = lamexp_rand_str();
605         QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
606         QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
607
608         m_logFile->append(QStringList() << "" << "Downloading update info:");
609         bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
610
611         m_logFile->append(QStringList() << "" << "Downloading signature:");
612         bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
613
614         if(ok1 && ok2)
615         {
616                 m_logFile->append(QStringList() << "" << "Download okay, checking signature:");
617                 if(checkSignature(outFileVersionInfo, outFileSignature))
618                 {
619                         m_logFile->append(QStringList() << "" << "Signature okay, parsing info:");
620                         success = parseVersionInfo(outFileVersionInfo, updateInfo);
621                 }
622                 else
623                 {
624                         m_logFile->append(QStringList() << "" << "Bad signature, take care!");
625                 }
626         }
627         else
628         {
629                 m_logFile->append(QStringList() << "" << "Download has failed!");
630         }
631
632         QFile::remove(outFileVersionInfo);
633         QFile::remove(outFileSignature);
634         
635         return success;
636 }
637
638 bool UpdateDialog::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
639 {
640         QFileInfo output(outFile);
641         output.setCaching(false);
642         if(httpOk) *httpOk = false;
643
644         if(output.exists())
645         {
646                 QFile::remove(output.canonicalFilePath());
647                 if(output.exists())
648                 {
649                         return false;
650                 }
651         }
652
653         QProcess process;
654         process.setProcessChannelMode(QProcess::MergedChannels);
655         process.setReadChannel(QProcess::StandardOutput);
656         process.setWorkingDirectory(output.absolutePath());
657
658         QStringList args;
659         args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
660         args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
661         args << "-O" << output.fileName() << url;
662
663         QEventLoop loop;
664         connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
665         connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
666         connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
667
668         QTimer timer;
669         timer.setSingleShot(true);
670         timer.setInterval(25000);
671         connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
672
673         const QRegExp httpResponseOK("200 OK$");
674         
675         process.start(m_binaryWGet, args);
676         
677         if(!process.waitForStarted())
678         {
679                 return false;
680         }
681
682         timer.start();
683
684         while(process.state() == QProcess::Running)
685         {
686                 loop.exec();
687                 bool bTimeOut = (!timer.isActive());
688                 while(process.canReadLine())
689                 {
690                         QString line = QString::fromLatin1(process.readLine()).simplified();
691                         if(line.contains(httpResponseOK))
692                         {
693                                 line.append(" [OK]");
694                                 if(httpOk) *httpOk = true;
695                         }
696                         m_logFile->append(line);
697                 }
698                 if(bTimeOut)
699                 {
700                         qWarning("WGet process timed out <-- killing!");
701                         process.kill();
702                         process.waitForFinished();
703                         m_logFile->append("!!! TIMEOUT !!!");
704                         return false;
705                 }
706         }
707         
708         timer.stop();
709         timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
710
711         m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
712         return (process.exitCode() == 0) && output.exists() && output.isFile();
713 }
714
715 bool UpdateDialog::checkSignature(const QString &file, const QString &signature)
716 {
717         if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
718         {
719                 qWarning("CheckSignature: File and signature should be in same folder!");
720                 return false;
721         }
722         if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
723         {
724                 qWarning("CheckSignature: File and keyring should be in same folder!");
725                 return false;
726         }
727
728         QProcess process;
729         process.setProcessChannelMode(QProcess::MergedChannels);
730         process.setReadChannel(QProcess::StandardOutput);
731         process.setWorkingDirectory(QFileInfo(file).absolutePath());
732
733         QEventLoop loop;
734         connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
735         connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
736         connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
737         
738         process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
739
740         if(!process.waitForStarted())
741         {
742                 return false;
743         }
744
745         while(process.state() == QProcess::Running)
746         {
747                 loop.exec();
748                 while(process.canReadLine())
749                 {
750                         m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
751                 }
752         }
753         
754         m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
755         return (process.exitCode() == 0);
756 }
757
758 bool UpdateDialog::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
759 {
760         QRegExp value("^(\\w+)=(.+)$");
761         QRegExp section("^\\[(.+)\\]$");
762
763         QDate updateInfoDate;
764         updateInfo->resetInfo();
765
766         QFile data(file);
767         if(!data.open(QIODevice::ReadOnly))
768         {
769                 qWarning("Cannot open update info file for reading!");
770                 return false;
771         }
772         
773         bool inHeader = false;
774         bool inSection = false;
775         
776         while(!data.atEnd())
777         {
778                 QString line = QString::fromLatin1(data.readLine()).trimmed();
779                 if(section.indexIn(line) >= 0)
780                 {
781                         m_logFile->append(QString("Sec: [%1]").arg(section.cap(1)));
782                         inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
783                         inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
784                         continue;
785                 }
786                 if(inSection && (value.indexIn(line) >= 0))
787                 {
788                         m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
789                         if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
790                         {
791                                 bool ok = false;
792                                 unsigned int temp = value.cap(2).toUInt(&ok);
793                                 if(ok) updateInfo->m_buildNo = temp;
794                         }
795                         else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
796                         {
797                                 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
798                                 if(temp.isValid()) updateInfo->m_buildDate = temp;
799                         }
800                         else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
801                         {
802                                 updateInfo->m_downloadSite = value.cap(2).trimmed();
803                         }
804                         else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
805                         {
806                                 updateInfo->m_downloadAddress = value.cap(2).trimmed();
807                         }
808                         else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
809                         {
810                                 updateInfo->m_downloadFilename = value.cap(2).trimmed();
811                         }
812                         else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
813                         {
814                                 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
815                         }
816                 }
817                 if(inHeader && (value.indexIn(line) >= 0))
818                 {
819                         m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
820                         if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
821                         {
822                                 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
823                                 if(temp.isValid()) updateInfoDate = temp;
824                         }
825                 }
826         }
827         
828         if(!updateInfoDate.isValid())
829         {
830                 updateInfo->resetInfo();
831                 m_logFile->append("WARNING: Version info timestamp is missing!");
832                 return false;
833         }
834         else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < QDate::currentDate())
835         {
836                 updateInfo->resetInfo();
837                 m_logFile->append(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
838                 return false;
839         }
840         else if(QDate::currentDate() < updateInfoDate)
841         {
842                 m_logFile->append("Version info is from the future, take care!");
843                 qWarning("Version info is from the future, take care!");
844         }
845
846         bool complete = true;
847
848         if(!(updateInfo->m_buildNo > 0)) complete = false;
849         if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
850         if(updateInfo->m_downloadSite.isEmpty()) complete = false;
851         if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
852         if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
853         if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
854         
855         if(!complete)
856         {
857                 m_logFile->append("WARNING: Version info is incomplete!");
858         }
859
860         return complete;
861 }
862
863 void UpdateDialog::linkActivated(const QString &link)
864 {
865         QDesktopServices::openUrl(QUrl(link));
866 }
867
868 void UpdateDialog::applyUpdate(void)
869 {
870         installButton->setEnabled(false);
871         closeButton->setEnabled(false);
872         retryButton->setEnabled(false);
873
874         if(m_updateInfo)
875         {
876                 statusLabel->setText(tr("Update is being downloaded, please be patient..."));
877                 frameAnimation->show();
878                 if(hintLabel->isVisible()) hintLabel->hide();
879                 if(hintIcon->isVisible()) hintIcon->hide();
880                 int oldMax = progressBar->maximum();
881                 int oldMin = progressBar->minimum();
882                 progressBar->setRange(0, 0);
883                 QApplication::processEvents();
884                 
885                 QProcess process;
886                 QStringList args;
887                 QEventLoop loop;
888
889                 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
890                 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
891
892                 args << QString("/Location=%1").arg(m_updateInfo->m_downloadAddress);
893                 args << QString("/Filename=%1").arg(m_updateInfo->m_downloadFilename);
894                 args << QString("/TicketID=%1").arg(m_updateInfo->m_downloadFilecode);
895                 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath())); 
896                 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
897                 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(m_updateInfo->m_buildNo));
898
899                 QApplication::setOverrideCursor(Qt::WaitCursor);
900                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
901                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
902
903                 process.start(m_binaryUpdater, args);
904                 bool updateStarted = process.waitForStarted();
905                 if(updateStarted)
906                 {
907                         m_updaterProcess = process.pid()->dwProcessId;
908                         loop.exec();
909                 }
910                 m_updaterProcess = NULL;
911                 QApplication::restoreOverrideCursor();
912
913                 hintLabel->show();
914                 hintIcon->show();
915                 progressBar->setRange(oldMin, oldMax);
916                 progressBar->setValue(oldMax);
917                 frameAnimation->hide();
918
919                 if(updateStarted && (process.exitCode() == 0))
920                 {
921                         statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
922                         m_updateReadyToInstall = true;
923                         WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
924                         WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
925                         accept();
926                 }
927                 else
928                 {
929                         statusLabel->setText(tr("Update failed. Please try again or download manually!"));
930                         WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
931                         WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
932                         WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), 100, 100);
933                 }
934         }
935
936         installButton->setEnabled(true);
937         closeButton->setEnabled(true);
938 }
939
940 void UpdateDialog::logButtonClicked(void)
941 {
942         LogViewDialog *logView = new LogViewDialog(this);
943         logView->exec(*m_logFile);
944         LAMEXP_DELETE(logView);
945 }
946
947 void UpdateDialog::progressBarValueChanged(int value)
948 {
949         WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), value, progressBar->maximum());
950 }
951
952 void UpdateDialog::testKnownWebSites(void)
953 {
954         int connectionScore = 0;
955
956         // ----- Initialization ----- //
957
958         progressBar->setValue(0);
959         WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
960         WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
961         installButton->setEnabled(false);
962         closeButton->setEnabled(false);
963         retryButton->setEnabled(false);
964         logButton->setEnabled(false);
965         if(infoLabel->isVisible()) infoLabel->hide();
966         if(hintLabel->isVisible()) hintLabel->hide();
967         if(hintIcon->isVisible()) hintIcon->hide();
968         frameAnimation->show();
969
970         QApplication::processEvents();
971         QApplication::setOverrideCursor(Qt::WaitCursor);
972
973         // ----- Test Internet Connection ----- //
974
975         statusLabel->setText("Testing all known hosts, this may take a few minutes...");
976
977         m_logFile->clear();
978         m_logFile->append("Checking internet connection...");
979         
980         QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
981         while(!connectedState.isFinished())
982         {
983                 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
984         }
985
986         if(!connectedState.result())
987         {
988                 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
989                 if(!retryButton->isVisible()) retryButton->show();
990                 if(!logButton->isVisible()) logButton->show();
991                 closeButton->setEnabled(true);
992                 retryButton->setEnabled(true);
993                 logButton->setEnabled(true);
994                 if(frameAnimation->isVisible()) frameAnimation->hide();
995                 statusLabel->setText(tr("It appears that the computer currently is offline!"));
996                 progressBar->setValue(progressBar->maximum());
997                 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
998                 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
999                 hintIcon->show();
1000                 hintLabel->show();
1001                 LAMEXP_DELETE(m_updateInfo);
1002                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1003                 QApplication::restoreOverrideCursor();
1004                 progressBar->setValue(progressBar->maximum());
1005                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
1006                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
1007                 return;
1008         }
1009         
1010         // ----- Test Known Hosts Connectivity ----- //
1011
1012         QStringList hostList;
1013         for(int i = 0; known_hosts[i]; i++)
1014         {
1015                 hostList << QString::fromLatin1(known_hosts[i]);
1016         }
1017
1018         qDebug("[Known Hosts]");
1019
1020         int hostCount = hostList.count();
1021         while(!hostList.isEmpty())
1022         {
1023                 QString currentHost = hostList.takeFirst();
1024                 progressBar->setValue(qRound((static_cast<double>(progressBar->maximum() - 1) / static_cast<double>(hostCount)) * static_cast<double>(connectionScore)) + 1);
1025                 qDebug("Testing: %s", currentHost.toLatin1().constData());
1026                 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
1027                 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
1028                 bool httpOk = false;
1029                 if(getFile(currentHost, outFile, 0, &httpOk))
1030                 {
1031                         connectionScore++;
1032                 }
1033                 else
1034                 {
1035                         if(httpOk)
1036                         {
1037                                 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
1038                                 connectionScore++;
1039                         }
1040                         else
1041                         {
1042                                 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
1043                         }
1044                 }
1045                 QFile::remove(outFile);
1046         }
1047
1048         if(connectionScore < hostCount)
1049         {
1050                 if(!retryButton->isVisible()) retryButton->show();
1051                 if(!logButton->isVisible()) logButton->show();
1052                 closeButton->setEnabled(true);
1053                 retryButton->setEnabled(true);
1054                 logButton->setEnabled(true);
1055                 if(frameAnimation->isVisible()) frameAnimation->hide();
1056                 statusLabel->setText("At least one host could not be reached!");
1057                 progressBar->setValue(progressBar->maximum());
1058                 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
1059                 hintLabel->setText("Please make sure your internet connection is working properly and try again.");
1060                 hintIcon->show();
1061                 hintLabel->show();
1062                 LAMEXP_DELETE(m_updateInfo);
1063                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1064                 QApplication::restoreOverrideCursor();
1065                 progressBar->setValue(progressBar->maximum());
1066                 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
1067                 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
1068                 return;
1069         }
1070
1071         // ----- Done ----- //
1072         
1073         QApplication::restoreOverrideCursor();
1074         progressBar->setValue(progressBar->maximum());
1075
1076         statusLabel->setText("Test completed.");
1077         hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
1078         hintLabel->setText("Congratulations, the test has completed.");
1079         if(frameAnimation->isVisible()) frameAnimation->hide();
1080         hintIcon->show();
1081         hintLabel->show();
1082         WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
1083         MessageBeep(MB_ICONINFORMATION);
1084
1085         closeButton->setEnabled(true);
1086         if(retryButton->isVisible()) retryButton->hide();
1087         if(logButton->isVisible()) logButton->hide();
1088         if(frameAnimation->isVisible()) frameAnimation->hide();
1089 }