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