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 //Request sent to server does not need the UID
178 QByteArray arr = m_database->getNotifications(613374451);
180 parseMessagesData(arr);
183 void SituareService::fetchPeopleWithSimilarInterest(const GeoCoordinate &southWestCoordinates,
184 const GeoCoordinate &northEastCoordinates)
186 qDebug() << __PRETTY_FUNCTION__;
188 //Request sent to server does not need the UID
189 QByteArray arr = m_database->getInterestingPeople(613374451,
190 southWestCoordinates,
191 northEastCoordinates);
193 parseInterestingPeopleData(arr);
196 void SituareService::fetchPopularTags()
198 qDebug() << __PRETTY_FUNCTION__;
200 QByteArray arr = m_database->getPopularTags();
202 parsePopularTagsData(arr);
205 void SituareService::fetchLocations()
207 qDebug() << __PRETTY_FUNCTION__;
209 QHash<QString, QString> parameters;
210 parameters.insert("extra_user_data", NORMAL_SIZE_PROFILE_IMAGE);
212 buildRequest(GET_LOCATIONS, parameters);
215 SituareService::RequestName SituareService::getRequestName(const QUrl &url) const
217 qDebug() << __PRETTY_FUNCTION__;
219 if (url.toString().contains(GET_LOCATIONS))
220 return SituareService::RequestGetLocations;
221 else if (url.toString().contains(UPDATE_LOCATION))
222 return SituareService::RequestUpdateLocation;
223 else if (url.toString().contains(REVERSE_GEO))
224 return SituareService::RequestReverseGeo;
226 return SituareService::RequestUnknown;
229 QHash<QString, QString> SituareService::getTags(const QString &userId)
231 qDebug() << __PRETTY_FUNCTION__;
233 return m_database->getTags(userId.toInt());
236 void SituareService::imageReceived(const QString &id, const QPixmap &image)
238 qDebug() << __PRETTY_FUNCTION__;
240 if (m_user->userId() == id)
241 emit imageReady(QString(), AvatarImage::create(image, AvatarImage::Large));
243 emit imageReady(id, AvatarImage::create(image, AvatarImage::Small));
246 void SituareService::parseInterestingPeopleData(const QByteArray &jsonReply)
248 qDebug() << __PRETTY_FUNCTION__;
250 QJson::Parser parser;
253 QVariantMap result = parser.parse(jsonReply, &ok).toMap();
256 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
259 QVariant people = result["people"];
264 foreach (QVariant personVariant, people.toMap().value("friends").toList()) {
266 QMap<QString, QVariant> person = personVariant.toMap();
267 user.setUserId(person["uid"].toString());
268 user.setName(person["name"].toString());
269 user.setProfileImage(AvatarImage::create(
270 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
271 user.setProfileImageUrl(person["image_url"].toUrl());
272 user.setTags(person["tags"].toList());
275 qreal latitude = person["latitude"].toReal(&latOk);
277 qreal longitude = person["longitude"].toReal(&lonOk);
279 if (latOk && lonOk) {
280 user.setCoordinates(GeoCoordinate(latitude, longitude));
282 //This should be from the server
283 GeoCoordinate myCoord(65.008, 25.5523);
284 qreal meters = myCoord.distanceTo(user.coordinates());
294 user.setDistance(value, unit);
297 friends.append(user);
299 //Remove comment when the actual server is used
300 //emit fetchImage(user.userId(), user.profileImageUrl());
303 foreach (QVariant personVariant, people.toMap().value("others").toList()) {
305 QMap<QString, QVariant> person = personVariant.toMap();
306 user.setUserId(person["uid"].toString());
307 user.setName(person["name"].toString());
308 user.setProfileImage(AvatarImage::create(
309 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
310 user.setProfileImageUrl(person["image_url"].toUrl());
311 user.setTags(person["tags"].toList());
315 //Remove comment when the actual server is used
316 //emit fetchImage(user.userId(), user.profileImageUrl());
319 emit interestingPeopleReceived(friends, others);
323 void SituareService::parseReply(const QByteArray &jsonReply, RequestName requestName)
325 qDebug() << __PRETTY_FUNCTION__;
327 QJson::Parser parser;
330 QVariantMap result = parser.parse(jsonReply, &ok).toMap();
333 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
335 QVariant resultStatus = result["ResultStatus"];
336 QVariant resultData = result["ResultData"];
338 if (resultStatus.toString() == "ERROR") {
339 QVariantMap errorData = resultData.toMap();
340 emit error(ErrorContext::SITUARE, errorData["ErrorCode"].toInt());
341 } else if (resultStatus.toString() == "OK") {
342 if (requestName == SituareService::RequestGetLocations)
343 parseUserData(resultData);
344 else if (requestName == SituareService::RequestUpdateLocation)
345 emit updateWasSuccessful(SituareService::SuccessfulUpdateLocation);
346 else if (requestName == SituareService::RequestReverseGeo)
347 parseReverseGeoData(resultData);
352 void SituareService::parseReverseGeoData(const QVariant &reverseGeoData)
354 qDebug() << __PRETTY_FUNCTION__;
356 QVariantMap result = reverseGeoData.toMap();
358 if (result.contains("address") && !result["address"].toString().isEmpty()) {
359 emit reverseGeoReady(result["address"].toString());
361 QStringList coordinates;
362 coordinates.append(result["lat"].toString());
363 coordinates.append(result["lon"].toString());
364 emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
365 emit reverseGeoReady(coordinates.join(", "));
369 void SituareService::parseUserData(const QVariant &userData)
371 qDebug() << __PRETTY_FUNCTION__;
373 m_defaultImage = false;
375 QVariantMap result = userData.toMap();
377 if (result.contains("user")) {
379 QVariant userVariant = result.value("user");
380 QMap<QString, QVariant> userMap = userVariant.toMap();
382 GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
384 QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
386 if(imageUrl.isEmpty()) {
387 // user doesn't have profile image, so we need to get him a silhouette image
388 m_defaultImage = true;
391 QString address = userMap["address"].toString();
392 if(address.isEmpty()) {
393 QStringList location;
394 location.append(QString::number(coordinates.latitude()));
395 location.append(QString::number(coordinates.longitude()));
396 address = location.join(", ");
399 User user = User(address, coordinates, userMap["name"].toString(),
400 userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
401 true, userMap["uid"].toString());
403 if(imageUrl.isEmpty()) {
404 // user doesn't have profile image, so we need to get him a silhouette image
405 m_defaultImage = true;
406 user.setProfileImage(AvatarImage::create(
407 QPixmap(":/res/images/empty_avatar_big.png"), AvatarImage::Large));
410 QList<User> tmpFriendsList;
412 foreach (QVariant friendsVariant, result["friends"].toList()) {
413 QMap<QString, QVariant> friendMap = friendsVariant.toMap();
414 QVariant distance = friendMap["distance"];
415 QMap<QString, QVariant> distanceMap = distance.toMap();
417 GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
419 QUrl imageUrl = friendMap["profile_pic"].toUrl();
421 if(imageUrl.isEmpty()) {
422 // friend doesn't have profile image, so we need to get him a silhouette image
423 m_defaultImage = true;
426 QString address = friendMap["address"].toString();
427 if(address.isEmpty()) {
428 QStringList location;
429 location.append(QString::number(coordinates.latitude()));
430 location.append(QString::number(coordinates.longitude()));
431 address = location.join(", ");
434 User buddy = User(address, coordinates, friendMap["name"].toString(),
435 friendMap["note"].toString(), imageUrl,
436 friendMap["timestamp"].toString(),
437 false, friendMap["uid"].toString(), distanceMap["units"].toString(),
438 distanceMap["value"].toDouble());
440 if(imageUrl.isEmpty()) {
441 // friend doesn't have profile image, so we need to get him a silhouette image
442 m_defaultImage = true;
443 buddy.setProfileImage(AvatarImage::create(
444 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
447 tmpFriendsList.append(buddy);
450 QHash<QString, QUrl> imageUrlList; // url list for images
452 // set unchanged profile images or add new images to imageUrlList for downloading
454 if(m_user->profileImageUrl() != user.profileImageUrl()) {
455 if(!user.profileImageUrl().isEmpty())
456 imageUrlList.insert(user.userId(), user.profileImageUrl());
458 user.setProfileImage(m_user->profileImage());
461 if(!user.profileImageUrl().isEmpty())
462 imageUrlList.insert(user.userId(), user.profileImageUrl());
465 // clear old user object
471 // create new user object from temporary user object
472 m_user = new User(user);
474 // set unchanged profile images or add new images to imageUrlList for downloading
475 if(!m_friendsList.isEmpty()) {
476 foreach(User tmpBuddy, tmpFriendsList) {
477 if(!tmpBuddy.profileImageUrl().isEmpty()) {
479 foreach(User *buddy, m_friendsList) {
480 if(tmpBuddy.profileImageUrl() == buddy->profileImageUrl()) {
481 tmpBuddy.setProfileImage(buddy->profileImage());
486 if(!found && !tmpBuddy.profileImageUrl().isEmpty())
487 imageUrlList.insert(tmpBuddy.userId(), tmpBuddy.profileImageUrl());
491 foreach(User buddy, tmpFriendsList) {
492 if(!buddy.profileImageUrl().isEmpty())
493 imageUrlList.insert(buddy.userId(), buddy.profileImageUrl());
497 // clear old friendlist
498 qDeleteAll(m_friendsList.begin(), m_friendsList.end());
499 m_friendsList.clear();
501 // populate new friendlist with temporary friendlist's data
502 foreach(User tmpFriendItem, tmpFriendsList) {
503 User *friendItem = new User(tmpFriendItem);
504 m_friendsList.append(friendItem);
506 tmpFriendsList.clear();
508 //REMOVE WHEN NOT NEEDED! get user tags and set tags to the user
509 m_user->setTags(getTags(m_user->userId()));
511 emit userDataChanged(m_user, m_friendsList);
513 // set silhouette image to imageUrlList for downloading
515 imageUrlList.insert("", QUrl(SILHOUETTE_URL));
517 addProfileImages(imageUrlList);
518 imageUrlList.clear();
522 void SituareService::parseMessagesData(const QByteArray &jsonReply)
524 QJson::Parser parser;
527 QVariantMap result = parser.parse(jsonReply, &ok).toMap();
530 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
533 QVariant messages = result["messages"];
535 QList<Message> received;
538 foreach (QVariant messageVariant, messages.toMap().value("received").toList()) {
539 Message message(Message::MessageTypeReceived);
540 QMap<QString, QVariant> messageMap = messageVariant.toMap();
541 message.setId(messageMap["id"].toString());
542 message.setSenderId(messageMap["sender_id"].toString());
543 message.setReceiverId(messageMap["receiver_id"].toString());
544 message.setSenderName(messageMap["sender_name"].toString());
545 uint timestampSeconds = messageMap["timestamp"].toUInt();
546 message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
547 message.setText(messageMap["text"].toString());
548 message.setImage(AvatarImage::create(
549 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
552 qreal latitude = messageMap["latitude"].toReal(&latOk);
554 qreal longitude = messageMap["longitude"].toReal(&lonOk);
556 if (latOk && lonOk) {
557 message.setAddress(messageMap["address"].toString());
558 message.setCoordinates(GeoCoordinate(latitude, longitude));
561 received.append(message);
563 //emit fetchImage(message.id(), messageMap["image_url"].toString());
566 foreach (QVariant messageVariant, messages.toMap().value("sent").toList()) {
567 Message message(Message::MessageTypeSent);
568 QMap<QString, QVariant> messageMap = messageVariant.toMap();
569 message.setId(messageMap["id"].toString());
570 message.setSenderId(messageMap["sender_id"].toString());
571 message.setReceiverId(messageMap["receiver_id"].toString());
572 message.setSenderName(messageMap["sender_name"].toString());
573 uint timestampSeconds = messageMap["timestamp"].toUInt();
574 message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
575 message.setText(messageMap["text"].toString());
576 message.setImage(AvatarImage::create(
577 QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
580 qreal latitude = messageMap["latitude"].toReal(&latOk);
582 qreal longitude = messageMap["longitude"].toReal(&lonOk);
584 if (latOk && lonOk) {
585 message.setAddress(messageMap["address"].toString());
586 message.setCoordinates(GeoCoordinate(latitude, longitude));
589 sent.append(message);
591 //emit fetchImage(message.id(), messageMap["image_url"].toString());
594 emit messagesReceived(received, sent);
598 void SituareService::parsePopularTagsData(const QByteArray &jsonReply)
600 qDebug() << __PRETTY_FUNCTION__;
602 QJson::Parser parser;
605 QVariantMap result = parser.parse(jsonReply, &ok).toMap();
608 emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
611 QHash<QString, QString> popularTags;
613 foreach (QVariant tagVariant, result["popular_tags"].toList()) {
614 QMap<QString, QVariant> tag = tagVariant.toMap();
615 popularTags.insert(tag["id"].toString(), tag["name"].toString());
618 emit popularTagsReceived(popularTags);
622 void SituareService::removeMessage(const QString &id)
624 qDebug() << __PRETTY_FUNCTION__;
626 if (m_database->removeMessage(613374451, id))
627 emit updateWasSuccessful(SituareService::SuccessfulRemoveMessage);
631 void SituareService::removeTags(const QStringList &tags)
633 qDebug() << __PRETTY_FUNCTION__;
635 if (m_database->removeTags(613374451, tags))
636 emit updateWasSuccessful(SituareService::SuccessfulRemoveTags);
639 void SituareService::requestFinished(QNetworkReply *reply)
641 qDebug() << __PRETTY_FUNCTION__;
644 if (m_currentRequests.contains(reply)) {
647 emit error(ErrorContext::NETWORK, reply->error());
649 parseReply(reply->readAll(), getRequestName(reply->url()));
651 m_currentRequests.removeAll(reply);
652 reply->deleteLater();
656 void SituareService::reverseGeo(const GeoCoordinate &coordinates)
658 qDebug() << __PRETTY_FUNCTION__;
660 QHash<QString, QString> parameters;
661 parameters.insert("lat", degreesToString(coordinates.latitude()));
662 parameters.insert("lon", degreesToString(coordinates.longitude()));
663 parameters.insert("format", "json");
665 buildRequest(REVERSE_GEO, parameters);
668 void SituareService::searchPeopleByTag(const QString &tag)
670 qDebug() << __PRETTY_FUNCTION__;
672 QByteArray arr = m_database->getInterestingPeopleByTag(613374451, tag);
674 parseInterestingPeopleData(arr);
677 void SituareService::sendMessage(const QString &receiverId, const QString &message,
678 const GeoCoordinate &coordinates)
680 qDebug() << __PRETTY_FUNCTION__;
682 if (m_database->sendMessage(613374451, receiverId.toULongLong(), message, coordinates))
683 emit updateWasSuccessful(SituareService::SuccessfulSendMessage);
686 void SituareService::sendRequest(const QString &requestUrl)
688 qDebug() << __PRETTY_FUNCTION__ << "requestUrl" << requestUrl;
690 // make and send the request
691 QNetworkRequest request;
692 request.setUrl(QUrl(requestUrl));
693 request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
694 QNetworkReply *reply = m_networkManager->get(request, true);
695 m_currentRequests.append(reply);
698 void SituareService::updateSession(const QString &session)
700 qDebug() << __PRETTY_FUNCTION__;
704 if (m_session.isEmpty())
708 void SituareService::updateLocation(const GeoCoordinate &coordinates, const QString &status,
711 qDebug() << __PRETTY_FUNCTION__;
713 QHash<QString, QString> parameters;
714 parameters.insert("lat", degreesToString(coordinates.latitude()));
715 parameters.insert("lon", degreesToString(coordinates.longitude()));
716 parameters.insert("publish", publish ? "true" : "false");
717 parameters.insert("data", status); ///< @todo if !empty ???
719 buildRequest(UPDATE_LOCATION, parameters);