Commit cb33ac1f3ebc8011fe178439eb93e2a8230457d1

Authored by Thiago Rocha
1 parent 61632edb
Exists in master

Métodos de download de arquivos por ftp e http terminados.

cacic-daemon/cacicD/cacicD.pro
... ... @@ -24,6 +24,7 @@ TEMPLATE = app
24 24 SOURCES += main.cpp \
25 25 cacicd.cpp \
26 26 cacictimer.cpp \
  27 + ../../src/cacic_comm.cpp \
27 28 ../../src/ccacic.cpp \
28 29 ../../src/wmi.cpp \
29 30 ../../src/cacic_computer.cpp \
... ...
cacic-teste/cacic-teste.pro
... ... @@ -23,6 +23,7 @@ SOURCES += \
23 23 testcacic.cpp \
24 24 ../src/ccacic.cpp \
25 25 ../src/cacic_computer.cpp \
  26 + ../src/cacic_comm.cpp \
26 27 ../src/operatingsystem.cpp \
27 28 ../src/cacic_software.cpp \
28 29 ../src/cacic_hardware.cpp \
... ...
cacic-teste/testcacic.cpp
... ... @@ -323,9 +323,9 @@ void CTestCacic::testFtpDownload()
323 323 OCacicComm->ftpDownload("ftp://ftp.unicamp.br", "/pub/gnu/Licenses/gpl-2.0.txt");
324 324 QFile downloaded("gpl-2.0.txt");
325 325  
326   - QVERIFY( !downloaded.open(QIODevice::ReadOnly) &&
327   - downloaded.exists() &&
328   - downloaded.readAll() != "" );
  326 + QVERIFY( downloaded.open(QIODevice::ReadOnly) );
  327 + QVERIFY( downloaded.exists() );
  328 + QVERIFY( downloaded.readAll() != "" );
