class MyServer public QObject Q_OBJECT public explicit MyServer int po

 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
class MyServer: public QObject {
Q_OBJECT
public:
explicit MyServer(int port, QString password, QByteArray templateData, QByteArray bg = "") {
server = new QWebSocketServer("TDM Server", QWebSocketServer::NonSecureMode, this);
server->listen(QHostAddress::Any, port);
this->templateData = templateData;
this->password = password;
if (bg != "") {
this->bg = true;
this->background = bg;
}
connect(server, SIGNAL(newConnection()), this, SLOT(clientConnected()));
}
~MyServer() {}
private:
QWebSocketServer* server;
QByteArray templateData;
bool bg;
QByteArray background;
QString password;
private slots:
void clientConnected() {
QWebSocket* clientSocket = server->nextPendingConnection();
connect(clientSocket, SIGNAL(textMessageReceived(QString)), this, SLOT(slotReadClient(QString)));
}
void slotReadClient(QString message) {
QWebSocket* clientSocket = (QWebSocket*) sender();
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
auto command = doc.object()["command"].toString();
auto pass = doc.object()["password"].toString();
if (pass != password) {
clientSocket->sendTextMessage("{success:false,error:\"Wrong password\"}");
return;
}
if (command == "get-background" && bg) {
clientSocket->sendBinaryMessage(background);
} else if (command == "get-background" && !bg) {
clientSocket->sendTextMessage("{success:false,error:\"No background.\"}");
}
if (command == "get-template") {
clientSocket->sendBinaryMessage(templateData);
}
if (command == "update") {
auto count = doc.object()["count"].toInt();
QString answer;
QJsonDocument json;
QJsonObject obj;
obj["success"] = QJsonValue(true);
obj["count"] = QJsonValue(count);
for (int i = 0; i < count; i++) {
auto execute = doc.object()["execute" + QString::number(i)].toString();
QProcess* process = new QProcess();
process->start("/bin/bash", QStringList() << "-c" << "echo $(" + execute + ")");
process->waitForFinished(1000);
auto value = process->readAll().trimmed();
obj["execute" + QString::number(i)] = QJsonValue(value.toStdString().c_str());
}
json.setObject(obj);
answer = json.toJson();
clientSocket->sendTextMessage(answer);
}
if (command == "execute") {
auto execute = doc.object()["execute"].toString();
QProcess* process = new QProcess();
process->start("/bin/bash", QStringList() << "-c" << execute);
}
}
};