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