329 329 }
330 330  
331 331 void CTestCacic::cleanupTestCase()
... ...
src/cacic_comm.cpp 0 → 100644
... ... @@ -0,0 +1,273 @@
  1 +#include "cacic_comm.h"
  2 +
  3 +CacicComm::CacicComm ()
  4 +{
  5 +}
  6 +
  7 +CacicComm::CacicComm (QString urlGerente, QString operatingSystem, QString computerSystem, QString csCipher,
  8 + QString csDebug, QString csCompress, QString httpUserAgent, QString moduleFolderName,
  9 + QString moduleProgramName, QString networkConfiguration,QString phpAuthPw, QString phpAuthUser,
  10 + QString so, QString cacicVersion, QString gercolsVersion)
  11 +{
  12 + this->setUrlGerente(urlGerente);
  13 + params.addQueryItem("OperatingSystem", operatingSystem);
  14 + params.addQueryItem("ComputerSystem",computerSystem);
  15 + params.addQueryItem("cs_cipher",csCipher);
  16 + params.addQueryItem("cs_debug",csDebug);
  17 + params.addQueryItem("cs_compress",csCompress);
  18 + params.addQueryItem("HTTP_USER_AGENT",httpUserAgent);
  19 + params.addQueryItem("ModuleFolderName",moduleFolderName);
  20 + params.addQueryItem("ModuleProgramName",moduleProgramName);
  21 + params.addQueryItem("NetworkAdapterConfiguration",networkConfiguration);
  22 + params.addQueryItem("PHP_AUTH_PW",phpAuthPw);
  23 + params.addQueryItem("PHP_AUTH_USER",phpAuthUser);
  24 + params.addQueryItem("te_so",so);
  25 + params.addQueryItem("te_versao_cacic",cacicVersion);
  26 + params.addQueryItem("te_versao_gercols",gercolsVersion);
  27 +
  28 +
  29 +}
  30 +
  31 +QJsonObject CacicComm::comm(QString route, bool *ok, const QJsonObject &json, bool isSsl)
  32 +{
  33 + *ok = false;
  34 + QByteArray data;
  35 + QNetworkRequest req;
  36 + QUrl url;
  37 + QString strReply;
  38 + QJsonObject jsonObj;
  39 + if (isSsl){
  40 + url = urlSsl.isEmpty() ? "https://" + this->urlGerente + route : this->urlSsl + route;
  41 + if (!url.isValid()){
  42 + jsonObj["error"] = QVariant("Invalid Url").toJsonValue();
  43 + return jsonObj;
  44 + }
  45 + req.setSslConfiguration(QSslConfiguration::defaultConfiguration());
  46 + } else
  47 + url = "http://" + urlGerente + route;
  48 + req.setUrl(url);
  49 + req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
  50 + if (json.empty()){
  51 + //se não for passado QJson, será mandado os valores do get/test antigo. (Será retirado depois)
  52 + req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
  53 + data.append(params.toString());
  54 + } else {
  55 + // Add JSON
  56 + QJsonDocument d(json);
  57 + data.append(d.toJson());
  58 + req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  59 + }
  60 + QEventLoop eventLoop;
  61 + QNetworkAccessManager mgr;
  62 + QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
  63 +
  64 + QNetworkReply *reply = mgr.post(req, data);
  65 + if (!reply->sslConfiguration().isNull()){
  66 + reply->ignoreSslErrors();
  67 + }
  68 + eventLoop.exec(); // sai do looping chamando o "finished()".
  69 +
  70 + jsonObj.insert("codestatus", QJsonValue::fromVariant(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)));
  71 +
  72 + if (reply->error() == QNetworkReply::NoError) {
  73 + //se não houver erro, grava o retorno;
  74 + QVariant replyVariant = reply->readAll();
  75 + QJsonDocument replyDocument = QJsonDocument::fromJson(replyVariant.toByteArray());
  76 + jsonObj["reply"] = (!replyDocument.isNull()) ?
  77 + replyDocument.object() :
  78 + QJsonValue::fromVariant(replyVariant.toString());
  79 + *ok = true;
  80 + delete reply;
  81 + } else {
  82 + strReply = reply->errorString();
  83 + jsonObj.insert("error", QJsonValue::fromVariant(strReply));
  84 + delete reply;
  85 + }
  86 + return jsonObj;
  87 +}
  88 +
  89 +
  90 +/* commStatus
  91 + * execulta um teste do tipo GET na urlGerente;
  92 + * @return retorna o resultado da conexão HTTP:
  93 + * exemplo: 200 OK
  94 + */
  95 +bool CacicComm::commStatus(){
  96 + // cria um event-loop temporario
  97 + QEventLoop eventLoop;
  98 + // "quit()" o event-loop, when the network request "finished()"
  99 + QNetworkAccessManager mgr;
  100 + QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
  101 + // a requisição HTTP
  102 + QUrl url = "http://" + urlGerente;
  103 + QNetworkRequest req( url );
  104 + req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
  105 + QNetworkReply *reply = mgr.get(req);
  106 + eventLoop.exec(); // sai do looping chamando o "finished()".
  107 +
  108 + QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
  109 + if (reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).isValid()){
  110 +// qDebug() << "Status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reason;
  111 + return true;
  112 + }else{
  113 + reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
  114 +// qDebug() << "Error:" << reason;
  115 + return false;
  116 + }
  117 +}
  118 +
  119 +/* login
  120 + * realiza login com usuario e senha
  121 + * @return retorna json com sessão e chave de criptografia
  122 + */
  123 +QJsonObject CacicComm::login(bool *ok) {
  124 + *ok = false;
  125 + // Cria dados de login
  126 + QVariantMap login;
  127 + login["user"] = this->usuario;
  128 + login["password"] = this->password;
  129 + // Cria conexão e retorna Json da sessão
  130 + QJsonObject retorno = this->comm("/ws/neo/getLogin", ok, QJsonObject::fromVariantMap(login), true);
  131 + if (*ok)
  132 + this->session = retorno["reply"].toObject()["session"].toString();
  133 + return retorno;
  134 +}
  135 +
  136 +/* fileDownload( QString path )
  137 + *
  138 + * Faz o download de um arquivo usando o protocolo mode
  139 + * a partir da url do gerente e do caminho até o arquivo.
  140 + */
  141 +bool CacicComm::fileDownload(const QString &mode, const QString &path){
  142 + QEventLoop eventLoop;
  143 + QNetworkAccessManager manager;
  144 + QNetworkRequest request;
  145 + QNetworkReply *reply;
  146 +
  147 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloadFinished(QNetworkReply*)) );
  148 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()) );
  149 +
  150 + QStringList splitPath = path.split("/");
  151 +
  152 + fileHandler = new QFile(splitPath[splitPath.size() - 1]);
  153 + if( !fileHandler->open(QIODevice::WriteOnly) ) {
  154 + qDebug() << "ftpDownload: fileHandler nâo pode abrir arquivo.";
  155 + return false;
  156 + }
  157 +
  158 + QUrl url(urlGerente);
  159 + url.setScheme(mode);
  160 + url.setPath(path);
  161 + request.setUrl(url);
  162 +
  163 + reply = manager.get(request);
  164 +
  165 + eventLoop.exec();
  166 +
  167 + delete fileHandler;
  168 + delete reply;
  169 +
  170 + return true;
  171 +}
  172 +
  173 +/* fileDownload( QString urlServer, QString path )
  174 + *
  175 + * Faz o download de um arquivo usando o protocolo mode
  176 + * a partir da url recebida e do caminho até o arquivo.
  177 + */
  178 +bool CacicComm::fileDownload(const QString &mode, const QString &urlServer, const QString &path){
  179 + QEventLoop eventLoop;
  180 + QNetworkAccessManager manager;
  181 + QNetworkRequest request;
  182 + QNetworkReply *reply;
  183 +
  184 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloadFinished(QNetworkReply*)) );
  185 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()) );
  186 +
  187 + QStringList splitPath = path.split("/");
  188 +
  189 + fileHandler = new QFile(splitPath[splitPath.size() - 1]);
  190 + if( !fileHandler->open(QIODevice::WriteOnly) ) {
  191 + qDebug() << "ftpDownload: fileHandler nâo pode abrir arquivo.";
  192 + return false;
  193 + }
  194 +
  195 + QUrl url(urlServer);
  196 + url.setScheme(mode);
  197 + url.setPath(path);
  198 + request.setUrl(url);
  199 +
  200 + reply = manager.get(request);
  201 +
  202 + eventLoop.exec();
  203 +
  204 + delete fileHandler;
  205 + delete reply;
  206 +
  207 + return true;
  208 +}
  209 +
  210 +bool CacicComm::ftpDownload( const QString &path ){
  211 + return fileDownload("ftp", path);
  212 +}
  213 +
  214 +bool CacicComm::ftpDownload( const QString &urlServer, const QString &path ){
  215 + return fileDownload("ftp", urlServer, path);
  216 +}
  217 +
  218 +bool CacicComm::httpDownload( const QString &path ){
  219 + return fileDownload("http", path);
  220 +}
  221 +
  222 +bool CacicComm::httpDownload( const QString &urlServer, const QString &path ){
  223 + return fileDownload("http", urlServer, path);
  224 +}
  225 +
  226 +QString CacicComm::getUrlSsl (){
  227 + return this->urlSsl;
  228 +}
  229 +
  230 +void CacicComm::setUrlSsl(QString value){
  231 + this->urlSsl = value;
  232 +}
  233 +
  234 +QString CacicComm::getUrlGerente (){
  235 + return this->urlGerente;
  236 +}
  237 +
  238 +void CacicComm::setUrlGerente(QString value){
  239 + if (value.contains("://", Qt::CaseInsensitive)){
  240 + value = value.mid(value.indexOf("://") + 3);
  241 + }
  242 + if (value.endsWith("/")){
  243 + value.remove(value.size()-1, 1);
  244 + }
  245 + this->urlGerente = value;
  246 +}
  247 +
  248 +QString CacicComm::getPassword()
  249 +{
  250 + return this->password;
  251 +}
  252 +
  253 +void CacicComm::setPassword(QString value)
  254 +{
  255 + this->password = value;
  256 +}
  257 +QString CacicComm::getUsuario()
  258 +{
  259 + return this->usuario;
  260 +}
  261 +
  262 +void CacicComm::setUsuario(QString value)
  263 +{
  264 + this->usuario = value;
  265 +}
  266 +
  267 +void CacicComm::fileDownloadFinished(QNetworkReply* reply)
  268 +{
  269 + QTextStream out(fileHandler);
  270 + out << reply->readAll();
  271 + fileHandler->close();
  272 + reply->close();
  273 +}
