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"
32 #include "ui/avatarimage.h"
33 #include "network/networkaccessmanager.h"
35 SituareService::SituareService(QObject *parent)
39 qDebug() << __PRETTY_FUNCTION__;
41 m_networkManager = new NetworkAccessManager(this);
42 connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
43 this, SLOT(requestFinished(QNetworkReply*)), Qt::QueuedConnection);
45 m_imageFetcher = new ImageFetcher(new NetworkAccessManager(this), this);
46 connect(this, SIGNAL(fetchImage(QUrl)),
47 m_imageFetcher, SLOT(fetchImage(QUrl)));
48 connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)),
49 this, SLOT(imageReceived(QUrl, QPixmap)));
50 connect(m_imageFetcher, SIGNAL(error(int, int)),
51 this, SIGNAL(error(int, int)));
54 SituareService::~SituareService()
56 qDebug() << __PRETTY_FUNCTION__;
63 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
64 m_friendsList.clear();
67 void SituareService::fetchLocations()
69 qDebug() << __PRETTY_FUNCTION__;
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);
75 QUrl url = formUrl(SITUARE_URL, GET_LOCATIONS);
76 sendRequest(url, COOKIE, cookie);
79 void SituareService::reverseGeo(const GeoCoordinate &coordinates)
81 qDebug() << __PRETTY_FUNCTION__;
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);
87 QString urlParameters = formUrlParameters(coordinates);
88 urlParameters.append(JSON_FORMAT);
89 QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
91 sendRequest(url, COOKIE, cookie);
94 void SituareService::updateLocation(const GeoCoordinate &coordinates, const QString &status,
97 qDebug() << __PRETTY_FUNCTION__;
99 QString urlParameters = formUrlParameters(coordinates, status, publish);
100 QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
102 QString cookie = formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
103 m_credentials.sessionKey(), m_credentials.sessionSecret(),
104 m_credentials.sig(), EN_LOCALE);
106 sendRequest(url, COOKIE, cookie);
109 QString SituareService::formCookie(const QString &apiKeyValue, QString expiresValue,
110 QString userValue, QString sessionKeyValue,
111 QString sessionSecretValue, const QString &signatureValue,
112 const QString &localeValue)
114 qDebug() << __PRETTY_FUNCTION__;
121 QString sessionSecret;
124 QString signature = EQUAL_MARK;
125 QStringList variableList;
127 signature.append(signatureValue);
128 apiKey.append(apiKeyValue);
129 apiKey.append(UNDERLINE_MARK);
132 user.append(EQUAL_MARK);
133 expires.append(EXPIRES);
134 expires.append(EQUAL_MARK);
135 sessionKey.append(SESSION_KEY);
136 sessionKey.append(EQUAL_MARK);
137 sessionSecret.append(SESSION_SECRET);
138 sessionSecret.append(EQUAL_MARK);
139 locale.append(LOCALE);
140 locale.append(EQUAL_MARK);
141 locale.append(localeValue);
143 variableList.append(expires.append(expiresValue.append(BREAK_MARK)));
144 variableList.append(sessionKey.append(sessionKeyValue.append(BREAK_MARK)));
145 variableList.append(user.append(userValue).append(BREAK_MARK));
146 variableList.append(sessionSecret.append(sessionSecretValue.append(BREAK_MARK)));
148 cookie.append(BREAK_MARK);
150 foreach(variable, variableList) {
151 cookie.append(apiKey);
152 cookie.append(variable);
154 apiKey.remove(UNDERLINE_MARK);
155 cookie.append(apiKey);
156 cookie.append(signature);
157 cookie.append(BREAK_MARK);
158 cookie.append(locale);
165 QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript,
166 QString urlParameters)
168 qDebug() << __PRETTY_FUNCTION__;
171 urlString.append(baseUrl);
172 urlString.append(phpScript);
173 if(!urlParameters.isEmpty())
174 urlString.append(urlParameters);
176 QUrl url = QUrl(urlString);
183 QString SituareService::formUrlParameters(const GeoCoordinate &coordinates, QString status,
186 qDebug() << __PRETTY_FUNCTION__;
188 // one scene pixel is about 5.4e-6 degrees, the integer part is max three digits and one
189 // additional digit is added for maximum precision
190 const int COORDINATE_PRECISION = 10;
194 parameters.append(QUESTION_MARK);
195 parameters.append(LATITUDE);
196 parameters.append(EQUAL_MARK);
197 parameters.append(QString::number(coordinates.latitude(), 'f', COORDINATE_PRECISION));
198 parameters.append(AMBERSAND_MARK);
199 parameters.append(LONGTITUDE);
200 parameters.append(EQUAL_MARK);
201 parameters.append(QString::number(coordinates.longitude(), 'f', COORDINATE_PRECISION));
203 parameters.append(AMBERSAND_MARK);
204 parameters.append(PUBLISH);
205 parameters.append(EQUAL_MARK);
208 parameters.append(PUBLISH_TRUE);
210 parameters.append(PUBLISH_FALSE);
212 if(!status.isEmpty()) {
213 parameters.append(AMBERSAND_MARK);
214 parameters.append(DATA);
215 parameters.append(EQUAL_MARK);
216 parameters.append(status);
222 void SituareService::sendRequest(const QUrl &url, const QString &cookieType, const QString &cookie)
224 qDebug() << __PRETTY_FUNCTION__;
226 QNetworkRequest request;
229 request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
230 request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
232 QNetworkReply *reply = m_networkManager->get(request, true);
234 m_currentRequests.append(reply);
237 void SituareService::requestFinished(QNetworkReply *reply)
239 qDebug() << __PRETTY_FUNCTION__;
242 if (m_currentRequests.contains(reply)) {
244 qDebug() << "BytesAvailable: " << reply->bytesAvailable();
246 if (reply->error()) {
247 emit error(ErrorContext::NETWORK, reply->error());
249 QByteArray replyArray = reply->readAll();
250 qDebug() << "Reply from: " << reply->url() << "reply " << replyArray;
252 if(replyArray == ERROR_LAT.toAscii()) {
253 qDebug() << "Error: " << ERROR_LAT;
254 emit error(ErrorContext::SITUARE, SituareError::UPDATE_FAILED);
255 } else if(replyArray == ERROR_LON.toAscii()) {
256 qDebug() << "Error: " << ERROR_LON;
257 emit error(ErrorContext::SITUARE, SituareError::UPDATE_FAILED);
258 } else if(replyArray.contains(ERROR_SESSION.toAscii())) {
259 qDebug() << "Error: " << ERROR_SESSION;
260 emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
261 } else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
262 qDebug() << "JSON string";
263 parseUserData(replyArray);
264 } else if(replyArray.isEmpty()) {
265 if(reply->url().toString().contains(UPDATE_LOCATION.toAscii())) {
266 emit updateWasSuccessful();
268 // session credentials are invalid
269 emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
273 emit error(ErrorContext::SITUARE, SituareError::ERROR_GENERAL);
276 m_currentRequests.removeAll(reply);
277 reply->deleteLater();
281 void SituareService::credentialsReady(const FacebookCredentials &credentials)
283 qDebug() << __PRETTY_FUNCTION__;
285 m_credentials = credentials;
288 void SituareService::parseUserData(const QByteArray &jsonReply)
290 qDebug() << __PRETTY_FUNCTION__;
292 m_defaultImage = false;
294 QJson::Parser parser;
297 QVariantMap result = parser.parse (jsonReply, &ok).toMap();
299 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
303 if(result.contains("ErrorCode")) {
304 QVariant errorVariant = result.value("ErrorCode");
305 emit error(ErrorContext::SITUARE, errorVariant.toInt());
307 } else if(result.contains("user")) {
309 QVariant userVariant = result.value("user");
310 QMap<QString, QVariant> userMap = userVariant.toMap();
312 GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
314 QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
316 if(imageUrl.isEmpty()) {
317 // user doesn't have profile image, so we need to get him a silhouette image
318 m_defaultImage = true;
321 QString address = userMap["address"].toString();
322 if(address.isEmpty()) {
323 QStringList location;
324 location.append(QString::number(coordinates.latitude()));
325 location.append(QString::number(coordinates.longitude()));
326 address = location.join(", ");
329 User user = User(address, coordinates, userMap["name"].toString(),
330 userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
331 true, userMap["uid"].toString());
333 QList<User> tmpFriendsList;
335 foreach (QVariant friendsVariant, result["friends"].toList()) {
336 QMap<QString, QVariant> friendMap = friendsVariant.toMap();
337 QVariant distance = friendMap["distance"];
338 QMap<QString, QVariant> distanceMap = distance.toMap();
340 GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
342 QUrl imageUrl = friendMap["profile_pic"].toUrl();
344 if(imageUrl.isEmpty()) {
345 // friend doesn't have profile image, so we need to get him a silhouette image
346 m_defaultImage = true;
349 QString address = friendMap["address"].toString();
350 if(address.isEmpty()) {
351 QStringList location;
352 location.append(QString::number(coordinates.latitude()));
353 location.append(QString::number(coordinates.longitude()));
354 address = location.join(", ");
357 User buddy = User(address, coordinates, friendMap["name"].toString(),
358 friendMap["note"].toString(), imageUrl,
359 friendMap["timestamp"].toString(),
360 false, friendMap["uid"].toString(), distanceMap["units"].toString(),
361 distanceMap["value"].toDouble());
363 tmpFriendsList.append(buddy);
366 QList<QUrl> imageUrlList; // url list for images
368 // set unchanged profile images or add new images to imageUrlList for downloading
370 if(m_user->profileImageUrl() != user.profileImageUrl()) {
371 if(!user.profileImageUrl().isEmpty())
372 imageUrlList.append(user.profileImageUrl());
374 user.setProfileImage(m_user->profileImage());
377 if(!user.profileImageUrl().isEmpty())
378 imageUrlList.append(user.profileImageUrl());
381 // clear old user object
387 // create new user object from temporary user object
388 m_user = new User(user);
390 // set unchanged profile images or add new images to imageUrlList for downloading
391 if(!m_friendsList.isEmpty()) {
392 foreach(User tmpBuddy, tmpFriendsList) {
393 if(!tmpBuddy.profileImageUrl().isEmpty()) {
395 foreach(User *buddy, m_friendsList) {
396 if(tmpBuddy.profileImageUrl() == buddy->profileImageUrl()) {
397 tmpBuddy.setProfileImage(buddy->profileImage());
402 if(!found && !tmpBuddy.profileImageUrl().isEmpty())
403 imageUrlList.append(tmpBuddy.profileImageUrl());
407 foreach(User buddy, tmpFriendsList) {
408 if(!buddy.profileImageUrl().isEmpty())
409 imageUrlList.append(buddy.profileImageUrl());
413 // clear old friendlist
414 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
415 m_friendsList.clear();
417 // populate new friendlist with temporary friendlist's data
418 foreach(User tmpFriendItem, tmpFriendsList) {
419 User *friendItem = new User(tmpFriendItem);
420 m_friendsList.append(friendItem);
422 tmpFriendsList.clear();
424 emit userDataChanged(m_user, m_friendsList);
426 // set silhouette image to imageUrlList for downloading
428 imageUrlList.append(QUrl(SILHOUETTE_URL));
430 addProfileImages(imageUrlList);
431 imageUrlList.clear();
433 QVariant address = result.value("address");
434 if(!address.toString().isEmpty()) {
435 emit reverseGeoReady(address.toString());
437 QStringList coordinates;
438 coordinates.append(result.value("lat").toString());
439 coordinates.append(result.value("lon").toString());
441 emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
442 emit reverseGeoReady(coordinates.join(", "));
448 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
450 qDebug() << __PRETTY_FUNCTION__;
451 qDebug() << "Image URL: " << url << " size :" << image.size();
453 // assign facebook silhouette image to all who doesn't have a profile image
454 if(url == QUrl(SILHOUETTE_URL)) {
455 if(m_user->profileImageUrl().isEmpty()) {
456 m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
457 emit imageReady(m_user);
459 foreach(User *friendItem, m_friendsList) {
460 if(friendItem->profileImageUrl().isEmpty()) {
461 friendItem->setProfileImage(AvatarImage::create(image, AvatarImage::Small));
462 emit imageReady(friendItem);
467 if (m_user->profileImageUrl() == url) {
468 m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
469 emit imageReady(m_user);
472 foreach(User *friendItem, m_friendsList) {
473 if(friendItem->profileImageUrl() == url) {
474 friendItem->setProfileImage(AvatarImage::create(image, AvatarImage::Small));
475 emit imageReady(friendItem);
480 void SituareService::addProfileImages(const QList<QUrl> &imageUrlList)
482 qDebug() << __PRETTY_FUNCTION__;
484 foreach(QUrl url, imageUrlList) {
485 emit fetchImage(url);
489 void SituareService::clearUserData()
491 qDebug() << __PRETTY_FUNCTION__;
493 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
494 m_friendsList.clear();
500 emit userDataChanged(m_user, m_friendsList);