cacic_comm.cpp
10.1 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
#include "cacic_comm.h"
CacicComm::CacicComm ()
{
}
CacicComm::CacicComm (const QString &urlGerente, const QString &operatingSystem, const QString &computerSystem, const QString &csCipher,
const QString &csDebug, const QString &csCompress, const QString &httpUserAgent, const QString &moduleFolderName,
const QString &moduleProgramName, const QString &networkConfiguration,const QString &phpAuthPw, const QString &phpAuthUser,
const QString &so, const QString &cacicVersion, const QString &gercolsVersion)
{
this->setUrlGerente(urlGerente);
params.addQueryItem("OperatingSystem", operatingSystem);
params.addQueryItem("ComputerSystem",computerSystem);
params.addQueryItem("cs_cipher",csCipher);
params.addQueryItem("cs_debug",csDebug);
params.addQueryItem("cs_compress",csCompress);
params.addQueryItem("HTTP_USER_AGENT",httpUserAgent);
params.addQueryItem("ModuleFolderName",moduleFolderName);
params.addQueryItem("ModuleProgramName",moduleProgramName);
params.addQueryItem("NetworkAdapterConfiguration",networkConfiguration);
params.addQueryItem("PHP_AUTH_PW",phpAuthPw);
params.addQueryItem("PHP_AUTH_USER",phpAuthUser);
params.addQueryItem("te_so",so);
params.addQueryItem("te_versao_cacic",cacicVersion);
params.addQueryItem("te_versao_gercols",gercolsVersion);
}
QJsonObject CacicComm::comm(QString route, bool *ok, const QJsonObject &json, bool isSsl)
{
*ok = false;
QByteArray data;
QNetworkRequest req;
QUrl url;
QString strReply;
QJsonObject jsonObj;
if (isSsl){
url = urlSsl.isEmpty() ? "https://" + this->urlGerente + route : this->urlSsl + route;
if (!url.isValid()){
jsonObj["error"] = QVariant("Invalid Url").toJsonValue();
return jsonObj;
}
req.setSslConfiguration(QSslConfiguration::defaultConfiguration());
} else
url = "http://" + this->urlGerente + route;
req.setUrl(url);
req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
if (json.empty()){
//se não for passado QJson, será mandado os valores do get/test antigo. (Será retirado depois)
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
data.append(params.toString());
} else {
// Add JSON
QJsonDocument d(json);
data.append(d.toJson());
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
}
QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
QNetworkReply *reply = mgr.post(req, data);
if (!reply->sslConfiguration().isNull()){
reply->ignoreSslErrors();
}
eventLoop.exec(); // sai do looping chamando o "finished()".
jsonObj.insert("codestatus", QJsonValue::fromVariant(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()));
if (reply->error() == QNetworkReply::NoError) {
//se não houver erro, grava o retorno;
QVariant replyVariant = reply->readAll();
QJsonDocument replyDocument = QJsonDocument::fromJson(replyVariant.toByteArray());
jsonObj["reply"] = (!replyDocument.isNull()) ?
replyDocument.object() :
QJsonValue::fromVariant(replyVariant.toString());
*ok = true;
delete reply;
} else {
strReply = reply->errorString();
jsonObj.insert("error", QJsonValue::fromVariant(strReply));
delete reply;
}
return jsonObj;
}
/* commStatus
* execulta um teste do tipo GET na urlGerente;
* @return retorna o resultado da conexão HTTP:
* exemplo: 200 OK
*/
bool CacicComm::commStatus(){
// cria um event-loop temporario
QEventLoop eventLoop;
// "quit()" o event-loop, when the network request "finished()"
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
// a requisição HTTP
QUrl url = "http://" + urlGerente;
QNetworkRequest req( url );
req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // sai do looping chamando o "finished()".
QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
if (reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).isValid()){
// qDebug() << "Status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reason;
return true;
}else{
reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
// qDebug() << "Error:" << reason;
return false;
}
}
/* login
* realiza login com usuario e senha
* @return retorna json com sessão e chave de criptografia
*/
QJsonObject CacicComm::login(bool *ok) {
*ok = false;
// Cria dados de login
QVariantMap login;
login["user"] = this->usuario;
login["password"] = this->password;
// Cria conexão e retorna Json da sessão
QJsonObject retorno = this->comm("/ws/neo/getLogin", ok, QJsonObject::fromVariantMap(login), true);
if (*ok)
this->session = retorno["reply"].toObject()["session"].toString();
return retorno;
}
/* fileDownload( QString path )
*
* Faz o download de um arquivo usando o protocolo mode
* a partir da url do gerente e do caminho até o arquivo.
*/
bool CacicComm::fileDownload(const QString &mode, const QString &path, const QString &pathDownload){
QEventLoop eventLoop;
QNetworkAccessManager manager;
QNetworkRequest request;
QNetworkReply *reply;
QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloadFinished(QNetworkReply*)) );
QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()) );
QStringList splitPath = path.split("/");
fileHandler = new QFile(pathDownload + splitPath[splitPath.size() - 1]);
if( !fileHandler->open(QIODevice::WriteOnly) ) {
qDebug() << "fileDownload: fileHandler nâo pode abrir arquivo.";
return false;
}
QUrl url(urlGerente);
url.setScheme(mode);
url.setPath(path);
if (!this->ftpUser.isEmpty())
url.setUserName(ftpUser);
if (!this->ftpPass.isEmpty())
url.setPassword(ftpPass);
request.setUrl(url);
reply = manager.get(request);
eventLoop.exec();
delete fileHandler;
delete reply;
return true;
}
/* fileDownload( QString urlServer, QString path )
*
* Faz o download de um arquivo usando o protocolo mode
* a partir da url recebida e do caminho até o arquivo.
*/
bool CacicComm::fileDownload(const QString &mode, const QString &urlServer, const QString &path, const QString &pathDownload){
QEventLoop eventLoop;
QNetworkAccessManager manager;
QNetworkRequest request;
QNetworkReply *reply;
QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloadFinished(QNetworkReply*)) );
QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()) );
QStringList splitPath = path.split("/");
fileHandler = new QFile((!pathDownload.isEmpty() ? pathDownload + "/" : "") + splitPath[splitPath.size() - 1]);
if( !fileHandler->open(QIODevice::WriteOnly) ) {
qDebug() << "ftpDownload: fileHandler nâo pode abrir arquivo.";
}
QUrl url(mode + "://" + (urlServer.endsWith("/") ? urlServer : urlServer + "/") + path);
// url.setScheme(mode);
// url.setUrl(urlServer);
// url.setPath(path);
if (!this->ftpUser.isEmpty())
url.setUserName(ftpUser);
if (!this->ftpPass.isEmpty())
url.setPassword(ftpPass);
request.setUrl(url);
reply = manager.get(request);
eventLoop.exec();
delete fileHandler;
delete reply;
return true;
}
void CacicComm::fileDownloadFinished(QNetworkReply* reply)
{
if (reply->size() > 0){
QTextStream out(fileHandler);
out << reply->readAll();
fileHandler->setPermissions(QFileDevice::ExeOwner |
QFileDevice::WriteOwner |
QFileDevice::ReadOwner |
QFileDevice::ExeUser);
// qDebug() << fileHandler->permissions();
fileHandler->close();
reply->close();
} else
qDebug() << "Falha ao baixar arquivo :" << reply->errorString();
}
QString CacicComm::getFtpPass() const
{
return ftpPass;
}
void CacicComm::setFtpPass(const QString &value)
{
ftpPass = value;
}
QString CacicComm::getFtpUser() const
{
return ftpUser;
}
void CacicComm::setFtpUser(const QString &value)
{
ftpUser = value;
}
bool CacicComm::ftpDownload( const QString &path, const QString &pathDownload ){
return fileDownload("ftp", path, pathDownload);
}
bool CacicComm::ftpDownload( const QString &urlServer, const QString &path, const QString &pathDownload ){
return fileDownload("ftp", urlServer, path, pathDownload);
}
bool CacicComm::httpDownload( const QString &path, const QString &pathDownload ){
return fileDownload("http", path, pathDownload);
}
bool CacicComm::httpDownload( const QString &urlServer, const QString &path,const QString &pathDownload ){
return fileDownload("http", urlServer, path, pathDownload);
}
QString CacicComm::getUrlSsl (){
return this->urlSsl;
}
void CacicComm::setUrlSsl(const QString &value){
this->urlSsl = value;
}
QString CacicComm::getUrlGerente (){
return this->urlGerente;
}
void CacicComm::setUrlGerente(QString value){
if (value.contains("://", Qt::CaseInsensitive)){
value = value.mid(value.indexOf("://") + 3);
}
if (value.endsWith("/")){
value.remove(value.size()-1, 1);
}
this->urlGerente = value;
}
QString CacicComm::getPassword()
{
return this->password;
}
void CacicComm::setPassword(const QString &value)
{
this->password = value;
}
QString CacicComm::getUsuario()
{
return this->usuario;
}
void CacicComm::setUsuario(const QString &value)
{
this->usuario = value;
}