... ...
src/cacic_comm.h
... ... @@ -16,240 +16,52 @@
16 16 class CacicComm : public QObject{
17 17  
18 18 Q_OBJECT
19   -private:
20   - QFile *fileHandler;
21   - QUrlQuery params;
22   - QString urlGerente;
23   - QString urlSsl;
24   - QString usuario;
25   - QString password;
26   - QString session;
27 19  
28 20 public:
29   - CacicComm (){
30   - }
31 21  
  22 + CacicComm ();
32 23 CacicComm (QString urlGerente, QString operatingSystem, QString computerSystem, QString csCipher,
33 24 QString csDebug, QString csCompress, QString httpUserAgent, QString moduleFolderName,
34 25 QString moduleProgramName, QString networkConfiguration,QString phpAuthPw, QString phpAuthUser,
35   - QString so, QString cacicVersion, QString gercolsVersion)
36   - {
37   - this->setUrlGerente(urlGerente);
38   - params.addQueryItem("OperatingSystem", operatingSystem);
39   - params.addQueryItem("ComputerSystem",computerSystem);
40   - params.addQueryItem("cs_cipher",csCipher);
41   - params.addQueryItem("cs_debug",csDebug);
42   - params.addQueryItem("cs_compress",csCompress);
43   - params.addQueryItem("HTTP_USER_AGENT",httpUserAgent);
44   - params.addQueryItem("ModuleFolderName",moduleFolderName);
45   - params.addQueryItem("ModuleProgramName",moduleProgramName);
46   - params.addQueryItem("NetworkAdapterConfiguration",networkConfiguration);
47   - params.addQueryItem("PHP_AUTH_PW",phpAuthPw);
48   - params.addQueryItem("PHP_AUTH_USER",phpAuthUser);
49   - params.addQueryItem("te_so",so);
50   - params.addQueryItem("te_versao_cacic",cacicVersion);
51   - params.addQueryItem("te_versao_gercols",gercolsVersion);
52   -
53   -
54   - }
55   -
56   - QJsonObject comm(QString route, bool *ok, const QJsonObject &json = QJsonObject(), bool isSsl = false)
57   - {
58   - *ok = false;
59   - QByteArray data;
60   - QNetworkRequest req;
61   - QUrl url;
62   - QString strReply;
63   - QJsonObject jsonObj;
64   - if (isSsl){
65   - url = urlSsl.isEmpty() ? "https://" + this->urlGerente + route : this->urlSsl + route;
66   - if (!url.isValid()){
67   - jsonObj["error"] = QVariant("Invalid Url").toJsonValue();
68   - return jsonObj;
69   - }
70   - req.setSslConfiguration(QSslConfiguration::defaultConfiguration());
71   - } else
72   - url = "http://" + urlGerente + route;
73   - req.setUrl(url);
74   - req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
75   - if (json.empty()){
76   - //se não for passado QJson, será mandado os valores do get/test antigo. (Será retirado depois)
77   - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
78   - data.append(params.toString());
79   - } else {
80   - // Add JSON
81   - QJsonDocument d(json);
82   - data.append(d.toJson());
83   - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
84   - }
85   - QEventLoop eventLoop;
86   - QNetworkAccessManager mgr;
87   - QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
88   -
89   - QNetworkReply *reply = mgr.post(req, data);
90   - if (!reply->sslConfiguration().isNull()){
91   - reply->ignoreSslErrors();
92   - }
93   - eventLoop.exec(); // sai do looping chamando o "finished()".
94   -
95   - jsonObj.insert("codestatus", QJsonValue::fromVariant(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)));
96   -
97   - if (reply->error() == QNetworkReply::NoError) {
98   - //se não houver erro, grava o retorno;
99   - QVariant replyVariant = reply->readAll();
100   - QJsonDocument replyDocument = QJsonDocument::fromJson(replyVariant.toByteArray());
101   - jsonObj["reply"] = (!replyDocument.isNull()) ?
102   - replyDocument.object() :
103   - QJsonValue::fromVariant(replyVariant.toString());
104   - *ok = true;
105   - delete reply;
106   - } else {
107   - strReply = reply->errorString();
108   - jsonObj.insert("error", QJsonValue::fromVariant(strReply));
109   - delete reply;
110   - }
111   - return jsonObj;
112   - }
113   -
114   -
115   - /* commStatus
116   - * execulta um teste do tipo GET na urlGerente;
117   - * @return retorna o resultado da conexão HTTP:
118   - * exemplo: 200 OK
119   - */
120   - bool commStatus(){
121   - // cria um event-loop temporario
122   - QEventLoop eventLoop;
123   - // "quit()" o event-loop, when the network request "finished()"
124   - QNetworkAccessManager mgr;
125   - QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
126   - // a requisição HTTP
127   - QUrl url = "http://" + urlGerente;
128   - QNetworkRequest req( url );
129   - req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
130   - QNetworkReply *reply = mgr.get(req);
131   - eventLoop.exec(); // sai do looping chamando o "finished()".
132   -
133   - QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
134   - if (reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).isValid()){
135   -// qDebug() << "Status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reason;
136   - return true;
137   - }else{
138   - reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
139   -// qDebug() << "Error:" << reason;
140   - return false;
141   - }
142   - }
143   -
144   - /* login
145   - * realiza login com usuario e senha
146   - * @return retorna json com sessão e chave de criptografia
147   - */
148   - QJsonObject login(bool *ok) {
149   - *ok = false;
150   - // Cria dados de login
151   - QVariantMap login;
152   - login["user"] = this->usuario;
153   - login["password"] = this->password;
154   - // Cria conexão e retorna Json da sessão
155   - QJsonObject retorno = this->comm("/ws/neo/getLogin", ok, QJsonObject::fromVariantMap(login), true);
156   - if (*ok)
157   - this->session = retorno["reply"].toObject()["session"].toString();
158   - return retorno;
159   - }
160   -
161   - bool ftpDownload(QString path){
162   - QUrl url(urlGerente);
163   - url.setScheme("ftp");
164   - url.setPath(path);
165   -
166   - return false;
167   - }
168   -
169   - bool ftpDownload(QString urlServer, QString path){
170   - QNetworkAccessManager manager;
171   - QNetworkRequest req;
172   - QNetworkReply *reply;
  26 + QString so, QString cacicVersion, QString gercolsVersion);
  27 + QJsonObject comm(QString route, bool *ok, const QJsonObject &json = QJsonObject(), bool isSsl = false);
  28 + bool commStatus();
  29 + QJsonObject login(bool *ok);
  30 + bool ftpDownload(const QString &path);
  31 + bool ftpDownload(const QString &urlServer, const QString &path);
  32 + bool httpDownload(const QString &path);
  33 + bool httpDownload(const QString &urlServer, const QString &path);
  34 + QString getUrlSsl ();
  35 + void setUrlSsl(QString value);
  36 + QString getUrlGerente ();
  37 + void setUrlGerente(QString value);
  38 + QString getPassword();
  39 + void setPassword(QString value);
  40 + QString getUsuario();
  41 + void setUsuario(QString value);
