Added method to queue requests if not connected to network.
[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 "engine/networkaccessmanager.h"
33
34 SituareService::SituareService(QObject *parent)
35         : QObject(parent)
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 NetworkAccessManager(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     m_user = 0;
49 }
50
51 SituareService::~SituareService()
52 {
53     qDebug() << __PRETTY_FUNCTION__;
54
55     delete m_networkManager;
56     m_networkManager = 0;
57     if(m_user) {
58         delete m_user;
59         m_user = 0;
60     }
61     delete m_imageFetcher;
62     m_imageFetcher = 0;
63
64     qDeleteAll(m_friendsList.begin(), m_friendsList.end());
65     m_friendsList.clear();
66 }
67
68 void SituareService::fetchLocations()
69 {
70     qDebug() << __PRETTY_FUNCTION__;
71
72     QString cookie = formCookie(API_KEY, m_credentials.expires(),m_credentials.userID(),
73                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
74                                 m_credentials.sig(), EN_LOCALE);
75
76     QUrl url = formUrl(SITUARE_URL, GET_LOCATIONS);
77     sendRequest(url, COOKIE, cookie);
78 }
79
80 void SituareService::reverseGeo(const QPointF &coordinates)
81 {
82     qDebug() << __PRETTY_FUNCTION__;
83
84     QString cookie = formCookie(API_KEY, m_credentials.expires(),m_credentials.userID(),
85                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
86                                 m_credentials.sig(), EN_LOCALE);
87
88     QString urlParameters = formUrlParameters(coordinates);
89     QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
90
91     sendRequest(url, COOKIE, cookie);
92 }
93
94 void SituareService::updateLocation(const QPointF &coordinates, const QString &status,
95                                     const bool &publish)
96 {
97     qDebug() << __PRETTY_FUNCTION__;
98
99     QString cookie = formCookie(API_KEY, m_credentials.expires(),m_credentials.userID(),
100                                 m_credentials.sessionKey(), m_credentials.sessionSecret(),
101                                 m_credentials.sig(), EN_LOCALE);
102
103
104     QString publishValue;
105     if(publish) {
106         publishValue = PUBLISH_TRUE;
107     }
108     else {
109         publishValue = PUBLISH_FALSE;
110     }
111     QString urlParameters = formUrlParameters(coordinates, status, publishValue);
112     QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
113
114     sendRequest(url, COOKIE, cookie);
115 }
116
117 QString SituareService::formCookie(const QString &apiKeyValue, QString expiresValue,
118                                    QString userValue, QString sessionKeyValue,
119                                    QString sessionSecretValue, const QString &signatureValue,
120                                    const QString &localeValue)
121 {
122     qDebug() << __PRETTY_FUNCTION__;
123
124     QString cookie;
125     QString apiKey;
126     QString user;
127     QString expires;
128     QString sessionKey;
129     QString sessionSecret;
130     QString locale;
131     QString variable;
132     QString signature = EQUAL_MARK;
133     QStringList variableList;
134
135     signature.append(signatureValue);
136     apiKey.append(apiKeyValue);
137     apiKey.append(UNDERLINE_MARK);
138
139     user.append(USER);
140     user.append(EQUAL_MARK);
141     expires.append(EXPIRES);
142     expires.append(EQUAL_MARK);
143     sessionKey.append(SESSION_KEY);
144     sessionKey.append(EQUAL_MARK);
145     sessionSecret.append(SESSION_SECRET);
146     sessionSecret.append(EQUAL_MARK);
147     locale.append(LOCALE);
148     locale.append(EQUAL_MARK);
149     locale.append(localeValue);
150
151     variableList.append(expires.append(expiresValue.append(BREAK_MARK)));
152     variableList.append(sessionKey.append(sessionKeyValue.append(BREAK_MARK)));
153     variableList.append(user.append(userValue).append(BREAK_MARK));
154     variableList.append(sessionSecret.append(sessionSecretValue.append(BREAK_MARK)));
155
156     cookie.append(BREAK_MARK);
157
158     foreach(variable, variableList) {
159         cookie.append(apiKey);
160         cookie.append(variable);
161     }
162     apiKey.remove(UNDERLINE_MARK);
163     cookie.append(apiKey);
164     cookie.append(signature);
165     cookie.append(BREAK_MARK);
166     cookie.append(locale);
167
168     qDebug() << cookie;
169
170     return cookie;
171 }
172
173 QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript,
174                              QString urlParameters)
175 {
176     qDebug() << __PRETTY_FUNCTION__;
177     QString urlString;
178
179     urlString.append(baseUrl);
180     urlString.append(phpScript);
181     if(!urlParameters.isEmpty())
182         urlString.append(urlParameters);
183
184     QUrl url = QUrl(urlString);
185
186     qDebug() << url;
187
188     return url;
189 }
190
191 QString SituareService::formUrlParameters(const QPointF &coordinates, QString status,
192                                           QString publish)
193 {
194     QString parameters;
195
196     parameters.append(QUESTION_MARK);
197     parameters.append(LATITUDE);
198     parameters.append(EQUAL_MARK);
199     parameters.append(QString::number(coordinates.y()));
200     parameters.append(AMBERSAND_MARK);
201     parameters.append(LONGTITUDE);
202     parameters.append(EQUAL_MARK);
203     parameters.append(QString::number(coordinates.x()));
204
205     if(publish.compare(PUBLISH_TRUE) == 0) {
206         parameters.append(AMBERSAND_MARK);
207         parameters.append(PUBLISH);
208         parameters.append(EQUAL_MARK);
209         parameters.append(PUBLISH_TRUE);
210     }
211     else if(publish.compare(PUBLISH_FALSE) == 0) {
212         parameters.append(AMBERSAND_MARK);
213         parameters.append(PUBLISH);
214         parameters.append(EQUAL_MARK);
215         parameters.append(PUBLISH_FALSE);
216     }
217
218     if(!status.isEmpty()) {
219         parameters.append(AMBERSAND_MARK);
220         parameters.append(DATA);
221         parameters.append(EQUAL_MARK);
222         parameters.append(status);
223     }
224
225     return parameters;
226 }
227
228 void SituareService::sendRequest(const QUrl &url, const QString &cookieType, const QString &cookie)
229 {
230     qDebug() << __PRETTY_FUNCTION__ << "url: " << url;
231
232     QNetworkRequest request;
233
234     request.setUrl(url);
235     request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
236
237     QNetworkReply *reply = m_networkManager->get(request);
238
239     m_currentRequests.append(reply);
240 }
241
242 void SituareService::requestFinished(QNetworkReply *reply)
243 {
244     qDebug() << __PRETTY_FUNCTION__;
245
246     QUrl url = reply->url();
247     qDebug() << "BytesAvailable: " << reply->bytesAvailable();
248     if (reply->error()) {
249         qDebug() << reply->errorString();
250         emit error(reply->errorString());
251     }
252     else {
253         qint64 max = reply->size();
254         QByteArray replyArray = reply->read(max);
255         qDebug() << "Reply from: " << url << "reply " << replyArray;
256         // ToDo: results handling includes Situare's errors
257         // works like situare's error handling i.e. both lat & lon are missing/wrong
258         // -> we get only error for wrong lon
259         if(replyArray == ERROR_LAT.toAscii()) {
260             qDebug() << "Error: " << ERROR_LAT;
261             emit error(replyArray);
262         }
263         else if(replyArray == ERROR_LON.toAscii()) {
264             qDebug() << "Error: " << ERROR_LON;
265             emit error(replyArray);
266         }
267         else if(replyArray.contains(ERROR_SESSION.toAscii())) {
268             qDebug() << "Error: " << ERROR_SESSION;
269             emit error(replyArray);
270         }
271         else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
272             qDebug() << "JSON string";
273             parseUserData(replyArray);
274         }
275         else if(replyArray == "") {
276                         if(url.toString().contains(UPDATE_LOCATION.toAscii())) {
277                 emit updateWasSuccessful();
278             }
279             else {
280                 // server error!
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 void SituareService::credentialsReady(bool freshLogin, const FacebookCredentials &credentials)
294 {
295     qDebug() << __PRETTY_FUNCTION__;
296     Q_UNUSED(freshLogin);
297     m_credentials = credentials;
298     
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["profile_pic"].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));
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     for(int i=0;i<m_friendsList.count();i++) {
391         if(m_friendsList.at(i)->profileImageUrl() == url) {
392             m_friendsList.at(i)->setProfileImage(AvatarImage::create(image));
393             m_nbrOfImages++; // indicates how many friend profile images has been downloaded
394         }
395     }
396
397     if(m_nbrOfImages == m_visited) {
398         qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
399         qDebug() << "emit userDataChanged";
400         emit userDataChanged(m_user, m_friendsList);
401     }
402 }
403
404 void SituareService::addProfileImages()
405 {
406     qDebug() << __PRETTY_FUNCTION__;
407
408     // reduce net traffic by sending only one download request for facebook silhouette image
409     if(m_defaultImage) {
410         emit fetchImage(QUrl(SILHOUETTE_URL));
411     }
412
413     if(!m_user->profileImageUrl().isEmpty() && m_user->profileImageUrl().isValid()) {
414         emit fetchImage(m_user->profileImageUrl());
415     }
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 }