Repository navigation
Expand file tree
/
Copy pathnetworkclient.cpp
More file actions
1152 lines (897 loc) · 36.7 KB
/
Copy pathnetworkclient.cpp
File metadata and controls
1152 lines (897 loc) · 36.7 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
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
/*
* Copyright 2010 Kyle M Hall <kyle.m.hall@gmail.com>
*
* This file is part of Libki.
*
* Libki is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Libki is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Libki. If not, see <http://www.gnu.org/licenses/>.
*/
#include "networkclient.h"
#include "utils.h"
#include "printsubmissionserver.h"
#include "printprotocol.h"
#include <QDir>
#include <QHttpMultiPart>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QList>
#include <QSslError>
#include <QUdpSocket>
#define VERSION "2.4.0"
NetworkClient::NetworkClient(QApplication *app) : QObject() {
qDebug("ENTER NetworkClient::NetworkClient");
this->app = app;
qDebug() << "SSL version use for build: "
<< QSslSocket::sslLibraryBuildVersionString();
qDebug() << "SSL version use for run-time: "
<< QSslSocket::sslLibraryVersionNumber();
fileCounter = 0;
QSettings settings;
settings.setIniCodec("UTF-8");
nodeName = getClientName();
nodeLocation = settings.value("node/location").toString();
qDebug() << "LOCATION: " << nodeLocation;
nodeType = settings.value("node/type").toString();
qDebug() << "TYPE: " << nodeType;
nodeAgeLimit = settings.value("node/age_limit").toString();
qDebug() << "AGE LIMIT: " << nodeAgeLimit;
QString action = settings.value("node/logoutAction").toString();
if (action == "logout") {
actionOnLogout = LogoutAction::Logout;
} else if (action == "reboot") {
actionOnLogout = LogoutAction::Reboot;
} else {
actionOnLogout = LogoutAction::NoAction;
}
clientStatus = "online";
qDebug() << "HOST: " << settings.value("server/host").toString();
serviceURL.setHost(settings.value("server/host").toString());
serviceURL.setPort(settings.value("server/port").toInt());
serviceURL.setScheme(settings.value("server/scheme").toString());
serviceURL.setPath("/api/client/v1_0");
customHeaderName = settings.value("server/customHeaderName").toString();
customHeaderValue = settings.value("server/customHeaderValue").toString();
nodeIPAddress = getIPv4Address();
nodeMACAddress = getMACAddress();
nodeHostname = getHostname();
urlQuery.addQueryItem("node", nodeName);
urlQuery.addQueryItem("location", nodeLocation);
urlQuery.addQueryItem("type", nodeType);
urlQuery.addQueryItem("ipaddress", nodeIPAddress);
urlQuery.addQueryItem("macaddress", nodeMACAddress);
urlQuery.addQueryItem("hostname", nodeHostname);
registerNode();
registerNodeTimer = new QTimer(this);
connect(registerNodeTimer, SIGNAL(timeout()), this, SLOT(registerNode()));
registerNodeTimer->start(1000 * 10);
checkForInternetConnectivity();
checkForInternetConnectivityTimer = new QTimer(this);
connect(checkForInternetConnectivityTimer, SIGNAL(timeout()), this, SLOT(checkForInternetConnectivity()));
checkForInternetConnectivityTimer->start(1000 * 10);
uploadPrintJobsTimer = new QTimer(this);
connect(uploadPrintJobsTimer, SIGNAL(timeout()), this,
SLOT(uploadPrintJobs()));
updateUserDataTimer = new QTimer(this);
connect(updateUserDataTimer, SIGNAL(timeout()), this,
SLOT(getUserDataUpdate()));
printServer = new PrintSubmissionServer(this);
if (printServer->start()) {
qDebug() << "IPC server name:"
<< LIBKI_PRINT_SERVER_NAME;
} else {
qWarning() << "Print submission server could not be started.";
}
connect(printServer,
SIGNAL(submitPrintRequested(SubmitPrintRequest)),
this,
SLOT(handlePrintRequest(SubmitPrintRequest)));
connect(printServer,
SIGNAL(printInfoRequested(PrintInfoRequest,QLocalSocket*)),
this,
SLOT(handlePrintInfoRequest(PrintInfoRequest,QLocalSocket*)));
qDebug("LEAVE NetworkClient::NetworkClient");
}
void NetworkClient::attemptLogin(QString aUsername, QString aPassword, bool createGuest) {
qDebug() << "ENTER NetworkClient::attemptLogin(" << aUsername << "," << aPassword << "," << createGuest << ")";
username = aUsername;
password = aPassword;
QUrl url = QUrl(serviceURL);
QUrlQuery query = QUrlQuery(urlQuery);
query.addQueryItem("version", VERSION);
query.addQueryItem("action", "login");
query.addQueryItem("username", username);
query.addQueryItem("password", password);
query.addQueryItem("createGuest", createGuest ? "1" : "0");
url.setQuery(query);
qDebug() << "LOGIN URL: " << url.toString();
qDebug() << "NetworkClient::attemptLogin";
QNetworkAccessManager *nam;
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(processAttemptLoginReply(QNetworkReply *)));
QObject::connect(
nam, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
/*QNetworkReply* reply = */ nam->get(buildRequest(url));
qDebug("LEAVE NetworkClient::attemptLogin");
}
void NetworkClient::processAttemptLoginReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::processAttemptLogoutReply");
handleNetworkReplyErrors(reply);
QByteArray result;
result = reply->readAll();
QScriptValue sc;
QScriptEngine engine;
sc = engine.evaluate("(" + QString(result) + ")");
if (sc.property("authenticated").toBoolean() == true) {
qDebug("Login Authenticated");
int units = sc.property("units").toInteger();
int hold_items_count = sc.property("hold_items_count").toInteger();
QString aUsername = sc.property("username").toString();
QString aPassword = sc.property("password").toString();
if ( aUsername.length() && aPassword.length() ) {
username = aUsername;
password = aPassword;
}
doLoginTasks(units, hold_items_count);
} else {
qDebug("Login Failed");
QString errorCode = sc.property("error").toString();
qDebug() << "Error Code: " << errorCode;
username.clear();
password.clear();
emit loginFailed(errorCode);
}
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
qDebug("LEAVE NetworkClient::processAttemptLogoutReply");
}
void NetworkClient::attemptLogout() {
qDebug("ENTER NetworkClient::attemptLogout");
QNetworkAccessManager *nam;
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(processAttemptLogoutReply(QNetworkReply *)));
QObject::connect(
nam, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
QUrl url = QUrl(serviceURL);
QUrlQuery query = QUrlQuery(urlQuery);
query.addQueryItem("version", VERSION);
query.addQueryItem("action", "logout");
query.addQueryItem("username", username);
query.addQueryItem("password", password);
url.setQuery(query);
/*QNetworkReply* reply =*/nam->get(buildRequest(url));
qDebug("LEAVE NetworkClient::attemptLogout");
}
void NetworkClient::processAttemptLogoutReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::processAttemptLogoutReply");
handleNetworkReplyErrors(reply);
QByteArray result;
result = reply->readAll();
QScriptValue sc;
QScriptEngine engine;
sc = engine.evaluate("(" + QString(result) + ")");
if (sc.property("logged_out").toBoolean() == true) {
doLogoutTasks();
} else {
emit logoutFailed();
}
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
qDebug("LEAVE NetworkClient::processAttemptLogoutReply");
}
void NetworkClient::getUserDataUpdate() {
qDebug("ENTER NetworkClient::getUserDataUpdate");
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(processGetUserDataUpdateReply(QNetworkReply *)));
QObject::connect(
nam, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
QUrl url = QUrl(serviceURL);
QUrlQuery query = QUrlQuery(urlQuery);
query.addQueryItem("version", VERSION);
query.addQueryItem("action", "get_user_data");
query.addQueryItem("username", username);
query.addQueryItem("password", password);
url.setQuery(query);
/*QNetworkReply* reply =*/nam->get(buildRequest(url));
qDebug("LEAVE NetworkClient::getUserDataUpdate");
}
void NetworkClient::processGetUserDataUpdateReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::processGetUserDataUpdateReply");
handleNetworkReplyErrors(reply);
QByteArray result;
result = reply->readAll();
qDebug() << "Server Result: " << result;
QJsonDocument jd = QJsonDocument::fromJson(result);
if (jd.isObject()) {
QJsonObject jo = jd.object();
QString status = jo["status"].toString();
qDebug() << "STATUS: " << status;
if (status == "Logged in") {
QJsonArray messages = jo["messages"].toArray();
qDebug() << "MESSAGE ARRAY SIZE: " << messages.size();
for (int i = 0; i < messages.size(); i++) {
QString m = messages[i].toString();
qDebug() << "MESSAGE: " << m;
emit messageRecieved(m);
}
QJsonValueRef units_json = jo["units"];
QVariant units_variant = units_json.toVariant();
int units = units_variant.toInt();
qDebug() << "UNITS JASON: " << units_json;
qDebug() << "UNITS VARIANT: " << units_variant;
qDebug() << "UNITS: " << units;
emit timeUpdatedFromServer(units);
if (units < 1) {
doLogoutTasks();
}
} else if (status == "Logged out") {
doLogoutTasks();
} else if (status == "Kicked") {
doLogoutTasks();
}
}
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
qDebug("LEAVE NetworkClient::processGetUserDataUpdateReply");
}
void NetworkClient::uploadPrintJobs() {
qDebug() << "NetworkClient::uploadPrintJobs";
QSettings printerSettings;
printerSettings.beginGroup("printers");
QStringList printers = printerSettings.allKeys();
qDebug() << "PRINTER: " << printers;
foreach (const QString &printer, printers) {
qDebug() << "FOUND PRINTER: " << printer;
qDebug() << "PATH: " << printerSettings.value(printer).toString();
QString directory = printerSettings.value(printer).toString();
QDir dir(directory);
if (!dir.exists()) {
qDebug() << "Directory does not exist: " << directory;
bool s = dir.mkpath(directory);
qDebug() << "Attempt to create directory result: " << s;
}
dir.setFilter(QDir::Files);
dir.setSorting(QDir::Time | QDir::Reversed);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
QString absoluteFilePath = fileInfo.absoluteFilePath();
SubmitPrintRequest request;
request.filename = absoluteFilePath;
request.printer = printer;
request.copies = 0;
request.pageCount = 0;
uploadPrintJob(request);
}
}
qDebug() << "LEAVE NetworkClient::uploadPrintJobs";
}
void NetworkClient::uploadPrintJob(const SubmitPrintRequest &request) {
QFile *file = new QFile(request.filename);
bool opened = file->open(QIODevice::ReadOnly);
if ( !opened ) {
qDebug() << "OPENING FILE " << request.filename << " FAILED! SKIPPING FILE.";
return;
}
QFileInfo fileInfo = request.filename;
QString fileNameOnly = fileInfo.fileName();
// If the file is less than 1 kb, it's still being written. An empty PDF is about 3.7K
if ( fileInfo.size() < 2048 ) {
qWarning() << "File size too small: " << fileNameOnly;
return;
}
// If the file is not writable, the print driver hasn't finished writing the PDF
if (!fileInfo.isWritable()) {
qWarning() << "File not writable: " << fileNameOnly;
return;
}
const QString printedFileSuffix = ".printed";
if (request.filename.endsWith(printedFileSuffix)) {
return;
}
qDebug() << "SENDING PRINT JOB: " << fileNameOnly;
QString fileCounterString = QString::number(fileCounter);
fileCounter++;
QString newAbsoluteFilePath =
request.filename + "." + fileCounterString + printedFileSuffix;
bool renamed = file->rename(request.filename, newAbsoluteFilePath);
if ( !renamed ) {
qWarning() << "RENAME FROM " << request.filename << " TO " << newAbsoluteFilePath << " FAILED!";
}
QHttpMultiPart *multiPart =
new QHttpMultiPart(QHttpMultiPart::FormDataType);
// We con't delete the file object now, delete it with the multiPart
file->setParent(multiPart);
QHttpPart clientNamePart;
clientNamePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=client_name"));
QByteArray clientNameQBA;
clientNameQBA.append(nodeName);
clientNamePart.setBody(clientNameQBA);
multiPart->append(clientNamePart);
QHttpPart userNamePart;
userNamePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=username"));
QByteArray userNameQBA;
userNameQBA.append(username);
userNamePart.setBody(userNameQBA);
multiPart->append(userNamePart);
QHttpPart printerNamePart;
printerNamePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=printer"));
QByteArray printerNameQBA;
printerNameQBA.append(request.printer);
printerNamePart.setBody(printerNameQBA);
multiPart->append(printerNamePart);
QHttpPart printJobPart;
printJobPart.setHeader(
QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=print_file; filename=" + fileNameOnly));
printJobPart.setBodyDevice(file);
multiPart->append(printJobPart);
QHttpPart fileNamePart;
fileNamePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=filename"));
QByteArray fileNameQBA;
fileNameQBA.append(fileNameOnly);
fileNamePart.setBody(fileNameQBA);
multiPart->append(fileNamePart);
QHttpPart copiesPart;
copiesPart.setHeader(
QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"copies\""));
copiesPart.setBody(
QByteArray::number(request.copies));
multiPart->append(copiesPart);
QUrl printUrl = QUrl(serviceURL);
printUrl.setPath("/api/client/v1_0/print");
QNetworkRequest netrequest = buildRequest(printUrl);
QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
QObject::connect(
networkManager,
SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
QNetworkReply *reply = networkManager->post(netrequest, multiPart);
multiPart->setParent(reply); // delete the multiPart with the reply
// TODO: delete file after finished signal emits
// https://stackoverflow.com/questions/5153157/passing-an-argument-to-a-slot
connect(networkManager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(uploadPrintJobReply(QNetworkReply *)));
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this,
SLOT(handleUploadProgress(qint64, qint64)));
}
void NetworkClient::handleUploadProgress(qint64 bytesSent, qint64 bytesTotal) {
qDebug() << "Uploaded " << bytesSent << "of" << bytesTotal;
}
void NetworkClient::uploadPrintJobReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::uploadPrintJobReply");
handleNetworkReplyErrors(reply);
if (reply->error() == QNetworkReply::NoError) {
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
} else {
qWarning() << "Network Error: " << reply->errorString();
qWarning() << "Retrying network request.";
QNetworkRequest request = reply->request();
QHttpMultiPart *multiPart = reply->findChild<QHttpMultiPart *>();
qDebug() << "Found multiPart " << multiPart;
QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
QObject::connect(
networkManager,
SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
QNetworkReply *reply = networkManager->post(request, multiPart);
multiPart->setParent(reply); // delete the multiPart with the reply
connect(networkManager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(uploadPrintJobReply(QNetworkReply *)));
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this,
SLOT(handleUploadProgress(qint64, qint64)));
};
qDebug("LEAVE NetworkClient::uploadPrintJobReply");
}
void NetworkClient::registerNode() {
qDebug("ENTER NetworkClient::registerNode");
QNetworkAccessManager *nam;
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(processRegisterNodeReply(QNetworkReply *)));
QObject::connect(nam, SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
this,
SLOT(handleSslErrors(QNetworkReply *, QList<QSslError>)));
QUrl url = QUrl(serviceURL);
QUrlQuery query = QUrlQuery(urlQuery);
query.addQueryItem("version", VERSION);
query.addQueryItem("action", "register_node");
query.addQueryItem("node_name", nodeName);
query.addQueryItem("age_limit", nodeAgeLimit);
url.setQuery(query);
/*QNetworkReply* reply =*/nam->get(buildRequest(url));
qDebug("LEAVE NetworkClient::registerNode");
}
void NetworkClient::handleSslErrors(QNetworkReply *reply,
QList<QSslError> error) {
reply->ignoreSslErrors(error);
}
void NetworkClient::processRegisterNodeReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::processRegisterNodeReply");
handleNetworkReplyErrors(reply);
QByteArray result;
result = reply->readAll();
qDebug() << "Server Result: " << result;
QScriptValue sc;
QScriptEngine engine;
sc = engine.evaluate("(" + QString(result) + ")");
if (!sc.property("registered").toBoolean()) {
qWarning("Node Registration FAILED");
}
// session unlocking
if (sc.property("unlock").toBoolean()) {
qDebug("Unlocking...");
emit unlockSession();
}
// auto guest creation (formerly 'unlock')
if (sc.property("autologin").toBoolean()) {
qDebug("Automatically logging in a new guest session...");
username = sc.property("username").toString();
doLoginTasks(sc.property("minutes").toInteger(), 0);
}
if (sc.property("shutdown").toBoolean()) {
qDebug("Received shutdown message from server");
emit allowClose(true);
#ifdef Q_OS_WIN
QProcess::startDetached("shutdown -s -f -t 0");
#endif // ifdef Q_OS_WIN
#ifdef Q_OS_UNIX
// For this to work, sudo must be installed and the line
// %shutdown ALL=(root) NOPASSWD: /sbin/reboot FIXME
// needs to be added to /etc/sudoers
QProcess::startDetached("sudo shutdown 0");
#endif // ifdef Q_OS_UNIX
}
if (sc.property("suspend").toBoolean()) {
#ifdef Q_OS_WIN
QProcess::startDetached("rundll32.exe powrprof.dll,SetSuspendState 0,1,0");
#endif // ifdef Q_OS_WIN
#ifdef Q_OS_UNIX
QProcess::startDetached("systemctl suspend -i");
#endif // ifdef Q_OS_UNIX
}
if (sc.property("restart").toBoolean()) {
emit allowClose(true);
#ifdef Q_OS_WIN
QProcess::startDetached("shutdown -r -f -t 0");
#endif // ifdef Q_OS_WIN
#ifdef Q_OS_UNIX
// For this to work, sudo must be installed and the line
// %shutdown ALL=(root) NOPASSWD: /sbin/reboot
// needs to be added to /etc/sudoers
QProcess::startDetached("sudo reboot");
#endif // ifdef Q_OS_UNIX
}
if (sc.property("wakeup").toBoolean()) {
QStringList MAC_addresses = sc.engine()->fromScriptValue<QStringList>(
sc.property("wol_mac_addresses"));
wakeOnLan(MAC_addresses, sc.property("wol_host").toString(),
sc.property("wol_port").toInteger());
}
if (sc.property("drop").toBoolean()) {
#ifdef Q_OS_WIN
QProcess::startDetached("c:/windows/explorer.exe");
QProcess::startDetached("windows/on_login.exe");
#endif // ifdef Q_OS_WIN
exit(1);
}
QString styleSheet = sc.property("ClientStyleSheet").toString();
if (!styleSheet.isEmpty()) {
this->app->setStyleSheet(styleSheet);
}
QSettings settings;
settings.setIniCodec("UTF-8");
QString bannerTopURL = settings.value("session/BannerTopURL").toString();
QString bannerBottomURL =
settings.value("session/BannerBottomURL").toString();
settings.setValue("session/ClientBehavior",
sc.property("ClientBehavior").toString());
settings.setValue("session/ReservationShowUsername",
sc.property("ReservationShowUsername").toString());
settings.setValue("session/EnableClientSessionLocking",
sc.property("EnableClientSessionLocking").toString());
settings.setValue("session/EnableClientPasswordlessMode",
sc.property("EnableClientPasswordlessMode").toString());
settings.setValue("session/TermsOfService",
sc.property("TermsOfService").toString());
settings.setValue("session/TermsOfServiceDetails",
sc.property("TermsOfServiceDetails").toString());
settings.setValue("session/BannerTopURL",
sc.property("BannerTopURL").toString());
settings.setValue("session/BannerTopWidth",
sc.property("BannerTopWidth").toString());
settings.setValue("session/BannerTopHeight",
sc.property("BannerTopHeight").toString());
settings.setValue("session/BannerBottomURL",
sc.property("BannerBottomURL").toString());
settings.setValue("session/BannerBottomWidth",
sc.property("BannerBottomWidth").toString());
settings.setValue("session/BannerBottomHeight",
sc.property("BannerBottomHeight").toString());
settings.setValue("session/LogoURL",
sc.property("Logo").toString());
settings.setValue("session/LogoWidth",
sc.property("LogoWidth").toString());
settings.setValue("session/LogoHeight",
sc.property("LogoHeight").toString());
settings.setValue("session/inactivityLogout",
sc.property("inactivityLogout").toString());
settings.setValue("session/inactivityWarning",
sc.property("inactivityWarning").toString());
settings.setValue("session/InternetConnectivityURLs",
sc.property("InternetConnectivityURLs").toString());
settings.setValue("session/EnableGuestSelfRegistration",
sc.property("EnableGuestSelfRegistration").toString());
settings.setValue("session/ShowTimeRemainingInSplash",
sc.property("ShowTimeRemainingInSplash").toString());
settings.setValue("session/ShowTimeRemainingInTray",
sc.property("ShowTimeRemainingInTray").toString());
settings.setValue("session/ClientTimeNotificationFrequency",
sc.property("ClientTimeNotificationFrequency").toString());
settings.setValue("session/ClientTimeWarningThreshold",
sc.property("ClientTimeWarningThreshold").toString());
settings.setValue("session/ClientTimeWarningFrequency",
sc.property("ClientTimeWarningFrequency").toString());
QString logoURL = settings.value("images/logo").toString();
QString guestRegistrationEnabled = settings.value("session/EnableGuestSelfRegistration").toString();
settings.sync();
if (
(logoURL != sc.property("Logo").toString()) ||
(bannerTopURL != sc.property("BannerTopURL").toString()) ||
(bannerBottomURL != sc.property("BannerBottomURL").toString()) ||
(guestRegistrationEnabled != sc.property("EnableGuestSelfRegistration").toString())
) {
emit handleBanners(); // TODO: Emit only if a banner url has changed
}
QString reserved_for = sc.property("reserved_for").toString();
emit setReservationStatus(reserved_for);
QString status = sc.property("status").toString();
if (status != clientStatus) {
if (status == "suspended") {
emit clientSuspended();
} else if (status == "online") {
emit clientOnline();
}
}
clientStatus = status;
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
qDebug("LEAVE NetworkClient::processRegisterNodeReply");
}
void NetworkClient::checkForInternetConnectivity() {
qDebug("ENTER NetworkClient::checkForInternetConnectivity");
QList<QString> list;
QSettings settings;
settings.setIniCodec("UTF-8");
QString internetConnectivityURLs = settings.value("session/InternetConnectivityURLs").toString();
//qDebug() << "URLS: " << internetConnectivityURLs;
if ( internetConnectivityURLs != "null" ) {
list = internetConnectivityURLs.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
}
//qDebug() << "URLS LIST: " << list.join(" ");
if ( list.size() ) {
// Select a URL from the list at random to test connectivity
QString url = list.at(qrand() % list.size());
qDebug() << "CHECKING URL: " << url;
QNetworkAccessManager *nam;
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(processCheckForInternetConnectivityReply(QNetworkReply *)));
QObject::connect(
nam, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
nam->get(QNetworkRequest(QUrl(url)));
}
qDebug("LEAVE NetworkClient::checkForInternetConnectivity");
}
void NetworkClient::processCheckForInternetConnectivityReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::processCheckForInternetConnectivityReply");
if ( reply->error() != QNetworkReply::NoError ) {
emit internetAccessWarning(reply->errorString());
qWarning() << "NetworkClient::processCheckForInternetConnectivityReply Network Reply Error: " << reply->errorString();
} else {
emit internetAccessWarning("");
}
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
qDebug("LEAVE NetworkClient::processCheckForInternetConnectivityReply");
}
void NetworkClient::clearMessage() {
qDebug("ENTER NetworkClient::clearMessage");
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(ignoreNetworkReply(QNetworkReply *)));
QObject::connect(
nam, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
QUrl url = QUrl(serviceURL);
QUrlQuery query = QUrlQuery(urlQuery);
query.addQueryItem("version", VERSION);
query.addQueryItem("action", "clear_message");
query.addQueryItem("username", username);
query.addQueryItem("password", password);
url.setQuery(query);
nam->get(buildRequest(url));
qDebug("LEAVE NetworkClient::clearMessage");
}
void NetworkClient::acknowledgeReservation(QString reserved_for) {
qDebug("ENTER NetworkClient::acknowledgeReservation");
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply *)), this,
SLOT(ignoreNetworkReply(QNetworkReply *)));
QObject::connect(
nam, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)), this,
SLOT(handleSslErrors(QNetworkReply *, const QList<QSslError> &)));
QUrl url = QUrl(serviceURL);
QUrlQuery query = QUrlQuery(urlQuery);
query.addQueryItem("version", VERSION);
query.addQueryItem("action", "acknowledge_reservation");
query.addQueryItem("reserved_for", reserved_for);
url.setQuery(query);
nam->get(buildRequest(url));
qDebug("LEAVE NetworkClient::acknowledgeReservation");
}
void NetworkClient::ignoreNetworkReply(QNetworkReply *reply) {
qDebug("ENTER NetworkClient::ignoreNetworkReply");
handleNetworkReplyErrors(reply);
reply->abort();
reply->deleteLater();
reply->manager()->deleteLater();
qDebug("LEAVE NetworkClient::ignoreNetworkReply");
}
void NetworkClient::doLoginTasks(int units, int hold_items_count) {
qDebug("ENTER NetworkClient::doLoginTasks");
#ifdef Q_OS_WIN
// FIXME: We should delete print jobs at login as well in case a client crash
// prevented the print jobs for getting cleaned up at logout time
// If this is an MS Windows platform, use the keylocker programs to limit
// mischief.
QProcess::startDetached("c:/windows/explorer.exe");
QProcess::startDetached("windows/on_login.exe");
#endif // ifdef Q_OS_WIN
uploadPrintJobsTimer->start(1000 * 2);
updateUserDataTimer->start(1000 * 10);
QSettings settings;
settings.setIniCodec("UTF-8");
settings.setValue("session/LoggedInUser", username);
settings.sync();
qDebug() << "SCRIPTLOGIN:" << settings.value("scriptlogin/enable").toString();
if (settings.value("scriptlogin/enable").toString() == "1") {
QProcess::startDetached(settings.value("scriptlogin/script").toString());
}
emit loginSucceeded(username, password, units, hold_items_count);
qDebug("ENTER NetworkClient::doLoginTasks");
}
void NetworkClient::doLogoutTasks() {
qDebug("ENTER NetworkClient::doLogoutTasks");
QSettings settings;
settings.setIniCodec("UTF-8");
settings.setValue("session/LoggedInUser", "");
settings.sync();
// Delete print jobs
QSettings printerSettings;
printerSettings.beginGroup("printers");
QStringList printers = printerSettings.allKeys();
foreach (const QString &printer, printers) {
QString directory = printerSettings.value(printer).toString();
QDir dir(directory);
dir.setFilter(QDir::Files);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
QString absoluteFilePath = fileInfo.absoluteFilePath();
QFile::remove(absoluteFilePath);
}
}
uploadPrintJobsTimer->stop();
updateUserDataTimer->stop();
username.clear();
password.clear();
#ifdef Q_OS_WIN
// If this is an MS Windows platform, use the keylocker programs to limit
// mischief.
QProcess::startDetached("taskkill /f /im explorer.exe");
QProcess::startDetached("windows/on_logout.exe");
if (actionOnLogout == LogoutAction::Logout) {
emit allowClose(true);
QProcess::startDetached("shutdown -l -f");
} else if (actionOnLogout == LogoutAction::Reboot) {
emit allowClose(true);
QProcess::startDetached("shutdown -r -f -t 0");
}
#endif // ifdef Q_OS_WIN
#ifdef Q_OS_UNIX
if (actionOnLogout == LogoutAction::Logout) {
emit allowClose(true);
// Restart KDE 4
QProcess::startDetached(
"qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout "
"-0 -1 -1");
// Restart Gnome
QProcess::startDetached("gnome-session-save --kill --silent");
// Restart Unity
QProcess::startDetached("gnome-session-quit --no-prompt");
// Restart XFCE 4
QProcess::startDetached("/usr/bin/xfce4-session-logout");
// Restart Mate
QProcess::startDetached("mate-session-save --force-logout");
} else if (actionOnLogout == LogoutAction::Reboot) {
emit allowClose(true);
// For this to work, sudo must be installed and the line
// %shutdown ALL=(root) NOPASSWD: /sbin/reboot
// needs to be added to /etc/sudoers
QProcess::startDetached("sudo reboot");
}
#endif // ifdef Q_OS_UNIX
qDebug() << "SCRIPTLOGOUT:"
<< settings.value("scriptlogout/enable").toString();
if (settings.value("scriptlogout/enable").toString() == "1") {
QProcess::startDetached(settings.value("scriptlogout/script").toString());
}
emit logoutSucceeded();
qDebug("LEAVE NetworkClient::doLogoutTasks");
}
void NetworkClient::wakeOnLan(QStringList MAC_addresses, QString host,
qint64 port) {
qDebug("ENTER NetworkClient::wakeOnLan");
QHostAddress host_address;
host_address.setAddress(host);
for (int i = 0; i < MAC_addresses.size(); i++) {
char address[6];
char packet[102];
memset(packet, 0xff, 6);
for (int j = 0; j < 6; j++) {
address[j] = MAC_addresses.at(i).section(":", j, j).toInt(Q_NULLPTR, 16);
}
for (int j = 1; j <= 16; j++) {
memcpy(&packet[j * 6], &address, 6 * sizeof(char));
}
QUdpSocket udpSocket;
udpSocket.writeDatagram(packet, 102, host_address, port);
}