Updated documentation preparing for refactoring
[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 <QDir>
14 #include "httpclient.h"
15 #include "mainwindow.h"
16
17 /**
18   *@brief Constructor, connects object to GUI
19   *@param Pointer to carmainwindow, which is temporarily used during development
20   */
21 HttpClient::HttpClient(MainWindow *myCarw)
22 {
23     qDebug() << "__HttpClient";
24     myMainw = myCarw;
25     netManager = new QNetworkAccessManager();
26     myXmlwriter = new XmlWriter();
27     myXmlreader = new XmlReader();
28 }
29
30 /**
31   *@brief Destructor
32   */
33 HttpClient::~HttpClient()
34 {
35     qDebug() << "__~HttpClient" ;
36
37     if(myXmlwriter)
38         delete myXmlwriter;
39     if(myXmlreader)
40         delete myXmlreader;
41 }
42
43 /**
44   *@brief Sends registration information to the server in xml format.
45   *Reads user name, password and emaol address from resuldialogs internal variables.
46   */
47 void HttpClient::requestRegistration()
48 {
49     qDebug() << "_requestRegistration" ;
50     qDebug() <<  myMainw->settingsDialog->getRegUserName() << "+" <<  myMainw->settingsDialog->getRegPassword() << "+" <<  myMainw->settingsDialog->getRegEmail();
51
52     QBuffer *regbuffer = new QBuffer();
53     QUrl qurl("http://api.speedfreak-app.com/api/register");
54     QNetworkRequest request(qurl);
55     qDebug() << qurl.toString();
56     QNetworkReply *currentDownload;
57
58     regbuffer->open(QBuffer::ReadWrite);
59     myXmlwriter->writeRegistering(regbuffer,
60                        myMainw->settingsDialog->getRegUserName(),
61                        myMainw->settingsDialog->getRegPassword(),
62                        myMainw->settingsDialog->getRegEmail());
63     qDebug() << "carmainwindow: regbuffer->data(): " << regbuffer->data();
64
65     currentDownload = netManager->post(request, ("xml=" + regbuffer->data()));
66     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfRegistration()));
67     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
68
69     //Indicating user
70     if(myMainw->settingsDialog)
71         myMainw->settingsDialog->setLabelInfoToUser("Reguesting registration from server");
72
73     regbuffer->close();
74 }
75
76 /**
77   *@brief Sends result(s) to the server in xml format.
78   *Send authentication information in the header.
79   */
80 void HttpClient::sendResultXml(QString category, double result)
81 {
82     qDebug() << "_sendResultXml";
83
84     QBuffer *xmlbuffer = new QBuffer();
85
86     QUrl qurl("http://api.speedfreak-app.com/api/update/" + category);
87     qDebug() << qurl.toString();
88     QNetworkRequest request(qurl);
89     QNetworkReply *currentDownload;
90
91     xmlbuffer->open(QBuffer::ReadWrite);
92     myXmlwriter->writeResult(xmlbuffer, result);
93     qDebug() << "carmainwindow: xmlbuffer->data(): " << xmlbuffer->data();
94
95     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
96     credentials = "Basic " + credentials.toAscii().toBase64();
97     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
98
99     currentDownload = netManager->post(request, ("xml=" + xmlbuffer->data()));
100     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfResult()));
101     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
102
103     //Indicating user
104     if(myMainw->accstart->accRealTimeDialog->resultDialog)
105         myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("Sending result to server");
106
107     xmlbuffer->close();
108 }
109
110 /**
111   * @brief Sends route to the server in xml format.
112   * Send authentication information in the header.
113   * @param QString filename
114   * @param int 1(send to server) or 0(no send)
115   * @todo Check destination URL.
116   */
117 void HttpClient::sendRouteXml(QString s, int i)
118 {
119     qDebug() << "_sendRouteXml";
120
121     QString filename = ".//speedfreak_route/route.xml";
122
123     if(s != "")
124     {
125         qDebug() << "_rename xml";
126         filename = s + ".xml";
127         QDir dir(filename);
128         qDebug() << dir.rename(".//speedfreak_route/route.xml", filename);
129     }
130
131     if(i == 1)
132     {
133         qDebug() << "_send route";
134         QFile file(filename);
135         if (!file.open(QFile::ReadOnly))
136         {
137             qDebug() << "_sendRouteXml file.open() fail";
138             return;
139         }
140
141         QUrl qurl("http://api.speedfreak-app.com/api/update/route");
142         qDebug() << qurl.toString();
143         QNetworkRequest request(qurl);
144         QNetworkReply *currentDownload;
145
146         QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
147         credentials = "Basic " + credentials.toAscii().toBase64();
148         request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
149
150         currentDownload = netManager->post(request, ("xml=" + file.readAll()));
151         connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfRoute()));
152         //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
153
154         //Indicating user
155         if(myMainw->routeSaveDialog->routeDialog)
156             myMainw->routeSaveDialog->routeDialog->setLabelInfoToUser("Sending route to server");
157
158         file.close();
159     }
160 }
161
162 /**
163   *@brief Request the Top10List of certain category from the server.
164   *Send authentication information in the header.
165   *@param Category of results.
166   *@param Limit, the number of results.
167   */
168 void HttpClient::requestTopList(QString category, QString limit)
169 {
170     qDebug() << "_requestTopList";
171     qDebug() << category;
172
173     QString urlBase = "http://api.speedfreak-app.com/api/results/";
174     QUrl qurl(urlBase + category + "/" + limit);
175     qDebug() << qurl.toString();
176     QNetworkRequest request(qurl);
177     QNetworkReply *currentDownload;
178
179     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
180     credentials = "Basic " + credentials.toAscii().toBase64();
181     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
182
183     currentDownload = netManager->post(request, ("data=" ));
184     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfToplist()));
185     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
186
187     //Indicating user
188     if(myMainw->topResultDialog)
189         myMainw->topResultDialog->setLabelInfoToUser("Reguesting top10 list from server");
190 }
191
192 /**
193   *@brief Request categories list from the server.
194   *Send authentication information in the header.
195   */
196 void HttpClient::requestCategories()
197 {
198     qDebug() << "_requestCategories" ;
199
200     QUrl qurl("http://api.speedfreak-app.com/api/categories/");
201     qDebug() << qurl.toString();
202     QNetworkRequest request(qurl);
203     QNetworkReply *currentDownload;
204
205     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
206     credentials = "Basic " + credentials.toAscii().toBase64();
207     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
208
209     currentDownload = netManager->post(request, ("data=" ));
210     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfCategories()));
211     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
212
213     //Indicating user
214     if(myMainw->topResultDialog)
215         myMainw->topResultDialog->setLabelInfoToUser("Reguesting categories from server");
216 }
217
218 /**
219   *@brief Check that username and password exist on the server.
220   *Send authentication information in the header.
221   */
222 void HttpClient::checkLogin()
223 {
224     qDebug() << "_checkLogin";
225
226     QUrl qurl("http://api.speedfreak-app.com/api/login/");
227     qDebug() << qurl.toString();
228     QNetworkRequest request(qurl);
229     QNetworkReply *currentDownload;
230
231     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
232     credentials = "Basic " + credentials.toAscii().toBase64();
233     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
234
235     currentDownload = netManager->post(request, ("data=" ));
236     connect(currentDownload,SIGNAL(finished()),this,SLOT(ackOfLogin()));
237     //connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),myMainw,SLOT(errorFromServer(QNetworkReply::NetworkError)));
238
239     //Indicating user
240     if(myMainw->settingsDialog)
241         myMainw->settingsDialog->setLabelInfoToUser("Checking login validity from server");
242 }
243
244 /**
245   *@brief React to servers responce after result has been sent.
246   */
247 void HttpClient::ackOfResult()
248 {
249     qDebug() << "_ackOfResult";
250
251     //Indicating user
252     if(myMainw->accstart->accRealTimeDialog->resultDialog)
253         myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("");
254
255     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
256
257     QNetworkReply::NetworkError errorcode;
258     errorcode = reply->error();
259     if(errorcode != 0) {
260         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
261
262         //Indicating user
263         if(myMainw->accstart->accRealTimeDialog->resultDialog)
264             QMessageBox::about(myMainw->accstart->accRealTimeDialog->resultDialog, "Server reply to result sending ",reply->errorString());
265         if(myMainw->accstart->accRealTimeDialog->resultDialog)
266             myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("Error");
267         if(myMainw->accstart->accRealTimeDialog->resultDialog)
268             myMainw->accstart->accRealTimeDialog->resultDialog->setSendServerButtonEnabled();
269     }
270     else {
271         qDebug() << "errorcode:" << errorcode << reply->errorString();
272
273         //Indicating user
274         if(myMainw->accstart->accRealTimeDialog->resultDialog)
275             QMessageBox::about(myMainw->accstart->accRealTimeDialog->resultDialog, "Server reply to result sending", "Result received " + reply->readAll());
276         if(myMainw->accstart->accRealTimeDialog->resultDialog)
277             myMainw->accstart->accRealTimeDialog->resultDialog->setLabelInfoToUser("Result received");
278     }
279 }
280
281 /**
282   *@brief React to servers responce after route has been sent.
283   */
284 void HttpClient::ackOfRoute()
285 {
286     qDebug() << "_ackOfRoute";
287
288     if(myMainw->routeSaveDialog->routeDialog)
289         myMainw->routeSaveDialog->routeDialog->setLabelInfoToUser("");
290
291     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
292
293     QNetworkReply::NetworkError errorcode;
294     errorcode = reply->error();
295     if(errorcode != 0) {
296         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
297         if(myMainw->routeSaveDialog->routeDialog)
298             QMessageBox::about(myMainw->routeSaveDialog->routeDialog, "Server reply to route sending ",reply->errorString());
299         if(myMainw->routeSaveDialog->routeDialog)
300             myMainw->routeSaveDialog->routeDialog->setSendServerButtonEnabled();
301     }
302     else {
303         qDebug() << "errorcode:" << errorcode << reply->errorString();
304         if(myMainw->routeSaveDialog->routeDialog)
305             QMessageBox::about(myMainw->routeSaveDialog->routeDialog, "Server reply to route sending", "Route received " + reply->readAll());
306     }
307 }
308
309 /**
310   *@brief React to servers responce after registration has been sent.
311   *@todo Implement consequencies of reply.
312   */
313 void HttpClient::ackOfRegistration()
314 {
315     qDebug() << "_ackOfRegistration";
316
317     if(myMainw->settingsDialog)
318         myMainw->settingsDialog->setLabelInfoToUser("");
319
320     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
321
322     QNetworkReply::NetworkError errorcode;
323     errorcode = reply->error();
324     if(errorcode != 0) {
325         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
326         if(myMainw->settingsDialog)
327             QMessageBox::about(myMainw->settingsDialog, "Server reply to registration",reply->readAll());
328     }
329     else {
330         qDebug() << "errorcode=0" << errorcode << reply->errorString();
331         if(myMainw->settingsDialog)
332         {
333             QMessageBox::about(myMainw->settingsDialog, "Server reply to registration", "User registration " + reply->readAll());
334             myMainw->settingsDialog->clearRegisterLineEdits();
335         }
336     }
337 }
338
339 /**
340   *@brief React to servers responce after request for categories has been sent.
341   */
342 void HttpClient::ackOfCategories()
343 {
344     qDebug() << "_ackOfCategories";
345
346     if(myMainw->topResultDialog)
347         myMainw->topResultDialog->setLabelInfoToUser("");
348
349     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
350     myXmlreader->xmlReadCategories(reply);
351
352     QNetworkReply::NetworkError errorcode;
353     errorcode = reply->error();
354     if(errorcode != 0) {
355         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
356         //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting categories",reply->errorString());
357         if(myMainw->topResultDialog)
358             myMainw->topResultDialog->setLabelInfoToUser("You're not logged! Please register or log in.");
359     }
360     else {
361         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
362         //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting categories ", "OK");
363         if(myMainw->topResultDialog)
364             myMainw->topResultDialog->setLabelInfoToUser("");
365     }
366 }
367
368 /**
369   *@brief React to servers responce after request of TopList in certain category has been sent.
370   */
371 void HttpClient::ackOfLogin()
372 {
373     qDebug() << "_ackOffLogin";
374
375     if(myMainw->settingsDialog)
376         myMainw->settingsDialog->setLabelInfoToUser("");
377
378     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
379
380     QNetworkReply::NetworkError errorcode;
381     errorcode = reply->error();
382     if(errorcode != 0) 
383     {
384         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
385         if(myMainw->settingsDialog)
386         {
387                 QMessageBox::about(myMainw->settingsDialog, "Server does not recognize your username. Please registrate.",reply->errorString());
388                 myMainw->settingsDialog->usernameOk(false);
389         }
390     }
391     else 
392     {
393         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
394         if(myMainw->settingsDialog)
395                 QMessageBox::about(myMainw->settingsDialog, "Server reply to login", "User login " + reply->readAll());
396         // here signal emit to mainwindow for username setting to main panel
397         emit loginOK();
398         if( myMainw->settingsDialog)
399         {
400                 myMainw->settingsDialog->usernameOk(true);
401                 myMainw->settingsDialog->close();    
402         }
403     }
404 }
405
406 /**
407   *@brief Reports errors, when server has sent error signal.
408   */
409 void HttpClient::errorFromServer(QNetworkReply::NetworkError errorcode)
410 {
411     qDebug() << "_errorFromServer";
412     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
413
414     if(errorcode != 0) {
415         qDebug() <<  "errorcode:" << errorcode;
416         //Note that errors are already reported on other each functions for server communication
417         //QMessageBox::about(myMainw, "Server reported an error", reply->errorString());
418     }
419     else {
420         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
421         qDebug() << reply->readAll();
422     }
423 }
424
425 /**
426   *@brief React to servers responce after request of TopList in certain category has been sent.
427   */
428 void HttpClient::ackOfToplist()
429 {
430     qDebug() << "_ackOfToplist";
431     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
432     myXmlreader->xmlReadTop10Results(reply,myMainw->settingsDialog->getUserName());
433
434     QNetworkReply::NetworkError errorcode;
435     errorcode = reply->error();
436     if(errorcode != 0) {
437         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
438         //Indicating user
439         if(myMainw->topResultDialog)
440         {
441             //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting top 10 list",reply->errorString());
442             myMainw->topResultDialog->setLabelInfoToUser("No results ;(");
443         }
444     }
445     else {
446         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
447         //Indicating user
448         if(myMainw->topResultDialog)
449         {
450             //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting top 10 list", "OK " + reply->readAll());
451             myMainw->topResultDialog->setLabelInfoToUser("");
452         }
453     }
454 }
455
456 /**
457   * This function sends profile to the server in xml format.
458   * Send authentication information in the header.
459   */
460 void HttpClient::sendProfileXml()
461 {
462     qDebug() << "_sendProfileXml";
463
464     QString userName = myMainw->settingsDialog->getUserName();
465     QString filename = userName + "_profile.xml";
466     QFile file(filename);
467     if (!file.open(QFile::ReadWrite | QFile::Text))
468     {
469         qDebug() << "_xmlWrite fail";
470         return;
471     }
472     myXmlwriter->writeProfileXmlFile(&file, userName,
473             myMainw->settingsDialog->profileDialog->getManufacturer(),
474             myMainw->settingsDialog->profileDialog->getType(),
475             myMainw->settingsDialog->profileDialog->getModel(),
476             myMainw->settingsDialog->profileDialog->getDescription(),
477             myMainw->settingsDialog->profileDialog->getPicture());
478
479     //Indicating user
480     if(myMainw->settingsDialog->profileDialog)
481         myMainw->settingsDialog->profileDialog->setLabelInfoToUser("Profile saved to phone");
482
483     // Send xml to server
484     /*QUrl qurl("http://api.speedfreak-app.com/api/profile");
485     QNetworkRequest request(qurl);
486     qDebug() << qurl.toString();
487     QNetworkReply *currentDownload;
488
489     QString credentials = myMainw->settingsDialog->getUserName() + ":" + myMainw->settingsDialog->getPassword();
490     credentials = "Basic " + credentials.toAscii().toBase64();
491     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
492
493     currentDownload = netManager->post(request, ("xml=" + file.readAll()));
494     bool error = connect(currentDownload, SIGNAL(finished()), this, SLOT(ackOfProfile()));*/
495
496     file.close();
497
498     // Send picture to server
499     /*if(myMainw->settingsDialog->profileDialog->getPicture() != "" && error == false)
500     {
501         QFile pictureFile( myMainw->settingsDialog->profileDialog->getPicture() );
502         if (!pictureFile.open(QIODevice::ReadOnly))
503         {
504             qDebug() << "__picture read fail";
505             return;
506         }
507         currentDownload = netManager->post(request, pictureFile.readAll());
508         connect(currentDownload, SIGNAL(finished()), this, SLOT(ackOfSendingPicture()));
509         pictureFile.close();
510     }*/
511 }
512
513 /**
514   * This slot function react to servers responce after request of profile has been sent.
515   */
516 bool HttpClient::ackOfProfile()
517 {
518     qDebug() << "__ackOfProfile";
519     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
520     QNetworkReply::NetworkError errorcode;
521     errorcode = reply->error();
522     if(errorcode != 0) {
523         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
524         //Indicating user
525         if(myMainw->settingsDialog->profileDialog)
526         {
527             //QMessageBox::about(myMainw->settingsDialog->profileDialog, "Server reply to requesting profile",reply->errorString());
528             myMainw->settingsDialog->profileDialog->setLabelInfoToUser("Profile save to server - fail");
529             return true;
530         }
531     }
532     else {
533         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
534         //Indicating user
535         if(myMainw->settingsDialog->profileDialog)
536         {
537             //QMessageBox::about(myMainw->settingsDialog->profileDialog, "Server reply to requesting profile", "OK " + reply->readAll());
538             myMainw->settingsDialog->profileDialog->setLabelInfoToUser("Profile saved to server");
539             return false;
540         }
541     }
542 }
543 /**
544   * This slot function react to servers responce after request of picture has been sent.
545   */
546 void HttpClient::ackOfSendingPicture()
547 {
548     qDebug() << "__ackOfSendingPicture";
549     QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
550     QNetworkReply::NetworkError errorcode;
551     errorcode = reply->error();
552     if(errorcode != 0) {
553         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
554         //Indicating user
555         if(myMainw->settingsDialog->profileDialog)
556         {
557             //QMessageBox::about(myMainw->settingsDialog->profileDialog, "Server reply to requesting picture",reply->errorString());
558             myMainw->settingsDialog->profileDialog->setLabelInfoToUser("Picture save to server - fail");
559         }
560     }
561     else {
562         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
563         //Indicating user
564         if(myMainw->settingsDialog->profileDialog)
565         {
566             //QMessageBox::about(myMainw->settingsDialog->profileDialog, "Server reply to requesting picture", "OK " + reply->readAll());
567             myMainw->settingsDialog->profileDialog->setLabelInfoToUser("Picture saved to server");
568         }
569     }
570 }