Removed unnecessary images from res folder and made a few cosmetic changes
[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 #include "network/networkaccessmanager.h"
33
34 SituareService::SituareService(QObject *parent)
35         : QObject(parent),
36         m_user(0)
37 {
38     qDebug() << __PRETTY_FUNCTION__;
39
40     m_networkManager = NetworkAccessManager::instance();
41     connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));
42
43     m_imageFetcher = new ImageFetcher(NetworkAccessManager::instance(), this);
44     connect(this, SIGNAL(fetchImage(QUrl)), m_imageFetcher, SLOT(fetchImage(QUrl)));
45     connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)), this,
46             SLOT(imageReceived(QUrl, QPixmap)));
47     connect(m_imageFetcher, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
48 }
49
50 SituareService::~SituareService()
51 {
52     qDebug() << __PRETTY_FUNCTION__;
53
54     if(m_user) {
55         delete m_user;
56         m_user = 0;
57     }
58
59     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
60     m_friendsList.clear();
61 }
62
63 void SituareService::fetchLocations()
64 {
65     qDebug() << __PRETTY_FUNCTION__;
66
67     QString cookie = formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
68                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
69                                 m_credentials.sig(), EN_LOCALE);
70
71     QUrl url = formUrl(SITUARE_URL, GET_LOCATIONS);
72     sendRequest(url, COOKIE, cookie);
73 }
74
75 void SituareService::reverseGeo(const QPointF &coordinates)
76 {
77     qDebug() << __PRETTY_FUNCTION__;
78
79     QString cookie = formCookie(API_KEY, m_credentials.expires(),m_credentials.userID(),
80                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
81                                 m_credentials.sig(), EN_LOCALE);
82
83     QString urlParameters = formUrlParameters(coordinates);
84     QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
85
86     sendRequest(url, COOKIE, cookie);
87 }
88
89 void SituareService::updateLocation(const QPointF &coordinates, const QString &status,
90                                     const bool &publish)
91 {
92     qDebug() << __PRETTY_FUNCTION__;
93
94     QString cookie = formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
95                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
96                                 m_credentials.sig(), EN_LOCALE);
97
98
99     QString publishValue;
100     if(publish) {
101         publishValue = PUBLISH_TRUE;
102     }
103     else {
104         publishValue = PUBLISH_FALSE;
105     }
106     QString urlParameters = formUrlParameters(coordinates, status, publishValue);
107     QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
108
109     sendRequest(url, COOKIE, cookie);
110 }
111
112 QString SituareService::formCookie(const QString &apiKeyValue, QString expiresValue,
113                                    QString userValue, QString sessionKeyValue,
114                                    QString sessionSecretValue, const QString &signatureValue,
115                                    const QString &localeValue)
116 {
117     qDebug() << __PRETTY_FUNCTION__;
118
119     QString cookie;
120     QString apiKey;
121     QString user;
122     QString expires;
123     QString sessionKey;
124     QString sessionSecret;
125     QString locale;
126     QString variable;
127     QString signature = EQUAL_MARK;
128     QStringList variableList;
129
130     signature.append(signatureValue);
131     apiKey.append(apiKeyValue);
132     apiKey.append(UNDERLINE_MARK);
133
134     user.append(USER);
135     user.append(EQUAL_MARK);
136     expires.append(EXPIRES);
137     expires.append(EQUAL_MARK);
138     sessionKey.append(SESSION_KEY);
139     sessionKey.append(EQUAL_MARK);
140     sessionSecret.append(SESSION_SECRET);
141     sessionSecret.append(EQUAL_MARK);
142     locale.append(LOCALE);
143     locale.append(EQUAL_MARK);
144     locale.append(localeValue);
145
146     variableList.append(expires.append(expiresValue.append(BREAK_MARK)));
147     variableList.append(sessionKey.append(sessionKeyValue.append(BREAK_MARK)));
148     variableList.append(user.append(userValue).append(BREAK_MARK));
149     variableList.append(sessionSecret.append(sessionSecretValue.append(BREAK_MARK)));
150
151     cookie.append(BREAK_MARK);
152
153     foreach(variable, variableList) {
154         cookie.append(apiKey);
155         cookie.append(variable);
156     }
157     apiKey.remove(UNDERLINE_MARK);
158     cookie.append(apiKey);
159     cookie.append(signature);
160     cookie.append(BREAK_MARK);
161     cookie.append(locale);
162
163     qDebug() << cookie;
164
165     return cookie;
166 }
167
168 QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript,
169                              QString urlParameters)
170 {
171     qDebug() << __PRETTY_FUNCTION__;
172     QString urlString;
173
174     urlString.append(baseUrl);
175     urlString.append(phpScript);
176     if(!urlParameters.isEmpty())
177         urlString.append(urlParameters);
178
179     QUrl url = QUrl(urlString);
180
181     qDebug() << url;
182
183     return url;
184 }
185
186 QString SituareService::formUrlParameters(const QPointF &coordinates, QString status,
187                                           QString publish)
188 {
189     QString parameters;
190
191     parameters.append(QUESTION_MARK);
192     parameters.append(LATITUDE);
193     parameters.append(EQUAL_MARK);
194     parameters.append(QString::number(coordinates.y()));
195     parameters.append(AMBERSAND_MARK);
196     parameters.append(LONGTITUDE);
197     parameters.append(EQUAL_MARK);
198     parameters.append(QString::number(coordinates.x()));
199
200     if(publish.compare(PUBLISH_TRUE) == 0) {
201         parameters.append(AMBERSAND_MARK);
202         parameters.append(PUBLISH);
203         parameters.append(EQUAL_MARK);
204         parameters.append(PUBLISH_TRUE);
205     }
206     else if(publish.compare(PUBLISH_FALSE) == 0) {
207         parameters.append(AMBERSAND_MARK);
208         parameters.append(PUBLISH);
209         parameters.append(EQUAL_MARK);
210         parameters.append(PUBLISH_FALSE);
211     }
212
213     if(!status.isEmpty()) {
214         parameters.append(AMBERSAND_MARK);
215         parameters.append(DATA);
216         parameters.append(EQUAL_MARK);
217         parameters.append(status);
218     }
219
220     return parameters;
221 }
222
223 void SituareService::sendRequest(const QUrl &url, const QString &cookieType, const QString &cookie)
224 {
225     qDebug() << __PRETTY_FUNCTION__;
226
227     QNetworkRequest request;
228
229     request.setUrl(url);
230     request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
231     request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
232
233     QNetworkReply *reply = m_networkManager->get(request);
234
235     m_currentRequests.append(reply);
236 }
237
238 void SituareService::requestFinished(QNetworkReply *reply)
239 {
240     qDebug() << __PRETTY_FUNCTION__;
241
242     //Reply from situare
243     if (m_currentRequests.contains(reply)) {
244
245         QUrl url = reply->url();
246         qDebug() << "BytesAvailable: " << reply->bytesAvailable();
247         if (reply->error()) {
248             qDebug() << reply->errorString();
249             emit error(reply->errorString());
250         }
251         else {
252             qint64 max = reply->size();
253             QByteArray replyArray = reply->read(max);
254             qDebug() << "Reply from: " << url << "reply " << replyArray;
255             // ToDo: results handling includes Situare's errors
256             // works like situare's error handling i.e. both lat & lon are missing/wrong
257             // -> we get only error for wrong lon
258             if(replyArray == ERROR_LAT.toAscii()) {
259                 qDebug() << "Error: " << ERROR_LAT;
260                 emit error(replyArray);
261             }
262             else if(replyArray == ERROR_LON.toAscii()) {
263                 qDebug() << "Error: " << ERROR_LON;
264                 emit error(replyArray);
265             }
266             else if(replyArray.contains(ERROR_SESSION.toAscii())) {
267                 qDebug() << "Error: " << ERROR_SESSION;
268                 emit invalidSessionCredentials();
269             }
270             else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
271                 qDebug() << "JSON string";
272                 parseUserData(replyArray);
273             }
274             else if(replyArray == "") {
275                             if(url.toString().contains(UPDATE_LOCATION.toAscii())) {
276                     emit updateWasSuccessful();
277                 }
278                 else {
279                     // session credentials are invalid
280                     emit invalidSessionCredentials();
281                 }
282             }
283             else {
284                 // Street address ready
285                 QString address = QString::fromUtf8(replyArray);
286                 emit reverseGeoReady(address);
287             }
288         }
289         m_currentRequests.removeAll(reply);
290         reply->deleteLater();
291     }
292 }
293
294 void SituareService::credentialsReady(const FacebookCredentials &credentials)
295 {
296     qDebug() << __PRETTY_FUNCTION__;
297
298     m_credentials = credentials;    
299 }
300
301 void SituareService::parseUserData(const QByteArray &jsonReply)
302 {
303     qDebug() << __PRETTY_FUNCTION__;
304
305     m_visited = 0;
306     m_nbrOfImages = 0;
307     m_defaultImage = false;
308     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
309     m_friendsList.clear();
310
311     if(m_user) {
312         delete m_user;
313         m_user = 0;
314     }
315
316     QJson::Parser parser;
317     bool ok;
318
319     QVariantMap result = parser.parse (jsonReply, &ok).toMap();
320     if (!ok) {
321
322         qFatal("An error occurred during parsing");
323         exit (1);
324     }
325
326     QVariant userVariant = result.value("user");
327     QMap<QString, QVariant> userMap = userVariant.toMap();
328
329     QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
330
331     QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
332
333     if(imageUrl.isEmpty()) {
334         // user doesn't have profile image, so we need to get him a silhouette image
335         m_defaultImage = true;
336     }
337
338     m_user = new User(userMap["address"].toString(), coordinates, userMap["name"].toString(),
339                   userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
340                   true, userMap["uid"].toString());
341
342     foreach (QVariant friendsVariant, result["friends"].toList()) {
343       QMap<QString, QVariant> friendMap = friendsVariant.toMap();
344       QVariant distance = friendMap["distance"];
345       QMap<QString, QVariant> distanceMap = distance.toMap();
346
347       QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
348
349       QUrl imageUrl = friendMap["profile_pic"].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,
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, AvatarImage::Large));
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                                                                          AvatarImage::Small));
383             }
384         }
385     }
386
387     if (m_user->profileImageUrl() == url) {
388         m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
389     }
390
391     for(int i=0;i<m_friendsList.count();i++) {
392         if(m_friendsList.at(i)->profileImageUrl() == url) {
393             m_friendsList.at(i)->setProfileImage(AvatarImage::create(image, AvatarImage::Small));
394             m_nbrOfImages++; // indicates how many friend profile images has been downloaded
395         }
396     }
397
398     if(m_nbrOfImages == m_visited) {
399         qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
400         qDebug() << "emit userDataChanged";
401         emit userDataChanged(m_user, m_friendsList);
402     }
403 }
404
405 void SituareService::addProfileImages()
406 {
407     qDebug() << __PRETTY_FUNCTION__;
408
409     // reduce net traffic by sending only one download request for facebook silhouette image
410     if(m_defaultImage) {
411         emit fetchImage(QUrl(SILHOUETTE_URL));
412     }
413
414     if(!m_user->profileImageUrl().isEmpty() && m_user->profileImageUrl().isValid())
415         emit fetchImage(m_user->profileImageUrl());
416
417     for(int i=0;i<m_friendsList.count();i++) {
418         if(!m_friendsList.at(i)->profileImageUrl().isEmpty() &&
419            m_friendsList.at(i)->profileImageUrl().isValid()) {
420             m_visited++; // indicates how many friends that have profile image
421             emit fetchImage(m_friendsList.at(i)->profileImageUrl());
422         }
423     }
424 }
425
426 void SituareService::clearUserData()
427 {
428     qDebug() << __PRETTY_FUNCTION__;
429
430     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
431     m_friendsList.clear();
432
433     if(m_user) {
434         delete m_user;
435         m_user = 0;
436     }
437     emit userDataChanged(m_user, m_friendsList);
438 }