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