Route and Results buttons updated.
[speedfreak] / Client / httpclient.cpp
1 /*
2  * Http client Connects application to server.
3  *
4  * @author      Tiina Kivilinna-Korhola <tiina.kivilinna-korhola@fudeco.com>
5  * @author      Olavi Pulkkinen <olavi.pulkkinen@fudeco.com>
6  * @author      Toni Jussila    <toni.jussila@fudeco.com>
7  * @copyright   (c) 2010 Speed Freak team
8  * @license     http://opensource.org/licenses/gpl-license.php GNU Public License
9  */
10
11 #include <QString>
12 #include <QMessageBox>
13 #include "httpclient.h"
14 #include "mainwindow.h"
15
16 /**
17   *@brief Constructor, connects object to GUI
18   *@param Pointer to carmainwindow, which is temporarily used during development
19   */
20 HttpClient::HttpClient(MainWindow *myCarw)
21 {
22     qDebug() << "__HttpClient";
23     myMainw = myCarw;
24     netManager = new QNetworkAccessManager();
25     myXmlwriter = new XmlWriter();
26     myXmlreader = new XmlReader();
27 }
28
29 /**
30   *@brief Destructor
31   */
32 HttpClient::~HttpClient()
33 {
34     qDebug() << "__~HttpClient" ;
35 }
36
37 /**
38   *@brief Sends registration information to the server in xml format.
39   *Reads user name, password and emaol address from resuldialogs internal variables.
40   */
41 void HttpClient::requestRegistration()
42 {
43     qDebug() << "_requestRegistration" ;
44     qDebug() <<  myMainw->settingsDialog->getRegUserName() << "+" <<  myMainw->settingsDialog->getRegPassword() << "+" <<  myMainw->settingsDialog->getRegEmail();
45
46     QBuffer *regbuffer = new QBuffer();
47     QUrl qurl("http://api.speedfreak-app.com/api/register");
48     QNetworkRequest request(qurl);
49     qDebug() << qurl.toString();
50     QNetworkReply *currentDownload;
51
52     regbuffer->open(QBuffer::ReadWrite);
53     myXmlwriter->writeRegistering(regbuffer,
54                        myMainw->settingsDialog->getRegUserName(),
55                        myMainw->settingsDialog->getRegPassword(),
56                        myMainw->settingsDialog->getRegEmail());
57     qDebug() << "carmainwindow: regbuffer->data(): " << regbuffer->data();
58
59     currentDownload = netManager->post(request, ("xml=" + regbuffer->data()));
60     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfRegistration()));
61     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
62
63     //Indicating user
64     if(myMainw->settingsDialog)
65         myMainw->settingsDialog->setLabelInfoToUser("Reguesting registration from server");
66
67     regbuffer->close();
68 }
69
70 /**
71   *@brief Sends result(s) to the server in xml format.
72   *Send authentication information in the header.
73   */
74 void HttpClient::sendResultXml(QString category, double result)
75 {
76     qDebug() << "_sendResultXml";
77
78     QBuffer *xmlbuffer = new QBuffer();
79
80     QUrl qurl("http://api.speedfreak-app.com/api/update/" + category);
81     qDebug() << qurl.toString();
82     QNetworkRequest request(qurl);
83     QNetworkReply *currentDownload;
84
85     xmlbuffer->open(QBuffer::ReadWrite);
86     myXmlwriter->writeResult(xmlbuffer, result);
87     qDebug() << "carmainwindow: xmlbuffer->data(): " << xmlbuffer->data();
88
89     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
90     credentials = "Basic " + credentials.toAscii().toBase64();
91     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
92
93     currentDownload = netManager->post(request, ("xml=" + xmlbuffer->data()));
94     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfResult()));
95     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
96
97     //Indicating user
98     if(myMainw->accstart->accRealTimeDialog->resultDialog)
99         myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("Sending result to server");
100
101     xmlbuffer->close();
102 }
103
104 /**
105   *@brief Sends route to the server in xml format.
106   *Send authentication information in the header.
107   *@todo Check destination URL.
108   */
109 void HttpClient::sendRouteXml()
110 {
111     qDebug() << "_sendRouteXml";
112
113     QString filename = "route.xml";
114     QFile file(filename);
115     if (!file.open(QFile::ReadOnly)) {
116         qDebug() << "_sendRouteXml file.open() fail";
117         return;
118     }
119
120     QUrl qurl("http://api.speedfreak-app.com/api/update/route");
121     qDebug() << qurl.toString();
122     QNetworkRequest request(qurl);
123     QNetworkReply *currentDownload;
124
125     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
126     credentials = "Basic " + credentials.toAscii().toBase64();
127     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
128
129     currentDownload = netManager->post(request, ("xml=" + file.readAll()));
130     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfRoute()));
131     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
132
133     //Indicating user
134     if(myMainw->routeSaveDialog->routeDialog)
135         myMainw->routeSaveDialog->routeDialog->setLabelInfoToUser("Sending route to server");
136
137     file.close();
138 }
139
140 /**
141   *@brief Request the Top10List of certain category from the server.
142   *Send authentication information in the header.
143   *@param Category of results.
144   *@param Limit, the number of results.
145   */
146 void HttpClient::requestTopList(QString category, QString limit)
147 {
148     qDebug() << "_requestTopList" ;
149
150     QString urlBase = "http://api.speedfreak-app.com/api/results/";
151     QUrl qurl(urlBase + category + "/" + limit);
152     qDebug() << qurl.toString();
153     QNetworkRequest request(qurl);
154     QNetworkReply *currentDownload;
155
156     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
157     credentials = "Basic " + credentials.toAscii().toBase64();
158     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
159
160     currentDownload = netManager->post(request, ("data=" ));
161     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfToplist()));
162     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
163
164     //Indicating user
165     if(myMainw->topResultDialog)
166         myMainw->topResultDialog->setLabelInfoToUser("Reguesting top10 list from server");
167 }
168
169 /**
170   *@brief Request categories list from the server.
171   *Send authentication information in the header.
172   */
173 void HttpClient::requestCategories()
174 {
175     qDebug() << "_requestCategories" ;
176
177     QUrl qurl("http://api.speedfreak-app.com/api/categories/");
178     qDebug() << qurl.toString();
179     QNetworkRequest request(qurl);
180     QNetworkReply *currentDownload;
181
182     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
183     credentials = "Basic " + credentials.toAscii().toBase64();
184     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
185
186     currentDownload = netManager->post(request, ("data=" ));
187     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfCategories()));
188     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
189
190     //Indicating user
191     if(myMainw->topResultDialog)
192         myMainw->topResultDialog->setLabelInfoToUser("Reguesting categories from server");
193 }
194
195 /**
196   *@brief Check that username and password exist on the server.
197   *Send authentication information in the header.
198   */
199 void HttpClient::checkLogin()
200 {
201     qDebug() << "_checkLogin";
202
203     QUrl qurl("http://api.speedfreak-app.com/api/login/");
204     qDebug() << qurl.toString();
205     QNetworkRequest request(qurl);
206     QNetworkReply *currentDownload;
207
208     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
209     credentials = "Basic " + credentials.toAscii().toBase64();
210     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
211
212     currentDownload = netManager->post(request, ("data=" ));
213     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfLogin()));
214     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
215
216     //Indicating user
217     if(myMainw->settingsDialog)
218         myMainw->settingsDialog->setLabelInfoToUser("Checking login validity from server");
219 }
220
221 /**
222   *@brief React to servers responce after result has been sent.
223   */
224 void HttpClient::ackOfResult()
225 {
226     qDebug() << "_ackOfResult";
227
228     //Indicating user
229     if(myMainw->accstart->accRealTimeDialog->resultDialog)
230         myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("");
231
232     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
233
234     QNetworkReply::NetworkError errorcode;
235     errorcode = reply->error();
236     if(errorcode != 0) {
237         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
238
239         //Indicating user
240         if(myMainw->accstart->accRealTimeDialog->resultDialog)
241             QMessageBox::about(myMainw->accstart->accRealTimeDialog->resultDialog, "Server reply to result sending ",reply->errorString());
242         if(myMainw->accstart->accRealTimeDialog->resultDialog)
243             myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("Error");
244         if(myMainw->accstart->accRealTimeDialog->resultDialog)
245             myMainw->accstart->accRealTimeDialog->resultDialog->setSendServerButtonEnabled();
246     }
247     else {
248         qDebug() << "errorcode:" << errorcode << reply->errorString();
249
250         //Indicating user
251         if(myMainw->accstart->accRealTimeDialog->resultDialog)
252             QMessageBox::about(myMainw->accstart->accRealTimeDialog->resultDialog, "Server reply to result sending", "Result received " + reply->readAll());
253         if(myMainw->accstart->accRealTimeDialog->resultDialog)
254             myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("Result received");
255     }
256 }
257
258 /**
259   *@brief React to servers responce after route has been sent.
260   */
261 void HttpClient::ackOfRoute()
262 {
263     qDebug() << "_ackOfRoute";
264
265     if(myMainw->routeSaveDialog->routeDialog)
266         myMainw->routeSaveDialog->routeDialog->setLabelInfoToUser("");
267
268     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
269
270     QNetworkReply::NetworkError errorcode;
271     errorcode = reply->error();
272     if(errorcode != 0) {
273         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
274         if(myMainw->routeSaveDialog->routeDialog)
275             QMessageBox::about(myMainw->routeSaveDialog->routeDialog, "Server reply to route sending ",reply->errorString());
276         if(myMainw->routeSaveDialog->routeDialog)
277             myMainw->routeSaveDialog->routeDialog->setSendServerButtonEnabled();
278     }
279     else {
280         qDebug() << "errorcode:" << errorcode << reply->errorString();
281         if(myMainw->routeSaveDialog->routeDialog)
282             QMessageBox::about(myMainw->routeSaveDialog->routeDialog, "Server reply to route sending", "Route received " + reply->readAll());
283     }
284 }
285
286 /**
287   *@brief React to servers responce after registration has been sent.
288   *@todo Implement consequencies of reply.
289   */
290 void HttpClient::ackOfRegistration()
291 {
292     qDebug() << "_ackOfRegistration";
293
294     if(myMainw->settingsDialog)
295         myMainw->settingsDialog->setLabelInfoToUser("");
296
297     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
298
299     QNetworkReply::NetworkError errorcode;
300     errorcode = reply->error();
301     if(errorcode != 0) {
302         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
303         if(myMainw->settingsDialog)
304             QMessageBox::about(myMainw->settingsDialog, "Server reply to registration",reply->readAll());
305     }
306     else {
307         qDebug() << "errorcode=0" << errorcode << reply->errorString();
308         if(myMainw->settingsDialog)
309         {
310             QMessageBox::about(myMainw->settingsDialog, "Server reply to registration", "User registration " + reply->readAll());
311             myMainw->settingsDialog->clearRegisterLineEdits();
312         }
313     }
314 }
315
316 /**
317   *@brief React to servers responce after request for categories has been sent.
318   */
319 void HttpClient::ackOfCategories()
320 {
321     qDebug() << "_ackOfCategories";
322
323     if(myMainw->topResultDialog)
324         myMainw->topResultDialog->setLabelInfoToUser("");
325
326     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
327     myXmlreader->xmlReadCategories(reply);
328
329     QNetworkReply::NetworkError errorcode;
330     errorcode = reply->error();
331     if(errorcode != 0) {
332         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
333         //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting categories",reply->errorString());
334         if(myMainw->topResultDialog)
335             myMainw->topResultDialog->setLabelInfoToUser("You're not logged! Please register or log in.");
336     }
337     else {
338         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
339         //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting categories ", "OK");
340         if(myMainw->topResultDialog)
341             myMainw->topResultDialog->setLabelInfoToUser("");
342     }
343 }
344
345 /**
346   *@brief React to servers responce after request of TopList in certain category has been sent.
347   */
348 void HttpClient::ackOfLogin()
349 {
350     qDebug() << "_ackOffLogin";
351
352     if(myMainw->settingsDialog)
353         myMainw->settingsDialog->setLabelInfoToUser("");
354
355     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
356
357     QNetworkReply::NetworkError errorcode;
358     errorcode = reply->error();
359     if(errorcode != 0) 
360     {
361         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
362         if(myMainw->settingsDialog)
363         {
364                 QMessageBox::about(myMainw->settingsDialog, "Server does not recognize your username. Please registrate.",reply->errorString());
365                 myMainw->settingsDialog->usernameOk(false);
366         }
367     }
368     else 
369     {
370         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
371         if(myMainw->settingsDialog)
372                 QMessageBox::about(myMainw->settingsDialog, "Server reply to login", "User login " + reply->readAll());
373         // here signal emit to mainwindow for username setting to main panel
374         emit loginOK();
375         if( myMainw->settingsDialog)
376         {
377                 myMainw->settingsDialog->usernameOk(true);
378                 myMainw->settingsDialog->close();    
379         }
380
381     }
382 }
383
384 /**
385   *@brief Reports errors, when server has sent error signal.
386   */
387 void HttpClient::errorFromServer(QNetworkReply::NetworkError errorcode)
388 {
389     qDebug() << "_errorFromServer";
390     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
391
392     if(errorcode != 0) {
393         qDebug() <<  "errorcode:" << errorcode;
394         //Note that errors are already reported on other each functions for server communication
395         //QMessageBox::about(myMainw, "Server reported an error", reply->errorString());
396     }
397     else {
398         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
399         qDebug() << reply->readAll();
400     }
401 }
402
403 /**
404   *@brief React to servers responce after request of TopList in certain category has been sent.
405   */
406 void HttpClient::ackOfToplist()
407 {
408     qDebug() << "_ackOfToplist";
409     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
410     myXmlreader->xmlReadTop10Results(reply);
411
412     QNetworkReply::NetworkError errorcode;
413     errorcode = reply->error();
414     if(errorcode != 0) {
415         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
416         //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting top 10 list",reply->errorString());
417         if(myMainw->topResultDialog)
418             myMainw->topResultDialog->setLabelInfoToUser("Error");
419     }
420     else {
421         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
422         //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting top 10 list", "OK " + reply->readAll());
423         if(myMainw->topResultDialog)
424             myMainw->topResultDialog->setLabelInfoToUser("");
425     }
426 }