2 Situare - A location system for Facebook
3 Copyright (C) 2010 Ixonos Plc. Authors:
5 Henri Lampela - henri.lampela@ixonos.com
6 Sami Rämö - sami.ramo@ixonos.com
8 Situare is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License
10 version 2 as published by the Free Software Foundation.
12 Situare is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Situare; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
23 #include <qjson/parser.h>
26 #include <QtNetwork/QNetworkReply>
28 #include <QStringList>
29 #include <QtAlgorithms>
34 #include "network/networkaccessmanager.h"
35 #include "situarecommon.h"
36 #include "ui/avatarimage.h"
38 #include "situareservice.h"
40 SituareService::SituareService(NetworkAccessManager *networkManager, ImageFetcher *imageFetcher,
45 qDebug() << __PRETTY_FUNCTION__;
47 m_networkManager = networkManager;
48 connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
49 this, SLOT(requestFinished(QNetworkReply*)), Qt::QueuedConnection);
51 m_imageFetcher = imageFetcher;
52 connect(this, SIGNAL(fetchImage(QString, QUrl)),
53 m_imageFetcher, SLOT(fetchImage(QString, QUrl)));
54 connect(m_imageFetcher, SIGNAL(imageReceived(QString,QPixmap)),
55 this, SLOT(imageReceived(QString,QPixmap)));
56 connect(m_imageFetcher, SIGNAL(error(int, int)),
57 this, SIGNAL(error(int, int)));
59 m_database = new Database(this);
60 m_database->openDatabase();
61 m_database->createNotificationTable();
62 m_database->createUserTable();
63 m_database->createTagTable();
64 m_database->createUserTagTable();
67 SituareService::~SituareService()
69 qDebug() << __PRETTY_FUNCTION__;
76 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
77 m_friendsList.clear();
80 void SituareService::addProfileImages(const QHash<QString, QUrl> &imageUrlList)
82 qDebug() << __PRETTY_FUNCTION__;
84 QHashIterator<QString, QUrl> imageUrlListIterator(imageUrlList);
86 while (imageUrlListIterator.hasNext()) {
87 imageUrlListIterator.next();
88 emit fetchImage(imageUrlListIterator.key(), imageUrlListIterator.value());
92 void SituareService::addTags(const QStringList &tags)
94 qWarning() << __PRETTY_FUNCTION__ << tags.count();
96 foreach (QString tag, tags)
97 m_database->addTag(613374451, tag);
99 emit updateWasSuccessful(SituareService::SuccessfulAddTags);
102 void SituareService::appendAccessToken(QString &requestUrl)
104 qDebug() << __PRETTY_FUNCTION__;
106 requestUrl.append(m_session);
109 void SituareService::buildRequest(const QString &script, const QHash<QString, QString> ¶meters)
111 qDebug() << __PRETTY_FUNCTION__;
113 const QString PARAMETER_KEY_API = "api";
114 const QString PARAMETER_VALUE_API = "2.0";
116 QString url = SITUARE_URL;
120 // append default api version parameter if not yet specified
121 if (!parameters.contains(PARAMETER_KEY_API))
122 url.append(PARAMETER_KEY_API + "=" + PARAMETER_VALUE_API + "&");
125 if (!parameters.isEmpty()) {
126 QHash<QString, QString>::const_iterator i = parameters.constBegin();
127 while (i != parameters.constEnd()) {
130 url.append(i.value());
136 /// @todo BUG: Url parameter strings are not url escaped
138 // qWarning() << __PRETTY_FUNCTION__ << "request url with parameters:" << url;
140 if (!m_session.isEmpty()) {
141 appendAccessToken(url);
144 emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
148 void SituareService::clearUserData()
150 qDebug() << __PRETTY_FUNCTION__;
152 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
153 m_friendsList.clear();
159 emit userDataChanged(m_user, m_friendsList);
162 QString SituareService::degreesToString(double degrees)
164 qDebug() << __PRETTY_FUNCTION__;
166 // one scene pixel is about 5.4e-6 degrees, the integer part is max three digits and one
167 // additional digit is added for maximum precision
168 const int PRECISION = 10;
170 return QString::number(degrees, 'f', PRECISION);
173 void SituareService::fetchMessages()
175 qDebug() << __PRETTY_FUNCTION__;
177 buildRequest(GET_MESSAGES, QHash<QString, QString>());
180 void SituareService::fetchPeopleWithSimilarInterest(const qreal distance)
182 qDebug() << __PRETTY_FUNCTION__;
184 const int TO_KM_DIVIDER = 1000;
185 QHash<QString, QString> parameters;
186 parameters.insert("distance", degreesToString(distance / TO_KM_DIVIDER));
188 buildRequest(GET_PEOPLE_WITH_SIMILAR_INTEREST, parameters);
191 void SituareService::fetchPopularTags()
193 qDebug() << __PRETTY_FUNCTION__;
195 QByteArray arr = m_database->getPopularTags();
197 parsePopularTagsData(arr);
200 void SituareService::fetchLocations()
202 qDebug() << __PRETTY_FUNCTION__;
204 QHash<QString, QString> parameters;
205 parameters.insert("extra_user_data", NORMAL_SIZE_PROFILE_IMAGE);
207 buildRequest(GET_LOCATIONS, parameters);
210 SituareService::RequestName SituareService::getRequestName(const QUrl &url) const
212 qDebug() << __PRETTY_FUNCTION__;
214 if (url.toString().contains(GET_LOCATIONS))
215 return SituareService::RequestGetLocations;
216 else if (url.toString().contains(UPDATE_LOCATION))
217 return SituareService::RequestUpdateLocation;
218 else if (url.toString().contains(REVERSE_GEO))
219 return SituareService::RequestReverseGeo;
220 else if (url.toString().contains(GET_MESSAGES))
221 return SituareService::RequestGetMessages;
222 else if (url.toString().contains(REMOVE_MESSAGE))
223 return SituareService::RequestRemoveMessage;
224 else if (url.toString().contains(SEND_MESSAGE))
225 return SituareService::RequestSendMessage;
226 else if (url.toString().contains(GET_PEOPLE_WITH_SIMILAR_INTEREST))
227 return SituareService::RequestGetPeopleWithSimilarInterest;
229 return SituareService::RequestUnknown;
232 QHash<QString, QString> SituareService::getTags(const QString &userId)
234 qDebug() << __PRETTY_FUNCTION__;
236 return m_database->getTags(userId.toInt());
239 void SituareService::imageReceived(const QString &id, const QPixmap &image)
241 qDebug() << __PRETTY_FUNCTION__;
243 if (m_user->userId() == id)
244 emit imageReady(QString(), AvatarImage::create(image, AvatarImage::Large));
246 emit imageReady(id, AvatarImage::create(image, AvatarImage::Small));
249 void SituareService::parseInterestingPeopleData(const QVariant &interestingPeopleData)
251 qDebug() << __PRETTY_FUNCTION__;
253 QVariant people = interestingPeopleData.toMap();
258 foreach (QVariant personVariant, people.toMap().value("friends").toList()) {
260 QMap<QString, QVariant> person = personVariant.toMap();
261 user.setUserId(person["uid"].toString());
262 user.setName(person["name"].toString());
263 user.setProfileImage(AvatarImage::create(
264 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
265 user.setProfileImageUrl(person["pic_square"].toUrl());
266 user.setTimestamp(person["timestamp"].toString());
267 user.setTags(person["tags"].toString());
268 user.setAddress(person["address"].toString());
269 user.setNote(person["note"].toString());
272 qreal latitude = person["lat"].toReal(&latOk);
274 qreal longitude = person["lon"].toReal(&lonOk);
276 if (latOk && lonOk) {
277 user.setCoordinates(GeoCoordinate(latitude, longitude));
279 qreal meters = person["distance"].toReal() * 1000;
289 user.setDistance(value, unit);
292 friends.append(user);
294 //Remove comment when the actual server is used
295 //emit fetchImage(user.userId(), user.profileImageUrl());
298 foreach (QVariant personVariant, people.toMap().value("others").toList()) {
300 QMap<QString, QVariant> person = personVariant.toMap();
301 user.setUserId(person["uid"].toString());
302 user.setName(person["name"].toString());
303 user.setProfileImage(AvatarImage::create(
304 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
305 user.setProfileImageUrl(person["pic_square"].toUrl());
306 user.setTimestamp(person["timestamp"].toString());
307 user.setTags(person["tags"].toString());
311 emit fetchImage(user.userId(), user.profileImageUrl());
314 emit interestingPeopleReceived(friends, others);
317 void SituareService::parseReply(const QByteArray &jsonReply, RequestName requestName)
319 qDebug() << __PRETTY_FUNCTION__ << jsonReply;
321 QJson::Parser parser;
324 QVariantMap result = parser.parse(jsonReply, &ok).toMap();
327 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
329 QVariant resultStatus = result["ResultStatus"];
330 QVariant resultData = result["ResultData"];
332 if (resultStatus.toString() == "ERROR") {
333 QVariantMap errorData = resultData.toMap();
334 emit error(ErrorContext::SITUARE, errorData["ErrorCode"].toInt());
335 } else if (resultStatus.toString() == "OK") {
336 if (requestName == SituareService::RequestGetLocations)
337 parseUserData(resultData);
338 else if (requestName == SituareService::RequestUpdateLocation)
339 emit updateWasSuccessful(SituareService::SuccessfulUpdateLocation);
340 else if (requestName == SituareService::RequestRemoveMessage)
341 emit updateWasSuccessful(SituareService::SuccessfulRemoveMessage);
342 else if (requestName == SituareService::RequestReverseGeo)
343 parseReverseGeoData(resultData);
344 else if (requestName == SituareService::RequestGetMessages)
345 parseMessagesData(resultData);
346 else if (requestName == SituareService::RequestSendMessage)
347 emit updateWasSuccessful((SituareService::SuccessfulSendMessage));
348 else if (requestName == SituareService::RequestGetPeopleWithSimilarInterest)
349 parseInterestingPeopleData(resultData);
354 void SituareService::parseReverseGeoData(const QVariant &reverseGeoData)
356 qDebug() << __PRETTY_FUNCTION__;
358 QVariantMap result = reverseGeoData.toMap();
360 if (result.contains("address") && !result["address"].toString().isEmpty()) {
361 emit reverseGeoReady(result["address"].toString());
363 QStringList coordinates;
364 coordinates.append(result["lat"].toString());
365 coordinates.append(result["lon"].toString());
366 emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
367 emit reverseGeoReady(coordinates.join(", "));
371 void SituareService::parseUserData(const QVariant &userData)
373 qDebug() << __PRETTY_FUNCTION__;
375 m_defaultImage = false;
377 QVariantMap result = userData.toMap();
379 if (result.contains("user")) {
381 QVariant userVariant = result.value("user");
382 QMap<QString, QVariant> userMap = userVariant.toMap();
384 GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
386 QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
388 if(imageUrl.isEmpty()) {
389 // user doesn't have profile image, so we need to get him a silhouette image
390 m_defaultImage = true;
393 QString address = userMap["address"].toString();
394 if(address.isEmpty()) {
395 QStringList location;
396 location.append(QString::number(coordinates.latitude()));
397 location.append(QString::number(coordinates.longitude()));
398 address = location.join(", ");
401 User user = User(address, coordinates, userMap["name"].toString(),
402 userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
403 true, userMap["uid"].toString());
405 if(imageUrl.isEmpty()) {
406 // user doesn't have profile image, so we need to get him a silhouette image
407 m_defaultImage = true;
408 user.setProfileImage(AvatarImage::create(
409 QPixmap(":/res/images/empty_avatar_big.png"), AvatarImage::Large));
412 QList<User> tmpFriendsList;
414 foreach (QVariant friendsVariant, result["friends"].toList()) {
415 QMap<QString, QVariant> friendMap = friendsVariant.toMap();
416 QVariant distance = friendMap["distance"];
417 QMap<QString, QVariant> distanceMap = distance.toMap();
419 GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
421 QUrl imageUrl = friendMap["profile_pic"].toUrl();
423 if(imageUrl.isEmpty()) {
424 // friend doesn't have profile image, so we need to get him a silhouette image
425 m_defaultImage = true;
428 QString address = friendMap["address"].toString();
429 if(address.isEmpty()) {
430 QStringList location;
431 location.append(QString::number(coordinates.latitude()));
432 location.append(QString::number(coordinates.longitude()));
433 address = location.join(", ");
436 User buddy = User(address, coordinates, friendMap["name"].toString(),
437 friendMap["note"].toString(), imageUrl,
438 friendMap["timestamp"].toString(),
439 false, friendMap["uid"].toString(), distanceMap["units"].toString(),
440 distanceMap["value"].toDouble());
442 if(imageUrl.isEmpty()) {
443 // friend doesn't have profile image, so we need to get him a silhouette image
444 m_defaultImage = true;
445 buddy.setProfileImage(AvatarImage::create(
446 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
449 tmpFriendsList.append(buddy);
452 QHash<QString, QUrl> imageUrlList; // url list for images
454 // set unchanged profile images or add new images to imageUrlList for downloading
456 if(m_user->profileImageUrl() != user.profileImageUrl()) {
457 if(!user.profileImageUrl().isEmpty())
458 imageUrlList.insert(user.userId(), user.profileImageUrl());
460 user.setProfileImage(m_user->profileImage());
463 if(!user.profileImageUrl().isEmpty())
464 imageUrlList.insert(user.userId(), user.profileImageUrl());
467 // clear old user object
473 // create new user object from temporary user object
474 m_user = new User(user);
476 // set unchanged profile images or add new images to imageUrlList for downloading
477 if(!m_friendsList.isEmpty()) {
478 foreach(User tmpBuddy, tmpFriendsList) {
479 if(!tmpBuddy.profileImageUrl().isEmpty()) {
481 foreach(User *buddy, m_friendsList) {
482 if(tmpBuddy.profileImageUrl() == buddy->profileImageUrl()) {
483 tmpBuddy.setProfileImage(buddy->profileImage());
488 if(!found && !tmpBuddy.profileImageUrl().isEmpty())
489 imageUrlList.insert(tmpBuddy.userId(), tmpBuddy.profileImageUrl());
493 foreach(User buddy, tmpFriendsList) {
494 if(!buddy.profileImageUrl().isEmpty())
495 imageUrlList.insert(buddy.userId(), buddy.profileImageUrl());
499 // clear old friendlist
500 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
501 m_friendsList.clear();
503 // populate new friendlist with temporary friendlist's data
504 foreach(User tmpFriendItem, tmpFriendsList) {
505 User *friendItem = new User(tmpFriendItem);
506 m_friendsList.append(friendItem);
508 tmpFriendsList.clear();
510 //REMOVE WHEN NOT NEEDED! get user tags and set tags to the user
511 m_user->setTags(getTags(m_user->userId()));
513 emit userDataChanged(m_user, m_friendsList);
515 // set silhouette image to imageUrlList for downloading
517 imageUrlList.insert("", QUrl(SILHOUETTE_URL));
519 addProfileImages(imageUrlList);
520 imageUrlList.clear();
524 void SituareService::parseMessagesData(const QVariant &messagesData)
526 QVariantMap result = messagesData.toMap();
528 QList<Message> received;
531 foreach (QVariant messageVariant, result["received"].toList()) {
532 Message message(Message::MessageTypeReceived);
533 QMap<QString, QVariant> messageMap = messageVariant.toMap();
534 message.setId(messageMap["mid"].toString());
535 message.setSenderId(messageMap["sid"].toString());
536 message.setReceiverId(messageMap["rid"].toString());
537 message.setSenderName(messageMap["name"].toString());
538 uint timestampSeconds = messageMap["timestamp"].toUInt();
539 message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
540 message.setText(messageMap["message"].toString());
541 message.setImage(AvatarImage::create(
542 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
545 qreal latitude = messageMap["lat"].toReal(&latOk);
547 qreal longitude = messageMap["lon"].toReal(&lonOk);
549 if (latOk && lonOk) {
550 message.setAddress(messageMap["address"].toString());
551 message.setCoordinates(GeoCoordinate(latitude, longitude));
554 received.append(message);
556 emit fetchImage(message.id(), messageMap["pic_square"].toString());
559 foreach (QVariant messageVariant, result["sent"].toList()) {
560 Message message(Message::MessageTypeSent);
561 QMap<QString, QVariant> messageMap = messageVariant.toMap();
562 message.setId(messageMap["mid"].toString());
563 message.setSenderId(messageMap["sid"].toString());
564 message.setReceiverId(messageMap["rid"].toString());
565 message.setSenderName(messageMap["name"].toString());
566 uint timestampSeconds = messageMap["timestamp"].toUInt();
567 message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
568 message.setText(messageMap["message"].toString());
569 message.setImage(AvatarImage::create(
570 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
573 qreal latitude = messageMap["lat"].toReal(&latOk);
575 qreal longitude = messageMap["lon"].toReal(&lonOk);
577 if (latOk && lonOk) {
578 message.setAddress(messageMap["address"].toString());
579 message.setCoordinates(GeoCoordinate(latitude, longitude));
582 sent.append(message);
584 emit fetchImage(message.id(), messageMap["pic_square"].toString());
587 emit messagesReceived(received, sent);
590 void SituareService::parsePopularTagsData(const QByteArray &jsonReply)
592 qDebug() << __PRETTY_FUNCTION__;
594 QJson::Parser parser;
597 QVariantMap result = parser.parse(jsonReply, &ok).toMap();
600 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
603 QHash<QString, QString> popularTags;
605 foreach (QVariant tagVariant, result["popular_tags"].toList()) {
606 QMap<QString, QVariant> tag = tagVariant.toMap();
607 popularTags.insert(tag["id"].toString(), tag["name"].toString());
610 emit popularTagsReceived(popularTags);
614 void SituareService::removeMessage(const QString &id)
616 qDebug() << __PRETTY_FUNCTION__;
618 QHash<QString, QString> parameters;
619 parameters.insert("mid", id);
621 buildRequest(REMOVE_MESSAGE, parameters);
625 void SituareService::removeTags(const QStringList &tags)
627 qDebug() << __PRETTY_FUNCTION__;
629 if (m_database->removeTags(613374451, tags))
630 emit updateWasSuccessful(SituareService::SuccessfulRemoveTags);
633 void SituareService::requestFinished(QNetworkReply *reply)
635 qDebug() << __PRETTY_FUNCTION__;
638 if (m_currentRequests.contains(reply)) {
640 emit error(ErrorContext::NETWORK, reply->error());
642 parseReply(reply->readAll(), getRequestName(reply->url()));
644 m_currentRequests.removeAll(reply);
645 reply->deleteLater();
649 void SituareService::reverseGeo(const GeoCoordinate &coordinates)
651 qDebug() << __PRETTY_FUNCTION__;
653 QHash<QString, QString> parameters;
654 parameters.insert("lat", degreesToString(coordinates.latitude()));
655 parameters.insert("lon", degreesToString(coordinates.longitude()));
656 parameters.insert("format", "json");
658 buildRequest(REVERSE_GEO, parameters);
661 void SituareService::searchPeopleByTag(const QString &tag)
663 qDebug() << __PRETTY_FUNCTION__;
665 QByteArray arr = m_database->getInterestingPeopleByTag(613374451, tag);
667 parseInterestingPeopleData(arr);
670 void SituareService::sendMessage(const QString &receiverId, const QString &message,
671 const GeoCoordinate &coordinates)
673 qDebug() << __PRETTY_FUNCTION__;
675 QHash<QString, QString> parameters;
676 parameters.insert("rid", receiverId);
677 parameters.insert("message", message);
679 if (coordinates.isValid()) {
680 parameters.insert("lat", degreesToString(coordinates.latitude()));
681 parameters.insert("lon", degreesToString(coordinates.longitude()));
684 buildRequest(SEND_MESSAGE, parameters);
687 void SituareService::sendRequest(const QString &requestUrl)
689 qDebug() << __PRETTY_FUNCTION__ << "requestUrl" << requestUrl;
691 // make and send the request
692 QNetworkRequest request;
693 request.setUrl(QUrl(requestUrl));
694 request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
695 QNetworkReply *reply = m_networkManager->get(request, true);
696 m_currentRequests.append(reply);
699 void SituareService::updateSession(const QString &session)
701 qDebug() << __PRETTY_FUNCTION__;
705 if (m_session.isEmpty())
709 void SituareService::updateLocation(const GeoCoordinate &coordinates, const QString &status,
712 qDebug() << __PRETTY_FUNCTION__;
714 QHash<QString, QString> parameters;
715 parameters.insert("lat", degreesToString(coordinates.latitude()));
716 parameters.insert("lon", degreesToString(coordinates.longitude()));
717 parameters.insert("publish", publish ? "true" : "false");
718 parameters.insert("data", status); ///< @todo if !empty ???
720 buildRequest(UPDATE_LOCATION, parameters);