OSDN Git Service

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