cleaning
[situare] / src / situareservice / situareservice.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5       Henri Lampela - henri.lampela@ixonos.com
6
7    Situare is free software; you can redistribute it and/or
8    modify it under the terms of the GNU General Public License
9    version 2 as published by the Free Software Foundation.
10
11    Situare is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with Situare; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
19    USA.
20 */
21
22 #include <QtAlgorithms>
23 #include <QDebug>
24 #include <QtGlobal>
25 #include <QStringList>
26 #include <QPixmap>
27 #include <QNetworkReply>
28 #include "situareservice.h"
29 #include "situarecommon.h"
30 #include "parser.h"
31 #include "ui/avatarimage.h"
32
33 SituareService::SituareService(QObject *parent)
34         : QObject(parent),
35         m_user(0)
36 {
37     qDebug() << __PRETTY_FUNCTION__;
38
39     m_networkManager = new QNetworkAccessManager;
40     connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));
41
42     m_imageFetcher = new ImageFetcher(new QNetworkAccessManager(this), this);
43     connect(this, SIGNAL(fetchImage(QUrl)), m_imageFetcher, SLOT(fetchImage(QUrl)));
44     connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)), this,
45             SLOT(imageReceived(QUrl, QPixmap)));
46     connect(m_imageFetcher, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
47 }
48
49 SituareService::~SituareService()
50 {
51     qDebug() << __PRETTY_FUNCTION__;
52
53     delete m_networkManager;
54     m_networkManager = 0;
55     if(m_user) {
56         delete m_user;
57         m_user = 0;
58     }
59     delete m_imageFetcher;
60     m_imageFetcher = 0;
61
62     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
63     m_friendsList.clear();
64 }
65
66 void SituareService::fetchLocations()
67 {
68     qDebug() << __PRETTY_FUNCTION__;
69
70     QString cookie = formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
71                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
72                                 m_credentials.sig(), EN_LOCALE);
73
74     QUrl url = formUrl(SITUARE_URL, GET_LOCATIONS);
75     sendRequest(url, COOKIE, cookie);
76 }
77
78 void SituareService::reverseGeo(const QPointF &coordinates)
79 {
80     qDebug() << __PRETTY_FUNCTION__;
81
82     QString cookie = formCookie(API_KEY, m_credentials.expires(),m_credentials.userID(),
83                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
84                                 m_credentials.sig(), EN_LOCALE);
85
86     QString urlParameters = formUrlParameters(coordinates);
87     QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
88
89     sendRequest(url, COOKIE, cookie);
90 }
91
92 void SituareService::updateLocation(const QPointF &coordinates, const QString &status,
93                                     const bool &publish)
94 {
95     qDebug() << __PRETTY_FUNCTION__;
96
97     QString cookie = formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
98                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
99                                 m_credentials.sig(), EN_LOCALE);
100
101
102     QString publishValue;
103     if(publish) {
104         publishValue = PUBLISH_TRUE;
105     }
106     else {
107         publishValue = PUBLISH_FALSE;
108     }
109     QString urlParameters = formUrlParameters(coordinates, status, publishValue);
110     QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
111
112     sendRequest(url, COOKIE, cookie);
113 }
114
115 QString SituareService::formCookie(const QString &apiKeyValue, QString expiresValue,
116                                    QString userValue, QString sessionKeyValue,
117                                    QString sessionSecretValue, const QString &signatureValue,
118                                    const QString &localeValue)
119 {
120     qDebug() << __PRETTY_FUNCTION__;
121
122     QString cookie;
123     QString apiKey;
124     QString user;
125     QString expires;
126     QString sessionKey;
127     QString sessionSecret;
128     QString locale;
129     QString variable;
130     QString signature = EQUAL_MARK;
131     QStringList variableList;
132
133     signature.append(signatureValue);
134     apiKey.append(apiKeyValue);
135     apiKey.append(UNDERLINE_MARK);
136
137     user.append(USER);
138     user.append(EQUAL_MARK);
139     expires.append(EXPIRES);
140     expires.append(EQUAL_MARK);
141     sessionKey.append(SESSION_KEY);
142     sessionKey.append(EQUAL_MARK);
143     sessionSecret.append(SESSION_SECRET);
144     sessionSecret.append(EQUAL_MARK);
145     locale.append(LOCALE);
146     locale.append(EQUAL_MARK);
147     locale.append(localeValue);
148
149     variableList.append(expires.append(expiresValue.append(BREAK_MARK)));
150     variableList.append(sessionKey.append(sessionKeyValue.append(BREAK_MARK)));
151     variableList.append(user.append(userValue).append(BREAK_MARK));
152     variableList.append(sessionSecret.append(sessionSecretValue.append(BREAK_MARK)));
153
154     cookie.append(BREAK_MARK);
155
156     foreach(variable, variableList) {
157         cookie.append(apiKey);
158         cookie.append(variable);
159     }
160     apiKey.remove(UNDERLINE_MARK);
161     cookie.append(apiKey);
162     cookie.append(signature);
163     cookie.append(BREAK_MARK);
164     cookie.append(locale);
165
166     qDebug() << cookie;
167
168     return cookie;
169 }
170
171 QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript,
172                              QString urlParameters)
173 {
174     qDebug() << __PRETTY_FUNCTION__;
175     QString urlString;
176
177     urlString.append(baseUrl);
178     urlString.append(phpScript);
179     if(!urlParameters.isEmpty())
180         urlString.append(urlParameters);
181
182     QUrl url = QUrl(urlString);
183
184     qDebug() << url;
185
186     return url;
187 }
188
189 QString SituareService::formUrlParameters(const QPointF &coordinates, QString status,
190                                           QString publish)
191 {
192     QString parameters;
193
194     parameters.append(QUESTION_MARK);
195     parameters.append(LATITUDE);
196     parameters.append(EQUAL_MARK);
197     parameters.append(QString::number(coordinates.y()));
198     parameters.append(AMBERSAND_MARK);
199     parameters.append(LONGTITUDE);
200     parameters.append(EQUAL_MARK);
201     parameters.append(QString::number(coordinates.x()));
202
203     if(publish.compare(PUBLISH_TRUE) == 0) {
204         parameters.append(AMBERSAND_MARK);
205         parameters.append(PUBLISH);
206         parameters.append(EQUAL_MARK);
207         parameters.append(PUBLISH_TRUE);
208     }
209     else if(publish.compare(PUBLISH_FALSE) == 0) {
210         parameters.append(AMBERSAND_MARK);
211         parameters.append(PUBLISH);
212         parameters.append(EQUAL_MARK);
213         parameters.append(PUBLISH_FALSE);
214     }
215
216     if(!status.isEmpty()) {
217         parameters.append(AMBERSAND_MARK);
218         parameters.append(DATA);
219         parameters.append(EQUAL_MARK);
220         parameters.append(status);
221     }
222
223     return parameters;
224 }
225
226 void SituareService::sendRequest(const QUrl &url, const QString &cookieType, const QString &cookie)
227 {
228     qDebug() << __PRETTY_FUNCTION__ << "url: " << url;
229
230     QNetworkRequest request;
231
232     request.setUrl(url);
233     request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
234
235     QNetworkReply *reply = m_networkManager->get(request);
236
237     m_currentRequests.append(reply);
238 }
239
240 void SituareService::requestFinished(QNetworkReply *reply)
241 {
242     qDebug() << __PRETTY_FUNCTION__;
243
244     QUrl url = reply->url();
245     qDebug() << "BytesAvailable: " << reply->bytesAvailable();
246     if (reply->error()) {
247         qDebug() << reply->errorString();
248         emit error(reply->errorString());
249     }
250     else {
251         qint64 max = reply->size();
252         QByteArray replyArray = reply->read(max);
253         qDebug() << "Reply from: " << url << "reply " << replyArray;
254         // ToDo: results handling includes Situare's errors
255         // works like situare's error handling i.e. both lat & lon are missing/wrong
256         // -> we get only error for wrong lon
257         if(replyArray == ERROR_LAT.toAscii()) {
258             qDebug() << "Error: " << ERROR_LAT;
259             emit error(replyArray);
260         }
261         else if(replyArray == ERROR_LON.toAscii()) {
262             qDebug() << "Error: " << ERROR_LON;
263             emit error(replyArray);
264         }
265         else if(replyArray.contains(ERROR_SESSION.toAscii())) {
266             qDebug() << "Error: " << ERROR_SESSION;
267             emit invalidSessionCredentials();
268         }
269         else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
270             qDebug() << "JSON string";
271             parseUserData(replyArray);
272         }
273         else if(replyArray == "") {
274                         if(url.toString().contains(UPDATE_LOCATION.toAscii())) {
275                 emit updateWasSuccessful();
276             }
277             else {
278                 // session credentials are invalid
279                 emit invalidSessionCredentials();
280             }
281         }
282         else {
283             // Street address ready
284             QString address = QString::fromUtf8(replyArray);
285             emit reverseGeoReady(address);
286         }
287     }
288     m_currentRequests.removeAll(reply);
289     reply->deleteLater();
290 }
291
292 void SituareService::credentialsReady(const FacebookCredentials &credentials)
293 {
294     qDebug() << __PRETTY_FUNCTION__;
295
296     m_credentials = credentials;    
297 }
298
299 void SituareService::parseUserData(const QByteArray &jsonReply)
300 {
301     qDebug() << __PRETTY_FUNCTION__;
302
303     m_visited = 0;
304     m_nbrOfImages = 0;
305     m_defaultImage = false;
306     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
307     m_friendsList.clear();
308
309     if(m_user) {
310         delete m_user;
311         m_user = 0;
312     }
313
314     QJson::Parser parser;
315     bool ok;
316
317     QVariantMap result = parser.parse (jsonReply, &ok).toMap();
318     if (!ok) {
319
320         qFatal("An error occurred during parsing");
321         exit (1);
322     }
323
324     QVariant userVariant = result.value("user");
325     QMap<QString, QVariant> userMap = userVariant.toMap();
326
327     QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
328
329     QUrl imageUrl = userMap["profile_pic"].toUrl();
330     QUrl imageUrlBig = userMap["pic_big"].toUrl();
331
332     if(imageUrl.isEmpty()) {
333         // user doesn't have profile image, so we need to get him a silhouette image
334         m_defaultImage = true;
335     }
336
337     m_user = new User(userMap["address"].toString(), coordinates, userMap["name"].toString(),
338                   userMap["note"].toString(), imageUrl, imageUrlBig, userMap["timestamp"].toString(),
339                   true, userMap["uid"].toString());
340
341     foreach (QVariant friendsVariant, result["friends"].toList()) {
342       QMap<QString, QVariant> friendMap = friendsVariant.toMap();
343       QVariant distance = friendMap["distance"];
344       QMap<QString, QVariant> distanceMap = distance.toMap();
345
346       QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
347
348       QUrl imageUrl = friendMap["profile_pic"].toUrl();
349       QUrl imageUrlBig = friendMap["pic_big"].toUrl();
350
351       if(imageUrl.isEmpty()) {
352           // friend doesn't have profile image, so we need to get him a silhouette image
353           m_defaultImage = true;
354       }
355
356       User *user = new User(friendMap["address"].toString(), coordinates,
357                             friendMap["name"].toString(),
358                             friendMap["note"].toString(), imageUrl, imageUrlBig,
359                             friendMap["timestamp"].toString(),
360                             false, friendMap["uid"].toString(),
361                             distanceMap["units"].toString(),
362                             distanceMap["value"].toDouble());
363
364       m_friendsList.append(user);
365     }
366     addProfileImages();
367 }
368
369 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
370 {
371     qDebug() << __PRETTY_FUNCTION__;
372     qDebug() << "Image URL: " << url << " size :" << image.size();
373
374     // assign facebook silhouette image to all who doesn't have a profile image
375     if(url == QUrl(SILHOUETTE_URL)) {
376         if(m_user->profileImageUrl().isEmpty()) {
377             m_user->setProfileImage(AvatarImage::create(image));
378         }
379         for(int i=0;i < m_friendsList.count();i++) {
380             if(m_friendsList.at(i)->profileImageUrl().isEmpty()) {
381                 m_friendsList.at(i)->setProfileImage(AvatarImage::create(image));
382             }
383         }
384     }
385
386     if(m_user->profileImageUrl() == url) {
387         m_user->setProfileImage(AvatarImage::create(image));
388     }
389
390     if(m_user->profileImageUrlBig() == url) {
391         m_user->setProfileImageBig(AvatarImage::create(image));
392     }
393
394     for(int i=0;i<m_friendsList.count();i++) {
395         if(m_friendsList.at(i)->profileImageUrl() == url) {
396             m_friendsList.at(i)->setProfileImage(AvatarImage::create(image));
397             m_nbrOfImages++; // indicates how many friend profile images has been downloaded
398         }
399     }
400
401     if(m_nbrOfImages == m_visited) {
402         qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
403         qDebug() << "emit userDataChanged";
404         emit userDataChanged(m_user, m_friendsList);
405     }
406 }
407
408 void SituareService::addProfileImages()
409 {
410     qDebug() << __PRETTY_FUNCTION__;
411
412     // reduce net traffic by sending only one download request for facebook silhouette image
413     if(m_defaultImage) {
414         emit fetchImage(QUrl(SILHOUETTE_URL));
415     }
416
417     if(!m_user->profileImageUrl().isEmpty() && m_user->profileImageUrl().isValid())
418         emit fetchImage(m_user->profileImageUrl());
419
420     if(!m_user->profileImageUrlBig().isEmpty() && m_user->profileImageUrlBig().isValid()) {
421         emit fetchImage(m_user->profileImageUrlBig());
422     }
423
424     for(int i=0;i<m_friendsList.count();i++) {
425         if(!m_friendsList.at(i)->profileImageUrl().isEmpty() &&
426            m_friendsList.at(i)->profileImageUrl().isValid()) {
427             m_visited++; // indicates how many friends that have profile image
428             emit fetchImage(m_friendsList.at(i)->profileImageUrl());
429         }
430     }
431 }
432
433 void SituareService::clearUserData()
434 {
435     qDebug() << __PRETTY_FUNCTION__;
436
437     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
438     m_friendsList.clear();
439
440     if(m_user) {
441         delete m_user;
442         m_user = 0;
443     }
444     emit userDataChanged(m_user, m_friendsList);
445 }