173 42  
174   - QStringList splitPath = path.split("/");
175 43  
176   - fileHandler = new QFile(splitPath[splitPath.size() - 1]);
177   - if( !fileHandler->open(QIODevice::WriteOnly) ) {
178   - return false;
179   - }
180 44  
181   - QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ftpDownloadFinished(QNetworkReply*)) );
182   -// QObject::connect(reply, SIGNAL(finished()), this, SIGNAL(finished(reply)) );
183   -// QObject::connect(this, SIGNAL(finished(reply)), this, SLOT(ftpDownloadFinished(reply)) );
184   -
185   - QUrl url(urlServer);
186   - url.setScheme("ftp");
187   - url.setPath(path);
188   - req.setUrl(url);
189   -
190   - reply = manager.get(req);
191   -
192   - return true;
193   - }
194   -
195   - bool httpDownload( QString urlServer, QString path ){
196   - return false;
197   - }
198   -
199   - QString getUrlSsl (){
200   - return this->urlSsl;
201   - }
202   -
203   - void setUrlSsl(QString value){
204   - this->urlSsl = value;
205   - }
206   -
207   - QString getUrlGerente (){
208   - return this->urlGerente;
209   - }
210   -
211   - void setUrlGerente(QString value){
212   - if (value.contains("://", Qt::CaseInsensitive)){
213   - value = value.mid(value.indexOf("://") + 3);
214   - }
215   - if (value.endsWith("/")){
216   - value.remove(value.size()-1, 1);
217   - }
218   - this->urlGerente = value;
219   - }
220   -
221   - QString getPassword()
222   - {
223   - return this->password;
224   - }
  45 +signals:
  46 +// void finished(QNetworkReply* reply);
225 47  
226   - void setPassword(QString value)
227   - {
228   - this->password = value;
229   - }
230   - QString getUsuario()
231   - {
232   - return this->usuario;
233   - }
  48 +private slots:
234 49  
235   - void setUsuario(QString value)
236   - {
237   - this->usuario = value;
238   - }
  50 + void fileDownloadFinished(QNetworkReply* reply);
239 51  
  52 +private:
240 53  
241   -signals:
242   - void finished(QNetworkReply* reply);
  54 + bool fileDownload(const QString &mode, const QString &path);
  55 + bool fileDownload(const QString &mode, const QString &urlServer, const QString &path);
243 56  
244   -private slots:
  57 + QUrlQuery params;
  58 + QString urlGerente;
  59 + QString urlSsl;
  60 + QString usuario;
  61 + QString password;
  62 + QString session;
245 63  
246   - void ftpDownloadFinished(QNetworkReply* reply)
247   - {
248   - qDebug() << "Entrou no SLOT.";
  64 + QFile *fileHandler;
249 65  
250   - QTextStream out(fileHandler);
251   - out << reply->readAll();
252   - fileHandler->close();
253   - }
254 66 };
255 67 #endif // CACIC_COMM_H
... ...