/
widget.cpp
1603 lines (1361 loc) · 45.6 KB
/
widget.cpp
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "widget.h"
#include <QtNetwork>
#include <QNetworkAddressEntry>
#define DEBUG
#if defined(WIN32) && defined(_DEBUG)
#define new DEBUG_NEW
#endif
/*
ALPHA PHASE BEGINS: CODE ALMSOT MEETS ORIGINAL REQUIREMENTS OR ALL ARE BEING IMPLEMENTED
Changelog 0.9 - 1.0
- Moved from QTableView to QTreeWidget. Re-Wrote the code controlling all the lists to be compatible.
- Gui Changes
- Did experimentation with 64 bit systems. Found that loopback is not always interface 0. Need to implement search.
- Added locking to the buttons. Buttons will eventually be removed.
- Overall Code Streamlining.
- Changed from a QWidget to a QMainWindow class (a subclass of QWidget) Enabling menu bar. Added about Qt. Need to fix Program About button.
Changelog 1.0 - 1.1
- Added socket error processing
- Fixed the infinite login bug
- Fixed 64 bit processing
- Code optimization
- Began Adding File Transfer Protocol Server to the SERVER mode. No crashes yet! Includes WSOCK32.lib in the makefile, so probably needs
WSOCK32.dll now.
Changelog 1.1 - 1.2
-Completely Added the FTP Server. Acts like any other. Default login is "lanclient" "tseug".
-Implemented a "search(file, dir)" function to assist in applying cracks. Will detect changes to Program Files and auto-search
for the file to replace.
-Began Implementing FTP Client.
Changelog 1.2 - 1.3
- Finished FTP Client: it auto reads all directories in Sync and downloads them to the application directory.
Will try to find a way to change the download directory. Added the client progress bar.
-Added a status bar to the server to indicate client download state
Changelog 1.3 - 1.3.1 : Jan 26, 2010
- Discovered a huge bug in the code that prevented FTP Accross a network, instead of through loopback. Fixed it (set the client to Active
instead of Passive mode, and forced Binary transfers)
- Discovered a huge bug in the broadcasting code of the client. Found a Qt Example called "Network Chat Example Qt4.6" that illustrates a fix.
- No changes to the actuall interface so no change to the Major Build Number
Changelog 1.3.1 - 1.3.2 : Jan 27, 2010
-Fixed the bug with UDP Broadcast, it now transmits on all interfaces that support broadcasting(which is usually the only one connected)
Changelog 1.3.2 - 1.4 : Jan 28, 2010
-Fixed client disconnect/reconnect issues.
-Added SystemTrayIcon (noticed that showMessage() doesnt work, so no popup windows yet. Maybe my copy of XP?)
Changelog 1.4 - 1.5 : Jan 29, 2010
-Added support in the backend for debugging (although it relies on showMessage(). Maybe move over to logfile?)
-No, that was just my computer. Mesage Popups are now enabled and working by default.
-New Icons (Thanks Adrian)
-Much improved debug mode, now writes to logfile and sends important messages to the screen.
-Icons show error status, clicking the icon clears the error, and resets the icon.
-Fully implemented settings, though they shouldn't really be changed.
-Built the installer and added the icons to the resource system
-Beta Phase begins
BETA PHASE BEINGS: CODE MEETS ORIGINAL REQUIREMENTS, AND NEW FEATURES ARE BEING ADDED
Changelog 1.5 : June 25, 2010
-Added the background capability to do remote download start/management on the client.
Changelog 1.5 - 1.5.2 : July 27, 2010
-Began work on the Server File Download dialog. So far, have got procedural button generation and directory genreation.
-Moved the server workspace inside a QTabWidget to allow for more server functionality
Changelog 1.5.2 - 1.5.5 : July 28, 2010
-Server File Download page modified with more functionality
-Bugs found:
-Directory-inside-Directory doesn't get named
-Wierd non-existant files with blank names
-Directory-inside-directory doesn't affect status of directory's above it
Changelog 1.5.5 - 1.5.8 : August 4, 2010
-Bugs from 1.5.5 are all fixed
-Added all the background needed to send files. Unfortunately, it doesn't work.
-Check button, and try and get DEBUG mode working again. Re-initialize the debug setting to view packtets arriving
*/
/*
NOTES:
-Implement Bytes In/ Out by default
*/
typedef DWORD (_stdcall *TGetIfTable) (
MIB_IFTABLE *pIfTable, // buffer for interface table
ULONG *pdwSize, // size of buffer
BOOL bOrder // sort the table by index?
);
typedef DWORD (_stdcall *TGetNumberOfInterfaces) (
PDWORD pdwNumIf // pointer to number of interfaces
);
TGetIfTable pGetIfTable;
TGetNumberOfInterfaces pGetNumberOfInterfaces;
ULONG uRetCode;
MIB_IFTABLE * m_pTable;
DWORD m_dwAdapters;
unsigned long long bytesTotal; //64 bits can suck it
int id;
QString ret;
QStringList files;
QStringList paths;
QStringList remPaths;
QString curDir;
QString workingDir = "/";
bool inEventLoop = false;
bool amIRite = false;
QString curRoot = "";
QString currentDir;
qint64 total = 100;
qint64 current = 0;
QList<QHostAddress> broadcastAddresses;
QList<QHostAddress> ipAddresses;
QList<QTreeWidgetItem*> fileList;
QList<QCheckBox*> boxList;
QString releaseVer = "1.5.8";
QString releaseType = "Beta";
//setup main varibles, settings
int udpBroadcastRate = 1000;
int tcpCheckRate = 5000;
int standardUdpPort = 45454;
int standardTcpPort = 1337;
int networkUpdateRate = 1000;
bool debugMode = true;
Widget::Widget()
{
// This class is the host of the whole application. This is BAD. Needs to be rectified. Should split this up into either: More classes OR More Files
firstComp = NULL; //Setup the linked list
//Spawn a QMainWindow, and set its attributes
mainWindow = new QMainWindow();
mainWindow->resize(400, 400);
mainWindow->setWindowTitle("Lan Party Manager " + releaseType + " " + releaseVer);
setup = new QSettings(QSettings::IniFormat, QSettings::SystemScope, "Alldritt Coding", "LanParty Manager", this);
QStringList keys = setup->allKeys();
if(keys.length() != 8)
{
setup->clear();
setup->setValue("udpBroadcast", 1000);
setup->setValue("tcpBroadcast", 5000);
setup->setValue("udpPort", 45454);
setup->setValue("tcpPort", 1337);
setup->setValue("debug", false);
setup->setValue("releaseType", releaseType);
setup->setValue("releaseVer", releaseVer);
setup->setValue("networkUpdateRate", 1000);
}
else
{
udpBroadcastRate = setup->value("udpBroadcast", 1000).toInt();
tcpCheckRate = setup->value("tcpBroadcast", 5000).toInt();
standardUdpPort = setup->value("udpPort", 45454).toInt();
standardTcpPort = setup->value("tcpPort", 1337).toInt();
debugMode = setup->value("debug", false).toBool();
//releaseType = setup->value("releaseType", "").toString();
//releaseVer = setup->value("releaseVer", "").toString();
networkUpdateRate = setup->value("networkUpdateRate", 1000).toInt();
}
settings = new QWidget(mainWindow, Qt::Dialog);
settings->resize(300, 300);
settings->setWindowTitle("Settings");
settings->hide();
QLabel * la = new QLabel(settings);
la->move(15, 15);
la->setText("UDP Broadcast Delay");
QLabel * lb = new QLabel(settings);
lb->move(15, 45);
lb->setText("TCP Broadcast Delay");
QLabel * lc = new QLabel(settings);
lc->move(15, 75);
lc->setText("Default UDP Port (Advanced)");
QLabel * ld = new QLabel(settings);
ld->move(15, 105);
ld->setText("Default TCP Port (Advanced)");
QLabel * le = new QLabel(settings);
le->move(15, 165);
le->setText("Debug Mode");
QLabel * lf = new QLabel(settings);
lf->move(15, 135);
lf->setText("Total Bytes Refresh Rate");
uPort = new QLineEdit(settings);
uPort->setGeometry(200, 75, 50, 20);
uPort->setText(QString().number(standardUdpPort));
tPort = new QLineEdit(settings);
tPort->setGeometry(200, 105, 50, 20);
tPort->setText(QString().number(standardTcpPort));
uDelay = new QLineEdit(settings);
uDelay->setGeometry(200, 15, 50, 20);
uDelay->setText(QString().number(udpBroadcastRate));
tDelay = new QLineEdit(settings);
tDelay->setGeometry(200, 45, 50, 20);
tDelay->setText(QString().number(tcpCheckRate));
nDelay = new QLineEdit(settings);
nDelay->setGeometry(200, 135, 50, 20);
nDelay->setText(QString().number(networkUpdateRate));
debugOn = new QCheckBox(settings);
debugOn->move(200, 165);
debugOn->setChecked(debugMode);
QPushButton * apply = new QPushButton(settings);
apply->setGeometry(200, 200, 60, 30);
apply->setText("Apply");
QObject::connect(apply, SIGNAL(clicked()), this, SLOT(apply()));
QWidget * passWindow = new QWidget(mainWindow, Qt::Tool);
passWindow->resize(200, 80);
passWindow->hide();
QLabel * passLabel = new QLabel(passWindow);
passLabel->move(50, 10);
passLabel->setText("Enter Password");
passBox = new QLineEdit(passWindow);
passBox->setGeometry(40, 25, 130, 20);
QPushButton * enter = new QPushButton(passWindow);
enter->setGeometry(40, 50, 50, 25);
enter->setText("Enter");
QObject::connect(enter, SIGNAL(clicked()), this, SLOT(passEnter()));
QObject::connect(enter, SIGNAL(clicked()), passWindow, SLOT(hide()));
QObject::connect(passBox, SIGNAL(returnPressed()), this, SLOT(passEnter()));
QObject::connect(passBox, SIGNAL(returnPressed()), passWindow, SLOT(hide()));
icon = new QIcon(":/images/icon.png");
sysIcon = new QSystemTrayIcon(*icon, this);
sysIcon->show();
sysMenu = new QMenu(mainWindow);
QAction * exitAction = sysMenu->addAction("Exit");
sysIcon->setContextMenu(sysMenu);
connect(exitAction, SIGNAL(triggered(bool)), qApp, SLOT(quit()));
connect(exitAction, SIGNAL(triggered(bool)), this, SLOT(close()));
bool success = connect(sysIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconClicked(QSystemTrayIcon::ActivationReason)));
if(success != true)
{
sysIcon->showMessage("System Tray Error", "Window Respawn Connection Failed", QSystemTrayIcon::Information, 10000 );
}
QMenu* file = mainWindow->menuBar()->addMenu(tr("&File"));
QMenu* help = mainWindow->menuBar()->addMenu(tr("&Help"));
QAction* exitAct = new QAction(tr("&Exit"), this);
exitAct->setStatusTip(tr("Quit"));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
QAction* settingAct = new QAction(tr("&Settings"), this);
settingAct->setStatusTip(tr("Access the Settings page"));
connect(settingAct, SIGNAL(triggered()), this, SLOT(settingsWindow()));
QAction* aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
QAction* aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Show the About box"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
help->addAction(aboutQtAct);
help->addAction(aboutAct);
file->addAction(settingAct);
file->addAction(exitAct);
mainWindow->show();
server = new QPushButton(mainWindow);
client = new QPushButton(mainWindow);
log = new QFile("log.txt");
currentTime = new QDateTime(); //create the log timestamp
*currentTime = QDateTime::currentDateTime(); //get system time
if(!log->open(QIODevice::ReadWrite|QIODevice::Append))
{
QMessageBox::information(0, "Error", "Can't open logfile. Reason: " + log->errorString());
}
if(debugMode)
{
writeLog("LanMan " + releaseType + " " + releaseVer + " Logfile Start");
writeLog("Time Format is: DD/MM/YYYY - HOUR:MIN:SEC AM/PM");
}
server->setGeometry(10, 30, 100, 30);
client->setGeometry(290, 30, 100, 30);
server->setText("SERVER MODE");
client->setText("CLIENT MODE");
client->show();
server->show();
connect(client, SIGNAL(released()), this, SLOT(startClient()));
connect(server, SIGNAL(released()), passWindow, SLOT(show()));
mainLabel = new QLabel("", mainWindow);
mainLabel->move(165, 40);
mainLabel->show();
udpSocket = new QUdpSocket(this);
}
Widget::~Widget()
{
}
//I don't even... what? Why is this here... I don't even remember
Widget::Mode Widget::getMode()
{
return Widget::Client;
}
void Widget::writeLog(QString input)
{
QString date = currentTime->toString("dd/MM/yyyy - h:m:s ap");
log->write(QByteArray(QString( date + " :: " + input + "\r\n").toAscii()));
}
void Widget::about()
{
QMessageBox::about( mainWindow, "About LanMan " + releaseType + " " + releaseVer, "LanMan is a Lan Party Manager currently capable of auto file sync, hostname identification, automatic network testing and other things. This is build " + releaseType + " " + releaseVer);
}
void Widget::iconClicked(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
mainWindow->show();
normal();
}
}
void Widget::close()
{
setup->setValue("udpBroadcast", udpBroadcastRate);
setup->setValue("tcpBroadcast", tcpCheckRate);
setup->setValue("udpPort", standardUdpPort);
setup->setValue("tcpPort", standardTcpPort);
setup->setValue("debug", debugMode);
setup->setValue("releaseType", releaseType);
setup->setValue("releaseVer", releaseVer);
setup->setValue("networkUpdateRate", networkUpdateRate);
setup->sync();
log->close();
sysIcon->hide();
sysIcon->~QSystemTrayIcon();
}
void Widget::settingsWindow()
{
uPort->setText(QString().number(standardUdpPort));
tPort->setText(QString().number(standardTcpPort));
uDelay->setText(QString().number(udpBroadcastRate));
tDelay->setText(QString().number(tcpCheckRate));
debugOn->setChecked(debugMode);
nDelay->setText(QString().number(networkUpdateRate));
settings->show();
}
void Widget::apply()
{
standardUdpPort = uPort->text().toInt();
standardTcpPort = tPort->text().toInt();
udpBroadcastRate = uDelay->text().toInt();
tcpCheckRate = tDelay->text().toInt();
debugMode = debugOn->isChecked();
networkUpdateRate = nDelay->text().toInt();
settings->show();
}
void Widget::error()
{
sysIcon->setIcon(QIcon(":/images/err.png"));
}
void Widget::normal()
{
sysIcon->setIcon(QIcon(":/images/icon.png"));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////SERVER FUNCTIONS//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Widget::passEnter()
{
checkPassword(passBox->text().toAscii());
}
//Hah. This "password" actually doesn't give any real security. The idea was that me (the programmer) would distribute a hash to the host which would allow only one person to become a server.
//In reality, this never got implemented correctly, so all it does is prevent the client becomming a server without a correct hash file / password pair
void Widget::checkPassword(QByteArray pass)
{
#ifndef DEBUG
QCryptographicHash * hash = new QCryptographicHash(QCryptographicHash::Md5);
QFile * password = new QFile("password.hash", this);
if(password->open(QIODevice::ReadOnly))
{
QByteArray hashSt = password->readAll();
hash->addData(pass);
QByteArray hashTs = hash->result().toHex();
QString test = QString(hashTs);
if(hashSt == hashTs)
{
#endif
startServer();
#ifndef DEBUG
}
else
{
QMessageBox::information(mainWindow, "Password", "That password does not hash to the one stored in password.hash");
}
}
else
{
QMessageBox::information(mainWindow, "Password", "password.hash Not found");
}
#endif
}
void Widget::startServer()
{
#ifdef WIN32
//Initialize WINSOCK because CFTPServer needs it on Windows
WSADATA WSAData;
if( WSAStartup( MAKEWORD(1, 0), &WSAData) != 0 ) {
//printf("-WSAStartup failure: WSAGetLastError=%d\r\n", WSAGetLastError() );
QMessageBox::information(0, "Error", "Winsock error: " + WSAGetLastError());
//return 0;
}
#endif
QString dir = qApp->applicationDirPath();
if(QDir().exists("/Sync") == false)
{
QDir().mkdir(dir + "/Sync");
}
//Begin FTP Server Initialization
ftpServer = new CFtpServer();
ftpServer->SetDataPortRange(100, 900);
CFtpServer::CUserEntry *FtpUser = ftpServer->AddUser("lanclient", "tseug", QString(dir + "/Sync").toAscii());
ftpServer->AddUser("anonymous", NULL, "C:\\dir");
if(FtpUser)
{
FtpUser->SetMaxNumberOfClient( 0 );
FtpUser->SetPrivileges( CFtpServer::READFILE | CFtpServer::WRITEFILE |
CFtpServer::LIST | CFtpServer::DELETEFILE | CFtpServer::CREATEDIR |
CFtpServer::DELETEDIR );
}
else
{
writeLog("FTP Server Could Not Create User");
sysIcon->showMessage("FTP Error", "No user could be created on the FTP Server. Login Not Possible", QSystemTrayIcon::Critical, 10000 );
error();
}
if(ftpServer->StartListening(INADDR_ANY, 21))
{
if(ftpServer->StartAccepting() == false)
{
writeLog("FTP Server Could Not Begin Accepting on Port 21. Code corruption or incompatible dll");
sysIcon->showMessage("FTP Error", "FTP Server Couldn't start accepting connections.", QSystemTrayIcon::Critical, 10000 );
error();
}
}
else
{
writeLog("FTP Server Could Not Start Listening On Port 21. Check WINSOCK. This application does not support concurrent instances.");
sysIcon->showMessage("FTP Error", "FTP Server Couldn't Listen on port 21. It may be in use already.", QSystemTrayIcon::Critical, 10000 );
error();
}
/*
End FTP Server Initialization
All Files in the applications working directory are now availible through FTP with user "lanclient" with pass "tseug"
*/
client->setEnabled(false);
udpSocket->bind(QHostAddress::Any, standardUdpPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(signalReceived()));
//resize the mainWindow because we need a bigger interface for server mode
mainWindow->resize(600, 500);
//create the tab-widget that we parent the sub-windows too
computerManager = new QTabWidget(mainWindow);
computerManager->setGeometry(5, 70, 590, 430);
primaryStatus = new QWidget(computerManager);
ftpWindow = new QWidget(computerManager);
serverDownload = new QPushButton(ftpWindow);
serverDownload->setGeometry(20, 355, 545, 45);
QObject::connect(serverDownload, SIGNAL(clicked()), this, SLOT(serverDownloadStart()));
computersConnected = 0;
ftpFiles = new QTreeWidget(ftpWindow);
ftpFiles->setGeometry(0, 0, 580, 350);
fileModel = new QTreeWidgetItem(0);
computerNames.append("Files");
ftpFiles->setHeaderLabels(computerNames);
computerManager->addTab(primaryStatus, "Network Status");
computerManager->addTab(ftpWindow, "File Control");
mapper = new QSignalMapper(this);
computerTable = new QTreeWidget(primaryStatus);
computerTable->setGeometry(0, 0, 580, 400);
QTreeWidgetItem * compModel = new QTreeWidgetItem(0);
compModel->setText(0, "Name");
compModel->setText(1,"Bytes Total");
compModel->setText(2, "Active");
computerTable->setHeaderItem(compModel);
computerTable->setColumnCount(3);
computerTable->setColumnWidth(0, 150);
computerTable->setColumnWidth(1, 120);
computerTable->setColumnWidth(2, 305);
computerTable->show();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
fileWatcher = new QFileSystemWatcher(this);
fileWatcher->addPath(dir + "/Sync");
connect(fileWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(sendUpdate()));
timer->start(tcpCheckRate);
computerManager->show();
updateFileTable();
}
void Widget::generateBoxLayout(QTreeWidgetItem * item)
{
qDebug("Generating...");
for(int columns = 1; columns < ftpFiles->columnCount(); columns++)
{
for(int i = 0; i < item->childCount(); i++)
{
item->child(i)->setCheckState(columns, Qt::Unchecked);
if(item->child(i)->childCount() != 0)
generateBoxLayout(item->child(i));
}
}
}
void Widget::boxUpdated(QTreeWidgetItem* item, int column)
{
int state = 2;
qDebug("Box Clicked");
for(int columns = 1; columns < ftpFiles->columnCount(); columns++)
{
int checkedCount = 0;
int ucheckedCount = 0;
if(item->childCount() == 0 && item->parent() != NULL)
{
for(int i = 0; i < item->parent()->childCount(); i++)
{
int val = item->parent()->child(i)->checkState(columns);
switch(val)
{
case 0:
ucheckedCount++;
break;
case 1:
ucheckedCount++;
break;
case 2:
checkedCount++;
break;
}
}
if(checkedCount == item->parent()->childCount())
{
item->parent()->setCheckState(columns, Qt::Checked);
}
else if(ucheckedCount == item->parent()->childCount())
{
item->parent()->setCheckState(columns, Qt::Unchecked);
}
else
{
item->parent()->setCheckState(columns, Qt::PartiallyChecked);
}
}
else
{
for(int i = 0; i < item->childCount(); i++)
{
item->child(i)->setCheckState(columns, item->checkState(columns));
}
}
}
}
void Widget::updateFileTable()
{
totalDownloads = 0;
QString dir = qApp->applicationDirPath();
QTreeWidgetItem * root = new QTreeWidgetItem(0);
QTreeWidgetItem * tempItem = root;
QTreeWidgetItem * tmp;
QDir sncdr(dir + "/Sync");
QFileInfoList syncDir = sncdr.entryInfoList(QDir::NoDotAndDotDot|QDir::AllEntries);
while(!syncDir.empty())
{
if(syncDir.at(0).isDir())
{
tmp = scanDirectory(syncDir.at(0).filePath());
tmp->setText(0, syncDir.at(0).fileName());
ftpFiles->addTopLevelItem(tmp);
totalDownloads++;
}
else
{
tmp = new QTreeWidgetItem(0);
tmp->setText(0, syncDir.at(0).fileName());
ftpFiles->addTopLevelItem(tmp);
totalDownloads++;
}
syncDir.removeAt(0);
}
}
QTreeWidgetItem * Widget::scanDirectory(QString path)
{
QTreeWidgetItem * root;
QDir myDir(path);
QTreeWidgetItem * tmp;
root = new QTreeWidgetItem(0);
root->setText(0, myDir.dirName());
QString dir = qApp->applicationDirPath();
QDirIterator * scanDir= new QDirIterator(path, QDir::AllEntries|QDir::NoDotAndDotDot);
QString nxt;
while(scanDir->hasNext())
{
nxt = scanDir->next();
qDebug(scanDir->filePath().toAscii());
if(scanDir->fileInfo().isDir())
{
root->addChild(scanDirectory(scanDir->filePath()));
totalDownloads++;
}
else
{
tmp = new QTreeWidgetItem(0);
tmp->setText(0, scanDir->fileName());
root->addChild(tmp);
totalDownloads++;
}
}
/*if(!nxt.isNull())
{
qDebug(scanDir->filePath().toAscii());
if(scanDir->fileInfo().isDir())
{
root->addChild(scanDirectory(scanDir->filePath()));
}
else
{
tmp = new QTreeWidgetItem(0);
tmp->setText(0, scanDir->fileName());
root->addChild(tmp);
}
}*/
return root;
}
void Widget::serverDownloadStart()
{
QTreeWidgetItem * item = ftpFiles->invisibleRootItem();
QTreeWidgetItem * header = ftpFiles->headerItem();
QStringList lst;
Computer * comp;
for(int i = 1; i < ftpFiles->columnCount(); i++)
{
lst = rebuildPath(item, "", i);
comp = findByName(header->text(i));
foreach(QString str, lst)
{
comp->getSocket()->write(QByteArray("ADFL::" + str.toAscii()));
}
comp->getSocket()->write(QByteArray("DNLD::"));
}
}
QStringList Widget::rebuildPath(QTreeWidgetItem * start, QString path, int column)
{
QStringList fullPaths;
path.append(start->text(0) + "/");
for(int i = 0; i < start->childCount(); i++)
{
if(start->child(i)->childCount() == 0) //A FILE
{
if(start->child(i)->checkState(column) == Qt::Checked)
fullPaths.append(path + start->child(i)->text(0));
}
else
fullPaths.append(rebuildPath(start->child(i), path, column));
}
return fullPaths;
}
Computer * Widget::findByName(QString name)
{
Computer * comp = firstComp;
while(comp != NULL)
{
if(comp->getName() == name)
break;
else
comp = comp->getNext();
}
return comp;
}
void Widget::sendUpdate()
{
Computer * comp = firstComp;
while(comp != NULL)
{
comp->getSocket()->write(QByteArray("UPDT"));
comp = comp->getNext();
}
while(syncDir->hasNext())
{
friendlyDownloads.append(syncDir->fileName());
syncDir->next();
}
syncDir->path();
}
void Widget::signalReceived()
{
QString edit;
QHostAddress *sender = new QHostAddress();
QHostAddress *check = new QHostAddress();
quint16 *port = new quint16();
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(),datagram.size(),sender,port);
if(check != sender)
{
establishTcp(*sender, standardTcpPort);
if(debugMode)
{
writeLog("User Found at: " + sender->toString());
}
}
check = sender;
}
}
void Widget::establishTcp(QHostAddress host, qint16 port)
{
Computer * comp;
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(socketClosed()));
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(tcpSocket, SIGNAL(connected()), this, SLOT(sockConn()));
comp = newComp();
comp->setSocket(tcpSocket);
comp->setId(id);
comp->setHost(host);
tcpSocket->connectToHost(host, port);
id++;
}
Computer * Widget::newComp()
{
Computer * comp = new Computer(primaryStatus);
Computer * nextComp;
if(firstComp == NULL)
{
firstComp = comp;
}
else
{
nextComp = firstComp;
while(nextComp->getNext() != NULL)
{
nextComp = nextComp->getNext();
}
nextComp->setNext(comp);
}
return comp;
}
void Widget::dataReceived()
{
if(debugMode)
{
writeLog("Data Received");
}
Computer * comp = firstComp;
Computer * comp2 = firstComp;
QObject * sender = QObject::sender();
if((QObject*)comp->getSocket() == sender)
{
computerRead(comp);
}
else
{
while(comp2 != NULL)
{
comp->getSocket();
if((QObject*)comp->getSocket() == sender)
{
computerRead(comp);
}
comp2 = comp->getNext();
comp = comp->getNext();
}
}
}
void Widget::computerRead(Computer * comp)
{
if(debugMode)
{
writeLog("Reading Data");
}
QByteArray datab = comp->getSocket()->read(comp->getSocket()->bytesAvailable());
QString data = QString(datab);
writeLog(data);
QString datac = data;
QString datad = data;
datac.truncate(6);
QStringList commands = datad.split(QRegExp("....::", Qt::CaseInsensitive), QString::SkipEmptyParts);
for(int i = 0; i <= commands.length(); i++)
{
if(datac == "INIT::")
{
comp->getSocket()->write(QByteArray("REDY"));
comp->getSocket()->write(QByteArray("RPRT"));
}
else if(datac == "BAND::")
{
comp->setTotal(commands.at(i).toULongLong());
}
else if(datac == "BDIN::")
{
comp->setIn(commands.at(i).toULongLong());
}
else if(datac == "BOUT::")
{
comp->setOut(commands.at(i).toULongLong());
}
else if(datac == "HOST::")
{
comp->setName(commands.at(i));
if(computerNames.indexOf(comp->getName()) == -1)
{
computerNames.append(comp->getName());
ftpFiles->setHeaderLabels(computerNames);
ftpFiles->show();
generateBoxLayout(ftpFiles->invisibleRootItem());
QObject::connect(ftpFiles, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(boxUpdated(QTreeWidgetItem*, int)));
}
}
else if(datac == "PING::")
{
comp->getSocket()->write(QByteArray("RPRT"));
}
else if(datac == "ERRR::")
{
}
else if(datac == "BTOT::")
{
comp->getBar()->setMaximum(commands.at(i).toLongLong());
}
else if(datac == "BCUR::")
{
comp->getBar()->setValue(commands.at(i).toLongLong());
}
if(commands.length() > 1 && i != commands.length())
{
datac = data;
datac.remove(0,6 + commands.at(i).length());
data = datac;
datac.truncate(6);
}
}
updateTable(comp);
}
void Widget::updateTable(Computer * comp)
{
if(debugMode)
{
writeLog("Refreshing Table");
}
comp->getItem();
}
void Widget::socketClosed()
{
QTreeWidgetItem * item;
int row = 0;
Computer * comp = firstComp;
Computer * prevComp = firstComp;
QObject * sender = QObject::sender();
computersConnected--;
if((QObject*)comp->getSocket() == sender)
{
row = comp->getId();
item = comp->getItem();
computerNames.removeAt(computerNames.indexOf(comp->getName()));
ftpFiles->setHeaderLabels(computerNames);
ftpFiles->setColumnCount(computersConnected + 1);
firstComp = comp->getNext();
delete comp;
}
else
{
while(comp != NULL)