2 Situare - A location system for Facebook
3 Copyright (C) 2010 Ixonos Plc. Authors:
5 Henri Lampela - henri.lampela@ixonos.com
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.
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.
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,
22 #include <QtAlgorithms>
25 #include <QStringList>
27 #include <QNetworkReply>
28 #include "situareservice.h"
29 #include "situarecommon.h"
31 #include "ui/avatarimage.h"
32 #include "network/networkaccessmanager.h"
34 SituareService::SituareService(QObject *parent)
38 qDebug() << __PRETTY_FUNCTION__;
40 m_networkManager = NetworkAccessManager::instance();
41 connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));
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)));
50 SituareService::~SituareService()
52 qDebug() << __PRETTY_FUNCTION__;
59 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
60 m_friendsList.clear();
63 void SituareService::fetchLocations()
65 qDebug() << __PRETTY_FUNCTION__;
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);
71 QUrl url = formUrl(SITUARE_URL, GET_LOCATIONS);
72 sendRequest(url, COOKIE, cookie);
75 void SituareService::reverseGeo(const QPointF &coordinates)
77 qDebug() << __PRETTY_FUNCTION__;
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);
83 QString urlParameters = formUrlParameters(coordinates);
84 QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
86 sendRequest(url, COOKIE, cookie);
89 void SituareService::updateLocation(const QPointF &coordinates, const QString &status,
92 qDebug() << __PRETTY_FUNCTION__;
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);
101 publishValue = PUBLISH_TRUE;
104 publishValue = PUBLISH_FALSE;
106 QString urlParameters = formUrlParameters(coordinates, status, publishValue);
107 QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
109 sendRequest(url, COOKIE, cookie);
112 QString SituareService::formCookie(const QString &apiKeyValue, QString expiresValue,
113 QString userValue, QString sessionKeyValue,
114 QString sessionSecretValue, const QString &signatureValue,
115 const QString &localeValue)
117 qDebug() << __PRETTY_FUNCTION__;
124 QString sessionSecret;
127 QString signature = EQUAL_MARK;
128 QStringList variableList;
130 signature.append(signatureValue);
131 apiKey.append(apiKeyValue);
132 apiKey.append(UNDERLINE_MARK);
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);
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)));
151 cookie.append(BREAK_MARK);
153 foreach(variable, variableList) {
154 cookie.append(apiKey);
155 cookie.append(variable);
157 apiKey.remove(UNDERLINE_MARK);
158 cookie.append(apiKey);
159 cookie.append(signature);
160 cookie.append(BREAK_MARK);
161 cookie.append(locale);
168 QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript,
169 QString urlParameters)
171 qDebug() << __PRETTY_FUNCTION__;
174 urlString.append(baseUrl);
175 urlString.append(phpScript);
176 if(!urlParameters.isEmpty())
177 urlString.append(urlParameters);
179 QUrl url = QUrl(urlString);
186 QString SituareService::formUrlParameters(const QPointF &coordinates, QString status,
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()));
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);
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);
213 if(!status.isEmpty()) {
214 parameters.append(AMBERSAND_MARK);
215 parameters.append(DATA);
216 parameters.append(EQUAL_MARK);
217 parameters.append(status);
223 void SituareService::sendRequest(const QUrl &url, const QString &cookieType, const QString &cookie)
225 qDebug() << __PRETTY_FUNCTION__;
227 QNetworkRequest request;
230 request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
231 request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
233 QNetworkReply *reply = m_networkManager->get(request);
235 m_currentRequests.append(reply);
238 void SituareService::requestFinished(QNetworkReply *reply)
240 qDebug() << __PRETTY_FUNCTION__;
243 if (m_currentRequests.contains(reply)) {
245 QUrl url = reply->url();
246 qDebug() << "BytesAvailable: " << reply->bytesAvailable();
247 if (reply->error()) {
248 qDebug() << reply->errorString();
249 emit error(reply->errorString());
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);
262 else if(replyArray == ERROR_LON.toAscii()) {
263 qDebug() << "Error: " << ERROR_LON;
264 emit error(replyArray);
266 else if(replyArray.contains(ERROR_SESSION.toAscii())) {
267 qDebug() << "Error: " << ERROR_SESSION;
268 emit invalidSessionCredentials();
270 else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
271 qDebug() << "JSON string";
272 parseUserData(replyArray);
274 else if(replyArray == "") {
275 if(url.toString().contains(UPDATE_LOCATION.toAscii())) {
276 emit updateWasSuccessful();
279 // session credentials are invalid
280 emit invalidSessionCredentials();
284 // Street address ready
285 QString address = QString::fromUtf8(replyArray);
286 emit reverseGeoReady(address);
289 m_currentRequests.removeAll(reply);
290 reply->deleteLater();
294 void SituareService::credentialsReady(const FacebookCredentials &credentials)
296 qDebug() << __PRETTY_FUNCTION__;
298 m_credentials = credentials;
301 void SituareService::parseUserData(const QByteArray &jsonReply)
303 qDebug() << __PRETTY_FUNCTION__;
307 m_defaultImage = false;
308 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
309 m_friendsList.clear();
316 QJson::Parser parser;
319 QVariantMap result = parser.parse (jsonReply, &ok).toMap();
322 qFatal("An error occurred during parsing");
326 QVariant userVariant = result.value("user");
327 QMap<QString, QVariant> userMap = userVariant.toMap();
329 QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
331 QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
333 if(imageUrl.isEmpty()) {
334 // user doesn't have profile image, so we need to get him a silhouette image
335 m_defaultImage = true;
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());
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();
347 QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
349 QUrl imageUrl = friendMap["profile_pic"].toUrl();
351 if(imageUrl.isEmpty()) {
352 // friend doesn't have profile image, so we need to get him a silhouette image
353 m_defaultImage = true;
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());
364 m_friendsList.append(user);
369 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
371 qDebug() << __PRETTY_FUNCTION__;
372 qDebug() << "Image URL: " << url << " size :" << image.size();
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));
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));
387 if (m_user->profileImageUrl() == url) {
388 m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
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
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);
405 void SituareService::addProfileImages()
407 qDebug() << __PRETTY_FUNCTION__;
409 // reduce net traffic by sending only one download request for facebook silhouette image
411 emit fetchImage(QUrl(SILHOUETTE_URL));
414 if(!m_user->profileImageUrl().isEmpty() && m_user->profileImageUrl().isValid())
415 emit fetchImage(m_user->profileImageUrl());
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());
426 void SituareService::clearUserData()
428 qDebug() << __PRETTY_FUNCTION__;
430 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
431 m_friendsList.clear();
437 emit userDataChanged(m_user, m_friendsList);