OSDN Git Service

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