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