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