c9080a810a761b2af7fc032ce06bd5d4065bbd26
[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
32 SituareService::SituareService(QObject *parent)
33         : QObject(parent)
34 {
35     qDebug() << __PRETTY_FUNCTION__;
36
37     m_networkManager = new QNetworkAccessManager;
38     connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));
39
40     m_imageFetcher = new ImageFetcher(new QNetworkAccessManager(this), this);
41     connect(this, SIGNAL(fetchImage(QUrl)), m_imageFetcher, SLOT(fetchImage(QUrl)));
42     connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)), this,
43             SLOT(imageReceived(QUrl, QPixmap)));
44     connect(m_imageFetcher, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
45
46     m_user = 0;
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.x()));
198     parameters.append(AMBERSAND_MARK);
199     parameters.append(LONGTITUDE);
200     parameters.append(EQUAL_MARK);
201     parameters.append(QString::number(coordinates.y()));
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 error(replyArray);
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                 // server error!
279             }
280         }
281         else {
282             // Street address ready
283             QString address(replyArray);
284             emit reverseGeoReady(address);
285         }
286     }
287     m_currentRequests.removeAll(reply);
288     reply->deleteLater();
289 }
290
291 void SituareService::credentialsReady(const FacebookCredentials &credentials)
292 {
293     qDebug() << __PRETTY_FUNCTION__;
294     m_credentials = credentials;
295     
296 }
297
298 void SituareService::parseUserData(const QByteArray &jsonReply)
299 {
300     qDebug() << __PRETTY_FUNCTION__;
301
302     m_visited = 0;
303     m_nbrOfImages = 0;
304     m_defaultImage = false;
305     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
306     m_friendsList.clear();
307
308     if(m_user) {
309         delete m_user;
310         m_user = 0;
311     }
312
313     QJson::Parser parser;
314     bool ok;
315
316     QVariantMap result = parser.parse (jsonReply, &ok).toMap();
317     if (!ok) {
318
319         qFatal("An error occurred during parsing");
320         exit (1);
321     }
322
323     QVariant userVariant = result.value("user");
324     QMap<QString, QVariant> userMap = userVariant.toMap();
325
326     QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
327
328     QUrl imageUrl = userMap["profile_pic"].toUrl();
329
330     if(imageUrl.isEmpty()) {
331         // user doesn't have profile image, so we need to get him a silhouette image
332         m_defaultImage = true;
333     }
334
335     m_user = new User(userMap["address"].toString(), coordinates, userMap["name"].toString(),
336                   userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
337                   true, userMap["uid"].toString());
338
339     foreach (QVariant friendsVariant, result["friends"].toList()) {
340       QMap<QString, QVariant> friendMap = friendsVariant.toMap();
341       QVariant distance = friendMap["distance"];
342       QMap<QString, QVariant> distanceMap = distance.toMap();
343
344       QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
345
346       QUrl imageUrl = friendMap["profile_pic"].toUrl();
347
348       if(imageUrl.isEmpty()) {
349           // friend doesn't have profile image, so we need to get him a silhouette image
350           m_defaultImage = true;
351       }
352
353       User *user = new User(friendMap["address"].toString(), coordinates,
354                             friendMap["name"].toString(),
355                             friendMap["note"].toString(), imageUrl,
356                             friendMap["timestamp"].toString(),
357                             false, friendMap["uid"].toString(),
358                             distanceMap["units"].toString(),
359                             distanceMap["value"].toDouble());
360
361       m_friendsList.append(user);
362     }
363     addProfileImages();
364 }
365
366 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
367 {
368     qDebug() << __PRETTY_FUNCTION__;
369     qDebug() << "Image URL: " << url << " size :" << image.size();
370
371     // assign facebook silhouette image to all who doesn't have a profile image
372     if(url == QUrl(SILHOUETTE_URL)) {
373         if(m_user->profileImageUrl().isEmpty()) {
374             m_user->setProfileImage(image);
375         }
376         for(int i=0;i < m_friendsList.count();i++) {
377             if(m_friendsList.at(i)->profileImageUrl().isEmpty()) {
378                 m_friendsList.at(i)->setProfileImage(image);
379             }
380         }
381     }
382
383     if(m_user->profileImageUrl() == url) {
384         m_user->setProfileImage(image);
385     }
386
387     for(int i=0;i<m_friendsList.count();i++) {
388         if(m_friendsList.at(i)->profileImageUrl() == url) {
389             m_friendsList.at(i)->setProfileImage(image);
390             m_nbrOfImages++; // indicates how many friend profile images has been downloaded
391         }
392     }
393
394     if(m_nbrOfImages == m_visited) {
395         qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
396         qDebug() << "emit userDataChanged";
397         emit userDataChanged(m_user, m_friendsList);
398     }
399 }
400
401 void SituareService::addProfileImages()
402 {
403     qDebug() << __PRETTY_FUNCTION__;
404
405     // reduce net traffic by sending only one download request for facebook silhouette image
406     if(m_defaultImage) {
407         emit fetchImage(QUrl(SILHOUETTE_URL));
408     }
409
410     if(!m_user->profileImageUrl().isEmpty() && m_user->profileImageUrl().isValid()) {
411         emit fetchImage(m_user->profileImageUrl());
412     }
413
414     for(int i=0;i<m_friendsList.count();i++) {
415         if(!m_friendsList.at(i)->profileImageUrl().isEmpty() &&
416            m_friendsList.at(i)->profileImageUrl().isValid()) {
417             m_visited++; // indicates how many friends that have profile image
418             emit fetchImage(m_friendsList.at(i)->profileImageUrl());
419         }
420     }
421 }