-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
385 lines (337 loc) · 13.5 KB
/
Copy pathmainwindow.cpp
File metadata and controls
385 lines (337 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "globalvar.h"
#include "downloaderui.h"
#include <QtSql>
#include <QSqlDatabase>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
// db.setDatabaseName(DIRECTORY);
//creating the UI
APIKEY=GetMyValue("KEY","NULL").toString();
this->setWindowFlags((Qt::WindowFlags) (Qt::Window | Qt::WindowStaysOnTopHint | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint & (~Qt::WindowFullscreenButtonHint)) );
ui->setupUi(this);
//CODE TO CHECK INTERNET CONNECTION if not dont open
checkCon();
if(failedcon==1)delete this;
this->setAttribute(Qt::WA_QuitOnClose,false);
QDir d = QStandardPaths::standardLocations(QStandardPaths::DataLocation)[0];
if(!d.exists()){
QDir().mkpath(d.path());
}
logger = new QFile(d.filePath("download.log"));
if(!logger->exists()){
logger->open(QIODevice::WriteOnly);
logger->close();
}else{
logger->open(QIODevice::ReadOnly);
QString logs = logger->readAll();
ui->plainTextEdit->setPlainText(logs);
logger->close();
}
ivlefetcher = NULL;
needStart = false;
settingsDialog = new SettingsDialog();
connect(ui->settingsBut, SIGNAL(clicked()), settingsDialog, SLOT(show()));
settings = new Settings(d, this);
QVariantMap m;
m["notify"] = settings->notify();
m["maxFileSize"] = settings->maxFileSize();
m["ignoreUploadable"] = settings->ignoreUploadable();
m["notifyAnm"] = settings->notifyAnnouncement();
m["jsonConfig"] = settings->pagesInfoJson();
parser = new ExternalPageParser(settings->pagesInfo());
settingsDialog->setDisplayedSettings(m);
connect(settingsDialog, SIGNAL(gottenToken(QString)), this, SLOT(processToken(QString)));
connect(settingsDialog,SIGNAL(updateDirectory(QString)),settings,SLOT(setDirectory(QString)));
connect(settingsDialog,SIGNAL(updateDirectory(QString)),this,SLOT(updateDirectory(QString)));
connect(settingsDialog,SIGNAL(closedWithSettings(QVariantMap)),this,SLOT(processSettingsDialog(QVariantMap)));
connect(settingsDialog, &SettingsDialog::configSaved, [=](const QVariantMap& data){
settings->setConfig(data);
parser->setConfig(settings->pagesInfo());
});
trayMenu = new QMenu(this);
QAction* main = new QAction("Main",this);
connect(main,SIGNAL(triggered()),this,SLOT(show()));
trayMenu->addAction(main);
QAction* open = new QAction("Open Folder", this);
connect(open, SIGNAL(triggered()), this, SLOT(openFolder()));
trayMenu->addAction(open);
#ifdef Q_OS_MAC
QAction* setting = new QAction(QString::fromUtf8("Preferences…"),this);
#else
QAction* setting = new QAction("Settings",this);
#endif
setting->setMenuRole(QAction::NoRole);
// connect(setting,SIGNAL(triggered()),settingsDialog,SLOT(show()));
connect(setting, &QAction::triggered, [=](){
settingsDialog->setWindowFlags(settingsDialog->windowFlags() | (Qt::WindowStaysOnTopHint));
settingsDialog->show();
});
trayMenu->addAction(setting);
trayMenu->addSeparator();
updateAction = new QAction("Update Now",this);
connect(updateAction,SIGNAL(triggered()),this,SLOT(updateFiles()));
trayMenu->addAction(updateAction);
updateAction->setDisabled(true);
statusAction = new QAction("Please log in",this);
statusAction->setDisabled(true);
trayMenu->addAction(statusAction);
trayMenu->addSeparator();
announcements = new AnnouncementsMenu(this);
trayMenu->addMenu(announcements);
recent = new QMenu("Recently downloaded files",this);
int l = settings->recents().length();
for(int i = 0; i < l; i++){
recents[i] = new recentFileAction(this);
recents[i]->setFile(settings->recents()[i]);
recent->addAction(recents[i]);
}
if(!l){
recent->setDisabled(true);
}
trayMenu->addMenu(recent);
trayMenu->addSeparator();
QAction* quit = new QAction("Quit",this);
quit->setMenuRole(QAction::NoRole);
connect(quit,SIGNAL(triggered()),qApp,SLOT(quit()));
trayMenu->addAction(quit);
normalIcon = QIcon(":/icons/icon.png");
attnIcon = QIcon(":/icons/icon_attn.png");
icon = new QSystemTrayIcon(normalIcon, this);
icon->setContextMenu(trayMenu);
icon->show();
connect(trayMenu, SIGNAL(aboutToShow()), this, SLOT(menuToShow()));
connect(icon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
if(settings->token().isEmpty() || settings->directory().isEmpty()){
settingsDialog->show();
}else{
settingsDialog->setDlText(QString("Download to: %1").arg(settings->directory()));
processToken(settings->token());
}
//========================================ADDED to make the UI for first time login and subsequent logins=================
webviewDialog = new QDialog(this);// an object that is shown in the UI, code below will set the settings of the Dialog box seen
webviewDialog->setLayout(new QBoxLayout(QBoxLayout::LeftToRight));
webviewDialog->setAttribute(Qt::WA_QuitOnClose,false);
webView = new QWebView(webviewDialog);
webviewDialog->layout()->addWidget(webView);
webviewDialog->layout()->setMargin(0);
//SetMyValue("KEY","NULL");
if (GetMyValue("KEY","NULL").toString().length()!=21){//FOR FIRST TIME USERS
ivleLoginPage();
getAPIkey();
QString keys=GetMyValue("KEY","h").toString();
} else {//================================================FOR SUBSESQUENT USERS
QString keys=GetMyValue("KEY","h").toString();
//qDebug()<<keys;
DownloaderUI UI;
UI.setModal(true);
UI.exec();
}
}
//=======================================================================================================================
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::ivleLoginPage()
{
webView->setUrl(QString("https://ivle.nus.edu.sg/LAPI/default.aspx").arg("EaLNhIs72xzNhdl9ai6Tr"));
webviewDialog->show();
}
// Navigates to the page that creates an APIKEY based on each user
void MainWindow::getAPIkey()
{
QUrl url("https://ivle.nus.edu.sg/LAPI/default.aspx");//url to obtain the APIKEY
webView->setUrl(url);
//Signals and slot function that ensures that the webpage is loaded finish before executing the parse function
connect(webView, SIGNAL(loadFinished(bool)), SLOT(parse(bool)));
}
//Parsing function that uses QSettings,QWebView,QWebFrame and QWebElement to extract the APIKEY from parsing HTML code on the webpage that generates the APIKEY
void MainWindow::parse(bool){
QWebFrame *frameInner = webView->page()->mainFrame();
QWebElement doc = frameInner->documentElement();
QWebElement key = doc.findFirst("b");//function to find the first element in the HTML tag <b>
APIKEY = key.toPlainText();
SetMyValue("KEY",APIKEY);
qDebug()<<GetMyValue("KEY","Does not exist");
QString keys=GetMyValue("KEY","h").toString();
//qDebug()<<keys;
}
void MainWindow::checkCon()
{
//CODE TO CHECK INTERNET CONNECTION if not dont open
QNetworkAccessManager nam;
QNetworkRequest req(QUrl("http://www.google.com"));
QNetworkReply *reply = nam.get(req);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if(reply->bytesAvailable())failedcon=0;
//QMessageBox::information(this, "Info", "You are connected to the internet :)");
else{
QMessageBox::critical(this, "Info","You are not connected to the internet! This app cannot be opened without an internet connection, if you want to view your files go to the directory you saved at. Please try again after you have a stable connection!");
failedcon=1;
}
//============ENDS HERE============================================
}
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason){
icon->setIcon(normalIcon);
}
void MainWindow::menuToShow(){
icon->setIcon(normalIcon);
}
void MainWindow::processSettingsDialog(QVariantMap m){
double s = m.value("maxFileSize").toDouble();
bool i = m.value("ignoreUploadable").toBool();
bool n = m.value("notify").toBool();
//s is in mb
double size = s * 1024 * 1024;
settings->setMaxFileSize(size);
ivlefetcher->setMaxFileSize(size);
settings->setIgnoreUploadable(i);
ivlefetcher->setIgnoreUploadable(i);
settings->setNotify(n);
settings->setNotifyAnnouncement(m.value("notifyAnm").toBool());
}
void MainWindow::updateFiles(){
if(ivlefetcher != NULL){
ivlefetcher->start();
updateAction->setDisabled(true);
}
}
void MainWindow::logDownload(const QString &filename){
//qDebug()<<filename;
logger->open(QIODevice::Append);
QString toAdd = QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm") + "\t" + filename + "\n";
logger->write(toAdd.toUtf8());
logger->close();
ui->plainTextEdit->setPlainText(ui->plainTextEdit->toPlainText() + toAdd);
ui->plainTextEdit->scroll(0,ui->plainTextEdit->height());
if(settings->notify()){
icon->setIcon(attnIcon);
}
}
void MainWindow::processToken(const QString& token){
settings->setToken(token);
if(!settings->directory().isEmpty()){
if(ivlefetcher == NULL){
createFetcher();
}else{
ivlefetcher->setToken(token);
}
}else{
settingsDialog->setLabelText("Please set the download directory below.");
}
}
void MainWindow::updateRecent(const QString &filename){
settings->addRecentFile(filename);
recent->setEnabled(true);
const QStringList& _recent = settings->recents();
int l = _recent.length() - 1;
if(recent->actions().length() < _recent.length()){
recents[l] = new recentFileAction(this);
recent->addAction(recents[l]);
}
for(int i = 0; i <= l; i++){
recents[i]->setFile(_recent[i]);
}
}
void MainWindow::createFetcher(){
ivlefetcher = new IVLEFetcher(settings->token(), parser, settings->directory(), settings->maxFileSize(), this);
ivlefetcher->setIgnoreUploadable(settings->ignoreUploadable());
connect(ivlefetcher,SIGNAL(statusUpdate(fetchingState)),this,SLOT(updateStatus(fetchingState)));
connect(ivlefetcher,SIGNAL(tokenUpdated(QString)),this,SLOT(processToken(QString)));
connect(ivlefetcher,SIGNAL(fileDownloaded(QString)),this,SLOT(logDownload(QString)));
connect(ivlefetcher,SIGNAL(fileDownloaded(QString)),this,SLOT(updateRecent(QString)));
connect(ivlefetcher, SIGNAL(gotUnreadAnnouncements(QVariantList)), this, SLOT(processAnnouncements(QVariantList)));
ivlefetcher->start();
}
void MainWindow::processAnnouncements(QVariantList l){
announcements->setAnnouncementItems(l);
QDateTime d;
for(int i = 0; i < l.size(); i++){
QVariantMap m = l[i].toMap();
if(d < m["latest_date"].toDateTime()){
d = m["latest_date"].toDateTime();
}
}
if(d > settings->lastAnnouncementTime()){
settings->setLastAnnouncementTime(d);
if(settings->notifyAnnouncement()){
icon->setIcon(attnIcon);
}
}
}
void MainWindow::updateStatus(fetchingState state){
switch(state){
case invalidToken:
settingsDialog->show();
break;
case gettingUserInfo:
settingsDialog->setLabelText("Fetching your infomation....");
statusAction->setText("Verifying user infomation...");
break;
case gottenUserInfo:
settingsDialog->setLabelText(QString("Currently logged in as %1").arg(ivlefetcher->username()));
needStart = false;
break;
case gettingWebbinInfo:
statusAction->setText("Retrieving the list of files...");
break;
case downloading:
statusAction->setText("Getting ready to download...");
break;
case remainingChange:
statusAction->setText(QString("%1 file(s) remaining...").arg(ivlefetcher->remainingFiles()));
break;
case complete:
statusAction->setText("All files up to date");
updateAction->setEnabled(true);
break;
case networkError:
statusAction->setText("Failed to connect the network");
updateAction->setEnabled(true);
needStart = true;
break;
}
}
void MainWindow::updateDirectory(const QString &dir){
settingsDialog->setDlText(QString("Download to: %1").arg(dir));
if(!settings->token().isEmpty()){
if(ivlefetcher == NULL){
createFetcher();
}else{
ivlefetcher->setDirectory(dir);
updateAction->setDisabled(true);
}
}
}
void MainWindow::on_pushButton_clicked()
{
ui->plainTextEdit->setPlainText("");
logger->remove();
logger->open(QIODevice::WriteOnly);
logger->close();
}
void MainWindow::openFolder(){
QDesktopServices::openUrl(QString("file:///") + settings->directory());
}
//A collection of functions that use QSettings to store settings variables. This stores settings in the registry of the computer and hence permanent even after the app is closed
QSettings* MainWindow:: InitRegSettings()
{
QSettings* regSett;
regSett = new QSettings("Organization-name","Project-name");
return regSett;
}
void MainWindow::SetMyValue(QString key, QVariant value)
{
InitRegSettings()->setValue(key,value); //Store value of key defined by user
}
QVariant MainWindow:: GetMyValue(QString key, QVariant defaultValue)
{
return InitRegSettings()->value(key,defaultValue);//Get value of a key-value pair
}