-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patholop.cpp
More file actions
765 lines (640 loc) · 26.3 KB
/
olop.cpp
File metadata and controls
765 lines (640 loc) · 26.3 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
#include "olop.hpp"
#include "ui_mainwindow.h"
#include <QtHttpServer>
#include <QDesktopServices>
#include <QApplication>
#include <QMessageBox>
#include <QTimer>
#include <QHttpServer>
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QWebEngineScript>
#include <QTcpServer>
QString def = "Olop n'a pas été initialisé\nSi vous êtes le développeur de cette application, veuillez utiliser \"MAIN::INIT();\" au démarrage.";
const QString MAIN::HOME = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).value(0) + "/";
QString MAIN::VERSION = "daily";
const QString MAIN::O_DIR = HOME + "Olop/";
const QString MAIN::APP_DIR = O_DIR + "/App/";
QHttpServer MAIN::httpServer;
MainWindow* MAIN::w;
QString MAIN::osname = def;
QList<QHttpServer*> APP::httpServers;
QString NETWORK::port = "";
int MAIN::mode = 0;
QHttpServerResponse CORSHEAD(const QString &content) {
QHttpServerResponse response(content);
response.setHeader("Access-Control-Allow-Origin", "qrc:");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
return response;
}
QHttpServerResponse CORSHEAD(const char* content) {
return CORSHEAD(QString(content));
}
QHttpServerResponse CORSHEAD(const QByteArray &content) {
return CORSHEAD(QString(content));
}
QHttpServerResponse CORSHEAD(QHttpServerResponse &&response) {
response.setHeader("Access-Control-Allow-Origin", "http://localhost");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
return std::move(response);
}
void sendJavaScriptToUi(const QString& script) {
QLocalSocket socket;
socket.connectToServer("Olop-threads-"+NETWORK::port);
if(socket.waitForConnected()) {
socket.write(("1" + script).toUtf8()); // ajoutez "1" devant le script
socket.flush();
socket.waitForBytesWritten();
}
}
bool MAIN::ecrireDansFichier(const QString& cheminFichier, const QByteArray& contenu) {
QFile fichier(cheminFichier);
if (fichier.open(QIODevice::WriteOnly)) {
fichier.write(contenu);
fichier.close();
return true;
} else {
qDebug() << "Impossible d'ouvrir le fichier en écriture :" << fichier.errorString();
return false;
}
}
bool MAIN::ecrireDansFichier(const QString& cheminFichier, const QString& contenu) {
QFile fichier(cheminFichier);
if (fichier.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream flux(&fichier);
flux << contenu;
fichier.close();
return true;
} else {
qDebug() << "Impossible d'ouvrir le fichier en écriture :" << fichier.errorString();
return false;
}
}
bool MAIN::INIT(int mode) {
MAIN::mode=mode;
if(MAIN::mode==0){
QMessageBox::critical(nullptr, "Olop - Erreur critique", "<h2 style=\"font-size:15px;\">Houston, we have a problem</h2>Olop n'arrive pas à déterminer le mode de démmarrage.<br><i><b>Essayer de mettre à jour / de réinstaller Olop</b></i>");
MAIN::Exit(-1);
}else {
qDebug() << "Olop est en mode "+QString::number(mode);
}
if (!MAIN::mkdir(O_DIR)) {
return false;
}
if (!MAIN::mkdir(APP_DIR)) {
return false;
}
#if defined(Q_OS_WIN)
osname = "Windows";
#elif defined(Q_OS_LINUX)
osname = "Linux";
#elif defined(Q_OS_MACOS)
osname = "macOS";
#else
QMessageBox::critical(nullptr, "Erreur", "Ce système est inconnu (n'est pas WIndows, ni Linux, ni macOS).\nOlop ne peut pas fonctionner correctement et va s'arrêter.");
exit(-1);
#endif
return true;
}
int MAIN::SERVER(QString ports){
int port = ports.toInt();
httpServer.route("/index.html", []() {
#ifdef Q_OS_LINUX
return CORSHEAD(MAIN::lireFichier(QStringLiteral(":/assets/index.html"))+"<script>"+MAIN::lireFichier(QStringLiteral(":/assets/linux.js"))+"</script>");
#else
return CORSHEAD(QHttpServerResponse::fromFile(QStringLiteral(":/assets/index.html")));
#endif
});
httpServer.route("/Applist.html", [](){
return CORSHEAD(APP::LIST(MAIN::APP_DIR));
});
httpServer.route("/Install/1/<arg>", [](const QUrl &Url){
QNetworkAccessManager* manager = new QNetworkAccessManager();
QNetworkRequest request(Url);
QNetworkReply* reply = manager->get(request);
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
QByteArray data = reply->readAll();
delete reply;
delete manager;
if (data.isEmpty()) {
return CORSHEAD(QString("Erreur, vérifiez l'URL et votre connexion internet"));
} else {
QStringList app = APP::decodeApp(data);
int rand = QRandomGenerator::global()->bounded(0, 99999 + 1);
MAIN::ecrireDansFichier(MAIN::O_DIR+QString::number(rand)+".app", data);
QString redirectUrl = "https://olop.rf.gd/Store/InstallPass/?name=" + QUrl::toPercentEncoding(app[1]) + "&version=" + QUrl::toPercentEncoding(app[2]) +"&dev=" + QUrl::toPercentEncoding(app[4]) +"&description=" + QUrl::toPercentEncoding(app[7]) +"&code=" + QUrl::toPercentEncoding(QString::number(rand));
QString encodedRedirectUrl = QUrl(redirectUrl.toUtf8()).toEncoded();
return CORSHEAD(QString("<script type=\"text/javascript\">location.href=\"" + encodedRedirectUrl +"&port=\" + location.port;</script><noscript>Activez javascript</noscript>"));
}
});
httpServer.route("/Install/2/<arg>", [](const QUrl &Url){
qDebug() << Url;
QStringList app = APP::decodeApp(MAIN::lireFichier(MAIN::O_DIR+Url.toDisplayString()+".app"));
if(!MAIN::moveFile(MAIN::O_DIR+Url.toDisplayString()+".app", MAIN::O_DIR+"App/"+Url.toDisplayString()+".app")){
QMessageBox::critical(MAIN::w, "Erreur", "Erreur lors de l'installation de l'application "+app[1]);
return CORSHEAD("Erreur lors de l'installation de l'application "+app[1]);
}
sendJavaScriptToUi("showNotification(0, \"Installation d'une application\", \"L\'application " + app[1] + " est prête à être installée.<br>Elle sera installée lorsque vous la démarrerez.\");");
return CORSHEAD("<script>location.href=\"https://olop.rf.gd/Store/?Installed="+QUrl::toPercentEncoding(app[1])+"\";</script><noscript><a href=\"https://olop.rf.gd/Store/?Installed="+app[1]+"\">Cliquez ici</a> et activez javascript</noscript>");
});
httpServer.route("/Launch/1/<arg>", [=](const QUrl &Url) {
auto args = Url.toDisplayString().split("-OLOP-");
auto appfile = args[0];
auto id = args[1];
auto decodedApp = APP::decodeApp(lireFichier(appfile));
auto appdir = appfile.split(".app")[0] + "/";
auto packageurl = decodedApp[3] + "/" + QUrl::toPercentEncoding(decodedApp[1]) + "-package.zip";
auto appurl = decodedApp[3] + "/" + QUrl::toPercentEncoding(decodedApp[1]) + ".txt";
qDebug() << decodedApp;
// Configurez le timer
auto setupTimerAndCounter = [&](QSharedPointer<QString> message, QPointer<QTimer> timer) {
timer->setInterval(1000);
int counter = 0;
QObject::connect(timer, &QTimer::timeout, [=]() mutable {
counter = counter % 4;
QString points = QString(".").repeated(counter++);
QString jsCode = QString("$(\"#%1\").html(\"" + *message + "%2\");")
.arg(id).arg(points);
sendJavaScriptToUi(jsCode);
});
timer->start();
};
QSharedPointer<QString> currentMessage(new QString("Lancement en cours de "+decodedApp[1]));
QPointer<QTimer> primaryTimer = new QTimer();
setupTimerAndCounter(currentMessage, primaryTimer);
APP *app = new APP;
auto launch = [=](){
if(!primaryTimer) {
qDebug() << "primaryTimer is null!";
} else {
primaryTimer->stop();
}
primaryTimer->deleteLater(); // puis, demandez la suppression
int port = app->HTTPSERVER(appdir);
qDebug() << port;
sendJavaScriptToUi("findWindowAndConvertToIframe(\"" + id + "\", \"http://localhost:" + QString::number(port) + "/index.html\");");
};
QTimer::singleShot(10, [=]() {
if (!QDir(appdir).exists()) {
MAIN::mkdir(appdir);
MAIN::ecrireDansFichier(QDir::tempPath() + "/tmp.zip", NETWORK::Download(QUrl(packageurl)));
FILES::unZip(QDir::tempPath() + "/tmp.zip", appdir);
launch();
} else {
QString newappfile = NETWORK::Download(QUrl(appurl));
qDebug() << appurl;
if (!newappfile.isEmpty() && newappfile != "ERR") {
auto newappdecoded = APP::decodeApp(newappfile);
if (newappdecoded[2] != decodedApp[2]) {
qDebug() << "Mise à jour disponible.";
int response;
response = QMessageBox::question(w, "Mise à jour", "L'application " + decodedApp[1] + " n'est pas à sa dernière version.\nSouhaitez-vous la mettre à jour ?", QMessageBox::Yes | QMessageBox::No);
if (response == QMessageBox::Yes) {
std::thread t([=](){
qDebug() << "Mise à jour en cours...";
*currentMessage="Téléchargement de la mise à jour de "+decodedApp[1]+" en cours";
MAIN::ecrireDansFichier(QDir::tempPath() + "/tmp.zip", NETWORK::Download(QUrl(packageurl)));
*currentMessage="Installation de la mise à jour de "+decodedApp[1]+" en cours";
FILES::unZip(QDir::tempPath() + "/tmp.zip", appdir, [=](){
*currentMessage="Nettoyage";
});
qDebug() << "Dézippé";
*currentMessage="Finitialisation de la mise à jour de "+decodedApp[1];
MAIN::ecrireDansFichier(appfile, newappfile);
*currentMessage="Mise à jour terminée. Lancement de "+decodedApp[1]+" en cours";
executeInMainThread(launch);
});
t.detach();
}else {
launch();
}
}else {
launch();
}
}else {
qDebug() << "Erreur d'update (vérifiez votre connexion internet)";
launch();
}
}
});
return CORSHEAD(QString("Chargement..."));
});
httpServer.route("/remove/<arg>", [=](const QUrl Url){
auto args = Url.toDisplayString().split("-OLOP-");
auto app = args[0];
auto id = args[1];
auto decodedApp(APP::decodeApp(lireFichier(app)));
qDebug() << app;
auto réponse = QMessageBox::question(w, "Confirmation", "Êtes-vous sûr de vouloir désinstaller "+decodedApp[1]+" ?", QMessageBox::Yes | QMessageBox::No);
if(réponse == QMessageBox::Yes){
sendJavaScriptToUi("$(\"#"+id+"\").html(\"Suppression...\");");
deleteFile(app);
supprimerDossier(app.split(".app")[0]+"/");
sendJavaScriptToUi("setTimeout(() => {loadPage(\"home\");}, 500);");
return CORSHEAD("Suppression terminée.");
}else {
sendJavaScriptToUi("tmpHTML(\""+id+"\", 4000, \"La suppression de l'application "+decodedApp[1]+" a été annulée.\");");
return CORSHEAD("OK");
}
});
httpServer.route("/stop/", [](){
exit(0);
return CORSHEAD("");
});
httpServer.route("/getapp/<arg>", [](const QUrl &Url) {
return CORSHEAD(lireFichier(Url.toDisplayString()));
});
httpServer.route("/checkurl/200/<arg>", [](const QUrl &Url){
/*if(NETWORK::checkURLAccess(Url.toDisplayString())){
return CORSHEAD("1");
}*/
return CORSHEAD("0");
});
/*httpServer.route("/actions/goupdate/", [](){
QString downloadUrl = "https://github.com/SuperAtraction/Olop/raw/main/InstallOlop.sh";
QNetworkAccessManager networkManager;
QNetworkReply* reply = networkManager.get(QNetworkRequest(QUrl(downloadUrl)));
QEventLoop eventLoop;
QObject::connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error downloading file:" << reply->errorString();
reply->deleteLater();
QMessageBox::critical(nullptr, "Erreur", "Une erreur est survenue durant la mise à jour");
}
return CORSHEAD("");
});*/
httpServer.route("/query", [] (const QHttpServerRequest &request) {
return CORSHEAD(QString("%1/query/").arg(request.value("Host")));
});
httpServer.route("/<arg>", [] (const QUrl &url) {
return CORSHEAD(QHttpServerResponse::fromFile(QStringLiteral(":/assets/%1").arg(url.path())));
});
if (!httpServer.listen(QHostAddress::Any, port)) {
qDebug() << "Erreur lors du démarrage du serveur sur le port" << port;
return 0;
}
return port;
}
void MAIN::executeInMainThread(std::function<void()> func) {
QMetaObject::invokeMethod(w, [=]() { func(); }, Qt::QueuedConnection);
}
bool MAIN::isVersionGreater(const QString& newVersion, const QString& oldVersion) {
QStringList newComponents = newVersion.split(".");
QStringList oldComponents = oldVersion.split(".");
int n = qMin(newComponents.size(), oldComponents.size());
for(int i = 0; i < n; ++i) {
int newComponent = newComponents[i].toInt();
int oldComponent = oldComponents[i].toInt();
if(newComponent > oldComponent) {
return true;
} else if(newComponent < oldComponent) {
return false;
}
}
return newComponents.size() > oldComponents.size();
}
bool MAIN::mkdir(QString path) {
QDir dir = path;
if (!dir.exists()) {
bool ook = dir.mkpath(dir.path());
if (!ook) {
return false;
}
}
return true;
}
QByteArray MAIN::lireFichier(const QString& cheminFichier) {
QFile fichier(cheminFichier);
if (!fichier.open(QIODevice::ReadOnly)) { // Note l'absence de QIODevice::Text
return QByteArray(); // Retourne un QByteArray vide en cas d'erreur
}
QByteArray contenu = fichier.readAll();
fichier.close();
return contenu;
}
bool MAIN::supprimerDossier(const QString& cheminDossier) {
QDir dossier(cheminDossier);
if (!dossier.exists()) {
qDebug() << "Le dossier n'existe pas!";
return false;
}
// Supprimer tous les fichiers dans le dossier
Q_FOREACH(QFileInfo info, dossier.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::Files, QDir::DirsFirst)) {
if (info.isFile()) {
QFile fichier(info.filePath());
if (!fichier.remove()) {
qDebug() << "Impossible de supprimer le fichier" << info.fileName();
return false;
}
}
else {
supprimerDossier(info.absoluteFilePath());
}
}
// Supprimer tous les dossiers vides
Q_FOREACH(QFileInfo info, dossier.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::Dirs, QDir::DirsFirst)) {
if (!QDir(info.absoluteFilePath()).removeRecursively()) {
qDebug() << "Impossible de supprimer le dossier" << info.absoluteFilePath();
return false;
}
}
return dossier.rmdir(cheminDossier);
}
bool MAIN::deleteFile(const QString& filePath) {
QFile file(filePath);
if (!file.exists()) {
qWarning() << "Le fichier n'existe pas :" << filePath;
return false;
}
if (!file.remove()) {
qWarning() << "Erreur lors de la suppression du fichier :" << file.errorString();
return false;
}
return true;
}
bool MAIN::copyFile(const QString& sourceFilePath, const QString& destinationFilePath) {
QString content = lireFichier(sourceFilePath);
if (content.isEmpty()) {
qWarning() << "Erreur lors de la copie : Le fichier ne peut pas être ouvert";
}
return ecrireDansFichier(destinationFilePath, content);
}
bool MAIN::moveFile(const QString& sourceFilePath, const QString& destinationFilePath) {
if (!copyFile(sourceFilePath, destinationFilePath)) {
return false;
}
if (!deleteFile(sourceFilePath)) {
return false;
}
return true;
}
QStringList MAIN::getListOfFilesInDirectory(const QString& directoryPath, bool includesubdir, bool includeDirs)
{
QDir directory(directoryPath);
QStringList fileList;
// Vérifier si le répertoire existe
if (!directory.exists()) {
qDebug() << "Le répertoire n'existe pas :" << directoryPath;
return QStringList();
}
QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QFileInfo& fileInfo, fileInfoList) {
if (fileInfo.isDir()) {
if (includesubdir) {
fileList.append(getListOfFilesInDirectory(fileInfo.absoluteFilePath(), true, includeDirs)); // appel récursif pour les sous-dossiers
}
if (includeDirs) {
fileList.append(fileInfo.absoluteFilePath()); // Ajoutez le dossier à la liste si includeDirs est true
}
} else {
fileList.append(fileInfo.absoluteFilePath()); // Ajoutez uniquement les fichiers à la liste
}
}
return fileList;
}
bool MAIN::Exit(int code) {
if(code==0){
qDebug() << "Olop est arrêté. À bientôt :) !";
}else {
qWarning() << "Un problème est survenu :(";
qWarning() << "Un crash report a du etre effectué";
}
exit(code);
}
bool MAIN::ReportCrash(int exitcode, QString log){
QString filename = "Crash du "+QDateTime::currentDateTime().toString("dddd dd MMMM yyyy hh:mm:ss.zzz");
QString filecontent = "Code de sortie: "+QString::number(exitcode)+"\nLog d'Olop:\n"+log;
QString filepath = MAIN::O_DIR+"Logs/";
QDir(filepath).mkdir(filepath);
MAIN::ecrireDansFichier(filepath+filename, filecontent);
return true;
}
APP::~APP(){
for (auto server : httpServers) {
delete server;
}
httpServers.clear();
}
QString APP::LIST(const QString& directoryPath)
{
QStringList fileList = MAIN::getListOfFilesInDirectory(directoryPath, false);
// Formater la liste des fichiers
QString formattedList;
QString builder;
for (const auto& filePath : fileList) {
QFile f(filePath);
builder += QStringLiteral("<a href='#' onclick=\"loadPAP('") % f.fileName() % "')\">" % decodeApp(MAIN::lireFichier(filePath))[1] % "</a><br>";
}
formattedList = builder;
return formattedList;
}
QStringList APP::decodeApp(const QString data) {
QStringList lignesSeparate = data.split('\n', Qt::SkipEmptyParts);
QStringList result;
QString nom;
QString version;
QString url;
QString developpeur;
QString type;
QString os;
QString description;
if (lignesSeparate.size() >= 6) {
nom = lignesSeparate[0];
version = lignesSeparate[1];
url = lignesSeparate[2];
developpeur = lignesSeparate[3];
type = lignesSeparate[4];
os = lignesSeparate[5];
// Si la description contient plusieurs lignes, les concaténer
if (lignesSeparate.size() > 6) {
description = lignesSeparate.mid(6).join("\n");
}
}
result << "Ceci est le .app de " + nom << nom << version << url << developpeur << type << os << description;
return result;
}
QStringList APP::decodeApp(const QByteArray data) {
return APP::decodeApp(QString::fromUtf8(data));
}
int APP::HTTPSERVER(QString dir){
QHttpServer* httpServer = new QHttpServer();
const auto port = httpServer->listen(QHostAddress::Any);
if (!port) {
qDebug() << QCoreApplication::translate("Olop", "Server failed to listen on a port.");
return 0;
}
QString URL = "";
httpServer->route("/jquery.js", [=](){
return QHttpServerResponse::fromFile(QStringLiteral(":/assets/jquery.js"));
});
httpServer->route("/setURL/<arg>", [&](QUrl Url){
URL = Url.toDisplayString();
return "OK";
});
httpServer->route("/<arg>", [=](QUrl Url) {
QByteArray fileData = MAIN::lireFichier(dir+"/"+Url.toDisplayString());
if (fileData.isEmpty()) {
QByteArray DOWN = NETWORK::Download(Url);
if (DOWN == "ERR") {
DOWN = NETWORK::Download(QUrl(QString(URL + Url.toDisplayString())));
}
if (!DOWN.isEmpty()) {
QMimeDatabase mimeDb;
QMimeType type = mimeDb.mimeTypeForFile(Url.toDisplayString()); // ou utilises filePath
return QHttpServerResponse(type.name().toUtf8(), DOWN);
}
} else {
QMimeDatabase mimeDb;
QMimeType type = mimeDb.mimeTypeForFile(Url.toDisplayString()); // ou utilises filePath
return QHttpServerResponse(type.name().toUtf8(), fileData);
}
// Gère l'erreur ou retourne une réponse par défaut si nécessaire
return QHttpServerResponse("text/plain", "Erreur ou contenu par défaut");
});
httpServer->route("/stop", [=]() {
QTimer::singleShot(300, httpServer, [httpServer]() {
httpServer->deleteLater();
});
return "Application arrêtée";
});
// Ajouter le nouveau serveur HTTP à la liste
httpServers.append(httpServer);
return port;
}
bool NETWORK::checkURLAccess(const QString& url) {
QNetworkAccessManager manager;
QNetworkRequest request(url);
QNetworkReply* reply = manager.get(request);
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() == QNetworkReply::NoError) {
return true; // L'URL est accessible
}
return false; // L'URL n'est pas accessible ou une erreur s'est produite
}
int NETWORK::findAvailablePort() {
QTcpServer server;
if(server.listen(QHostAddress::LocalHost, 0)) {
int port = server.serverPort();
server.close(); // Ferme le serveur et libère le port
return port;
}
return -1; // retourne -1 si aucun port n'est disponible, ce qui est peu probable
}
QByteArray NETWORK::Download(const QUrl Url) {
QNetworkAccessManager manager;
QNetworkReply* reply = manager.get(QNetworkRequest(Url));
QByteArray downloadedData;
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, [&]() {
if (reply->error() == QNetworkReply::NoError) {
downloadedData = reply->readAll();
qDebug() << "Taille des données téléchargées: " << downloadedData.size();
qWarning() << "Réponse du serveur : " << reply->readAll();
} else {
qWarning() << "Erreur lors du téléchargement : " << reply->errorString();
qWarning() << "Réponse du serveur : " << reply->readAll();
downloadedData = QByteArray("ERR");
}
loop.quit();
});
loop.exec();
return downloadedData;
}
#ifdef Q_OS_LINUX
int NETWORK::goalpha() {
if(MAIN::VERSION.indexOf("daily")){
qDebug() << "Préparation de la migration vers des releases...";
MAIN::VERSION="release";
}else {
qDebug() << "Préparation de la migration vers un daily build...";
MAIN::VERSION="daily";
}
return 0;
}
#endif
bool FILES::unZip(const QString &file, const QString &dest, std::function<void()> cleaningCallback) {
// Créer un dossier temporaire pour l'extraction
QString tempDirPath = QDir::tempPath() + "/tempExtractionFolder_" + QUuid::createUuid().toString();
QDir().mkdir(tempDirPath);
#ifdef Q_OS_WIN
QString program = "7z.exe";
QStringList arguments;
arguments << "x" << file << "-o" + tempDirPath << "-aoa";
#elif defined(Q_OS_LINUX)
QString program = "/usr/bin/unzip";
QStringList arguments;
arguments << "-o" << file << "-d" << tempDirPath;
#else
// Gérer les autres systèmes d'exploitation
return false;
#endif
QProcess unzip;
unzip.start(program, arguments);
unzip.waitForFinished();
// Affichez la sortie pour le dépannage
qDebug() << "Standard Output:" << unzip.readAllStandardOutput();
qDebug() << "Standard Error:" << unzip.readAllStandardError();
if (unzip.exitCode() != 0) {
return false;
}
// Copier les fichiers du dossier temporaire vers le dossier de destination
QStringList extractedFilesAndDirs = MAIN::getListOfFilesInDirectory(tempDirPath, true, true);
foreach (const QString &filePath, extractedFilesAndDirs) {
QString relativePath = QDir(tempDirPath).relativeFilePath(filePath);
if (QFileInfo(filePath).isDir()) {
QDir().mkdir(QDir(dest).absoluteFilePath(relativePath));
} else {
QFile::copy(filePath, QDir(dest).absoluteFilePath(relativePath));
}
}
// Supprimer le dossier temporaire après avoir copié les fichiers et dossiers
MAIN::supprimerDossier(tempDirPath);
QStringList preExtractionFilesAndDirs = MAIN::getListOfFilesInDirectory(dest, true, true);
if (cleaningCallback) {
cleaningCallback();
}
// Supprimez les fichiers et dossiers du répertoire de destination qui ne sont pas dans le zip
foreach (const QString& preFileOrDir, preExtractionFilesAndDirs) {
if (!extractedFilesAndDirs.contains(QDir(tempDirPath).absoluteFilePath(QDir(dest).relativeFilePath(preFileOrDir)))) {
if (QFileInfo(preFileOrDir).isDir()) {
QDir(preFileOrDir).removeRecursively();
} else {
QFile::remove(preFileOrDir);
}
}
}
return true;
}
QString FILES::getcurrentdir() {
return QDir::currentPath();;
}
int FILES::checkpermission(QString path){
QFileInfo fileInfo(path);
if(fileInfo.exists() && fileInfo.isDir())
{
if(fileInfo.isWritable())
{
return 0;
}
else
{
return -2;
}
}
else
{
return -1;
}
}
int FILES::gocurrentdirandcheckpermissions() {
return FILES::checkpermission(FILES::getcurrentdir());
}