USA.
*/
+#include "parser.h"
+
#include <QtAlgorithms>
#include <QDebug>
-#include <QtGlobal>
-#include <QStringList>
-#include <QPixmap>
#include <QNetworkReply>
-#include "situareservice.h"
+#include <QPixmap>
+#include <QStringList>
+#include <QtGlobal>
+
+#include "database.h"
+#include "error.h"
+#include "network/networkaccessmanager.h"
#include "situarecommon.h"
-#include "common.h"
-#include "parser.h"
#include "ui/avatarimage.h"
-#include "network/networkaccessmanager.h"
+
+#include "situareservice.h"
SituareService::SituareService(QObject *parent)
: QObject(parent),
{
qDebug() << __PRETTY_FUNCTION__;
- m_networkManager = NetworkAccessManager::instance();
+ m_networkManager = new NetworkAccessManager(this);
connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
- this, SLOT(requestFinished(QNetworkReply*)));
-
- m_imageFetcher = new ImageFetcher(NetworkAccessManager::instance(), this);
- connect(this, SIGNAL(fetchImage(QUrl)),
- m_imageFetcher, SLOT(fetchImage(QUrl)));
- connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)),
- this, SLOT(imageReceived(QUrl, QPixmap)));
- connect(m_imageFetcher, SIGNAL(error(QString)),
- this, SIGNAL(error(QString)));
+ this, SLOT(requestFinished(QNetworkReply*)), Qt::QueuedConnection);
+
+ m_imageFetcher = new ImageFetcher(new NetworkAccessManager(this), this);
+ connect(this, SIGNAL(fetchImage(QString, QUrl)),
+ m_imageFetcher, SLOT(fetchImage(QString, QUrl)));
+ connect(m_imageFetcher, SIGNAL(imageReceived(QString,QPixmap)),
+ this, SLOT(imageReceived(QString,QPixmap)));
+ connect(m_imageFetcher, SIGNAL(error(int, int)),
+ this, SIGNAL(error(int, int)));
+
+ m_database = new Database(this);
+ m_database->openDatabase();
+ m_database->createNotificationTable();
+ m_database->createUserTable();
+ m_database->createTagTable();
+ m_database->createUserTagTable();
}
SituareService::~SituareService()
m_friendsList.clear();
}
+void SituareService::fetchNotifications()
+{
+ qDebug() << __PRETTY_FUNCTION__;
+
+// QList<Notification*> notifications = m_database->getNotifications(m_user->userId().toULongLong());
+
+// foreach (Notification *notification, notifications) {
+// notification->setImage(AvatarImage::create(QPixmap(":/res/images/empty_avatar.png"),
+// AvatarImage::Small));
+// }
+
+// foreach (User *user, m_friendsList) {
+// foreach (Notification *notification, notifications)
+// if (notification->senderId() == user->userId())
+// notification->setImage(user->profileImage());
+// }
+
+// emit notificationsReceived(notifications);
+
+ QByteArray arr = m_database->getNotifications(m_user->userId().toULongLong());
+
+ parseNotificationsData(arr);
+}
+
+void SituareService::fetchPeopleWithSimilarInterest(const GeoCoordinate &southWestCoordinates,
+ const GeoCoordinate &northEastCoordinates)
+{
+ qDebug() << __PRETTY_FUNCTION__;
+
+ QByteArray arr = m_database->getInterestingPeople(m_user->userId().toULongLong(),
+ southWestCoordinates,
+ northEastCoordinates);
+
+ parseInterestingPeopleData(arr);
+}
+
void SituareService::fetchLocations()
{
qDebug() << __PRETTY_FUNCTION__;
sendRequest(url, COOKIE, cookie);
}
-void SituareService::reverseGeo(const QPointF &coordinates)
+void SituareService::reverseGeo(const GeoCoordinate &coordinates)
{
qDebug() << __PRETTY_FUNCTION__;
m_credentials.sig(), EN_LOCALE);
QString urlParameters = formUrlParameters(coordinates);
+ urlParameters.append(JSON_FORMAT);
QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
sendRequest(url, COOKIE, cookie);
}
-void SituareService::updateLocation(const QPointF &coordinates, const QString &status,
+void SituareService::updateLocation(const GeoCoordinate &coordinates, const QString &status,
const bool &publish)
{
qDebug() << __PRETTY_FUNCTION__;
+ QString urlParameters = formUrlParameters(coordinates, status, publish);
+ QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
+
QString cookie = formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
m_credentials.sessionKey(), m_credentials.sessionSecret(),
m_credentials.sig(), EN_LOCALE);
-
- QString publishValue;
- if(publish) {
- publishValue = PUBLISH_TRUE;
- }
- else {
- publishValue = PUBLISH_FALSE;
- }
- QString urlParameters = formUrlParameters(coordinates, status, publishValue);
- QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
-
sendRequest(url, COOKIE, cookie);
}
return url;
}
-QString SituareService::formUrlParameters(const QPointF &coordinates, QString status,
- QString publish)
+QString SituareService::formUrlParameters(const GeoCoordinate &coordinates, QString status,
+ bool publish)
{
+ qDebug() << __PRETTY_FUNCTION__;
+
+ // one scene pixel is about 5.4e-6 degrees, the integer part is max three digits and one
+ // additional digit is added for maximum precision
+ const int COORDINATE_PRECISION = 10;
+
QString parameters;
parameters.append(QUESTION_MARK);
parameters.append(LATITUDE);
parameters.append(EQUAL_MARK);
- parameters.append(QString::number(coordinates.y()));
+ parameters.append(QString::number(coordinates.latitude(), 'f', COORDINATE_PRECISION));
parameters.append(AMBERSAND_MARK);
parameters.append(LONGTITUDE);
parameters.append(EQUAL_MARK);
- parameters.append(QString::number(coordinates.x()));
+ parameters.append(QString::number(coordinates.longitude(), 'f', COORDINATE_PRECISION));
- if(publish.compare(PUBLISH_TRUE) == 0) {
- parameters.append(AMBERSAND_MARK);
- parameters.append(PUBLISH);
- parameters.append(EQUAL_MARK);
+ parameters.append(AMBERSAND_MARK);
+ parameters.append(PUBLISH);
+ parameters.append(EQUAL_MARK);
+
+ if(publish)
parameters.append(PUBLISH_TRUE);
- } else if(publish.compare(PUBLISH_FALSE) == 0) {
- parameters.append(AMBERSAND_MARK);
- parameters.append(PUBLISH);
- parameters.append(EQUAL_MARK);
+ else
parameters.append(PUBLISH_FALSE);
- }
if(!status.isEmpty()) {
parameters.append(AMBERSAND_MARK);
request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
- QNetworkReply *reply = m_networkManager->get(request);
+ QNetworkReply *reply = m_networkManager->get(request, true);
m_currentRequests.append(reply);
}
//Reply from situare
if (m_currentRequests.contains(reply)) {
- QUrl url = reply->url();
qDebug() << "BytesAvailable: " << reply->bytesAvailable();
if (reply->error()) {
- emit error(reply->errorString());
- emit error("Terve");
- qDebug() << "TMP MESSAGE VILLE";
+ emit error(ErrorContext::NETWORK, reply->error());
} else {
- qint64 max = reply->size();
- QByteArray replyArray = reply->read(max);
- qDebug() << "Reply from: " << url << "reply " << replyArray;
+ QByteArray replyArray = reply->readAll();
+ qDebug() << "Reply from: " << reply->url() << "reply " << replyArray;
if(replyArray == ERROR_LAT.toAscii()) {
qDebug() << "Error: " << ERROR_LAT;
- emit error(UPDATE_FAILED);
+ emit error(ErrorContext::SITUARE, SituareError::UPDATE_FAILED);
} else if(replyArray == ERROR_LON.toAscii()) {
qDebug() << "Error: " << ERROR_LON;
- emit error(UPDATE_FAILED);
+ emit error(ErrorContext::SITUARE, SituareError::UPDATE_FAILED);
} else if(replyArray.contains(ERROR_SESSION.toAscii())) {
qDebug() << "Error: " << ERROR_SESSION;
- emit error(SESSION_EXPIRED);
+ emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
} else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
qDebug() << "JSON string";
parseUserData(replyArray);
} else if(replyArray.isEmpty()) {
- if(url.toString().contains(UPDATE_LOCATION.toAscii())) {
+ if(reply->url().toString().contains(UPDATE_LOCATION.toAscii())) {
emit updateWasSuccessful();
} else {
// session credentials are invalid
- emit error(SESSION_EXPIRED);
+ emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
}
} else {
- // Street address ready
- QString address = QString::fromUtf8(replyArray);
- emit reverseGeoReady(address);
+ // unknown reply
+ emit error(ErrorContext::SITUARE, SituareError::ERROR_GENERAL);
}
}
m_currentRequests.removeAll(reply);
{
qDebug() << __PRETTY_FUNCTION__;
- m_credentials = credentials;
+ m_credentials = credentials;
}
-void SituareService::parseUserData(const QByteArray &jsonReply)
+void SituareService::parseInterestingPeopleData(const QByteArray &jsonReply)
{
qDebug() << __PRETTY_FUNCTION__;
- m_visited = 0;
- m_nbrOfImages = 0;
- m_defaultImage = false;
- qDeleteAll(m_friendsList.begin(), m_friendsList.end());
- m_friendsList.clear();
+ QJson::Parser parser;
+ bool ok;
- if(m_user) {
- delete m_user;
- m_user = 0;
+ QVariantMap result = parser.parse(jsonReply, &ok).toMap();
+
+ if (!ok) {
+ emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
+ return;
+ } else {
+ QList<User> interestingPeople;
+
+ foreach (QVariant personVariant, result["people"].toList()) {
+ User user;
+ QMap<QString, QVariant> person = personVariant.toMap();
+ user.setUserId(person["uid"].toString());
+ user.setName(person["name"].toString());
+ user.setProfileImageUrl(person["image_url"].toUrl());
+
+ interestingPeople.append(user);
+
+ emit fetchImage(user.userId(), user.profileImageUrl());
+ }
+
+ emit interestingPeopleReceived(interestingPeople);
}
+}
+void SituareService::parseNotificationsData(const QByteArray &jsonReply)
+{
QJson::Parser parser;
bool ok;
- QVariantMap result = parser.parse (jsonReply, &ok).toMap();
+ QVariantMap result = parser.parse(jsonReply, &ok).toMap();
+
if (!ok) {
+ emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
+ return;
+ } else {
+ QList<Notification> notifications;
+
+ foreach (QVariant notificationVariant, result["notifications"].toList()) {
+ Notification notification;
+ QMap<QString, QVariant> notificationMap = notificationVariant.toMap();
+ notification.setId(notificationMap["id"].toString());
+ notification.setSenderId(notificationMap["sender_id"].toString());
+ notification.setSenderName(notificationMap["sender_name"].toString());
+ uint timestampSeconds = notificationMap["timestamp"].toUInt();
+ notification.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
+ notification.setText(notificationMap["text"].toString());
+
+ notifications.append(notification);
+
+ emit fetchImage(notification.senderId(), notificationMap["image_url"].toString());
+ }
- qFatal("An error occurred during parsing");
- exit (1);
+ emit notificationsReceived(notifications);
}
+}
- QVariant userVariant = result.value("user");
- QMap<QString, QVariant> userMap = userVariant.toMap();
+void SituareService::parseUserData(const QByteArray &jsonReply)
+{
+ qDebug() << __PRETTY_FUNCTION__;
- QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
+ m_defaultImage = false;
- QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
+ QJson::Parser parser;
+ bool ok;
- if(imageUrl.isEmpty()) {
- // user doesn't have profile image, so we need to get him a silhouette image
- m_defaultImage = true;
- }
+ QVariantMap result = parser.parse (jsonReply, &ok).toMap();
- m_user = new User(userMap["address"].toString(), coordinates, userMap["name"].toString(),
- userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
- true, userMap["uid"].toString());
+ if (!ok) {
+ emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
+ return;
+ } else {
- foreach (QVariant friendsVariant, result["friends"].toList()) {
- QMap<QString, QVariant> friendMap = friendsVariant.toMap();
- QVariant distance = friendMap["distance"];
- QMap<QString, QVariant> distanceMap = distance.toMap();
+ if(result.contains("ErrorCode")) {
+ QVariant errorVariant = result.value("ErrorCode");
+ emit error(ErrorContext::SITUARE, errorVariant.toInt());
+ return;
+ } else if(result.contains("user")) {
- QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
+ QVariant userVariant = result.value("user");
+ QMap<QString, QVariant> userMap = userVariant.toMap();
- QUrl imageUrl = friendMap["profile_pic"].toUrl();
+ GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
- if(imageUrl.isEmpty()) {
- // friend doesn't have profile image, so we need to get him a silhouette image
- m_defaultImage = true;
- }
+ QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
- User *user = new User(friendMap["address"].toString(), coordinates,
- friendMap["name"].toString(),
- friendMap["note"].toString(), imageUrl,
- friendMap["timestamp"].toString(),
- false, friendMap["uid"].toString(),
- distanceMap["units"].toString(),
- distanceMap["value"].toDouble());
+ QString address = userMap["address"].toString();
+ if(address.isEmpty()) {
+ QStringList location;
+ location.append(QString::number(coordinates.latitude()));
+ location.append(QString::number(coordinates.longitude()));
+ address = location.join(", ");
+ }
- m_friendsList.append(user);
- }
- addProfileImages();
-}
+ User user = User(address, coordinates, userMap["name"].toString(),
+ userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
+ true, userMap["uid"].toString());
-void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
-{
- qDebug() << __PRETTY_FUNCTION__;
- qDebug() << "Image URL: " << url << " size :" << image.size();
+ if(imageUrl.isEmpty()) {
+ // user doesn't have profile image, so we need to get him a silhouette image
+ m_defaultImage = true;
+ user.setProfileImage(QPixmap(":/res/images/empty_avatar_big.png"));
+ }
- // assign facebook silhouette image to all who doesn't have a profile image
- if(url == QUrl(SILHOUETTE_URL)) {
- if(m_user->profileImageUrl().isEmpty()) {
- m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
- }
- for(int i=0;i < m_friendsList.count();i++) {
- if(m_friendsList.at(i)->profileImageUrl().isEmpty()) {
- m_friendsList.at(i)->setProfileImage(AvatarImage::create(image,
- AvatarImage::Small));
+ QList<User> tmpFriendsList;
+
+ foreach (QVariant friendsVariant, result["friends"].toList()) {
+ QMap<QString, QVariant> friendMap = friendsVariant.toMap();
+ QVariant distance = friendMap["distance"];
+ QMap<QString, QVariant> distanceMap = distance.toMap();
+
+ GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
+
+ QUrl imageUrl = friendMap["profile_pic"].toUrl();
+
+ QString address = friendMap["address"].toString();
+ if(address.isEmpty()) {
+ QStringList location;
+ location.append(QString::number(coordinates.latitude()));
+ location.append(QString::number(coordinates.longitude()));
+ address = location.join(", ");
+ }
+
+ User buddy = User(address, coordinates, friendMap["name"].toString(),
+ friendMap["note"].toString(), imageUrl,
+ friendMap["timestamp"].toString(),
+ false, friendMap["uid"].toString(), distanceMap["units"].toString(),
+ distanceMap["value"].toDouble());
+
+ if(imageUrl.isEmpty()) {
+ // friend doesn't have profile image, so we need to get him a silhouette image
+ m_defaultImage = true;
+ buddy.setProfileImage(AvatarImage::create(
+ QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
+ }
+
+ tmpFriendsList.append(buddy);
}
- }
- }
- if (m_user->profileImageUrl() == url) {
- m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
- }
+ QHash<QString, QUrl> imageUrlList; // url list for images
- for(int i=0;i<m_friendsList.count();i++) {
- if(m_friendsList.at(i)->profileImageUrl() == url) {
- m_friendsList.at(i)->setProfileImage(AvatarImage::create(image, AvatarImage::Small));
- m_nbrOfImages++; // indicates how many friend profile images has been downloaded
- }
- }
+ // set unchanged profile images or add new images to imageUrlList for downloading
+ if(m_user) {
+ if(m_user->profileImageUrl() != user.profileImageUrl()) {
+ if(!user.profileImageUrl().isEmpty())
+ imageUrlList.insert(user.userId(), user.profileImageUrl());
+ } else {
+ user.setProfileImage(m_user->profileImage());
+ }
+ } else {
+ if(!user.profileImageUrl().isEmpty())
+ imageUrlList.insert(user.userId(), user.profileImageUrl());
+ }
- if(m_nbrOfImages == m_visited) {
- qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
- qDebug() << "emit userDataChanged";
- emit userDataChanged(m_user, m_friendsList);
+ // clear old user object
+ if(m_user) {
+ delete m_user;
+ m_user = 0;
+ }
+
+ // create new user object from temporary user object
+ m_user = new User(user);
+
+ // set unchanged profile images or add new images to imageUrlList for downloading
+ if(!m_friendsList.isEmpty()) {
+ foreach(User tmpBuddy, tmpFriendsList) {
+ if(!tmpBuddy.profileImageUrl().isEmpty()) {
+ bool found = false;
+ foreach(User *buddy, m_friendsList) {
+ if(tmpBuddy.profileImageUrl() == buddy->profileImageUrl()) {
+ tmpBuddy.setProfileImage(buddy->profileImage());
+ found = true;
+ break;
+ }
+ }
+ if(!found && !tmpBuddy.profileImageUrl().isEmpty())
+ imageUrlList.insert(tmpBuddy.userId(), tmpBuddy.profileImageUrl());
+ }
+ }
+ } else {
+ foreach(User buddy, tmpFriendsList) {
+ if(!buddy.profileImageUrl().isEmpty())
+ imageUrlList.insert(buddy.userId(), buddy.profileImageUrl());
+ }
+ }
+
+ // clear old friendlist
+ qDeleteAll(m_friendsList.begin(), m_friendsList.end());
+ m_friendsList.clear();
+
+ // populate new friendlist with temporary friendlist's data
+ foreach(User tmpFriendItem, tmpFriendsList) {
+ User *friendItem = new User(tmpFriendItem);
+ m_friendsList.append(friendItem);
+ }
+ tmpFriendsList.clear();
+
+ //REMOVE WHEN NOT NEEDED! get user tags and set tags to the user
+ m_user->setTags(getTags(m_user->userId()));
+
+ emit userDataChanged(m_user, m_friendsList);
+
+ // set silhouette image to imageUrlList for downloading
+ if(m_defaultImage)
+ imageUrlList.insert("", QUrl(SILHOUETTE_URL));
+
+ addProfileImages(imageUrlList);
+ imageUrlList.clear();
+
+ } else {
+ QVariant address = result.value("address");
+ if(!address.toString().isEmpty()) {
+ emit reverseGeoReady(address.toString());
+ } else {
+ QStringList coordinates;
+ coordinates.append(result.value("lat").toString());
+ coordinates.append(result.value("lon").toString());
+
+ emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
+ emit reverseGeoReady(coordinates.join(", "));
+ }
+ }
}
}
-void SituareService::addProfileImages()
+void SituareService::imageReceived(const QString &id, const QPixmap &image)
{
qDebug() << __PRETTY_FUNCTION__;
- // reduce net traffic by sending only one download request for facebook silhouette image
- if(m_defaultImage) {
- emit fetchImage(QUrl(SILHOUETTE_URL));
- }
+ if (m_user->userId() == id)
+ emit imageReady(id, AvatarImage::create(image, AvatarImage::Large));
+ else
+ emit imageReady(id, AvatarImage::create(image, AvatarImage::Small));
+}
- if(!m_user->profileImageUrl().isEmpty() && m_user->profileImageUrl().isValid())
- emit fetchImage(m_user->profileImageUrl());
+void SituareService::addProfileImages(const QHash<QString, QUrl> &imageUrlList)
+{
+ qDebug() << __PRETTY_FUNCTION__;
- for(int i=0;i<m_friendsList.count();i++) {
- if(!m_friendsList.at(i)->profileImageUrl().isEmpty() &&
- m_friendsList.at(i)->profileImageUrl().isValid()) {
- m_visited++; // indicates how many friends that have profile image
- emit fetchImage(m_friendsList.at(i)->profileImageUrl());
- }
+ QHashIterator<QString, QUrl> imageUrlListIterator(imageUrlList);
+
+ while (imageUrlListIterator.hasNext()) {
+ imageUrlListIterator.next();
+ emit fetchImage(imageUrlListIterator.key(), imageUrlListIterator.value());
}
}
}
emit userDataChanged(m_user, m_friendsList);
}
+
+QStringList SituareService::getTags(const QString &userId)
+{
+ qDebug() << __PRETTY_FUNCTION__;
+
+ return m_database->getTags(userId.toInt());
+}
+
+void SituareService::updateTags(const QString &userId, const QStringList &tags)
+{
+ qDebug() << __PRETTY_FUNCTION__;
+
+ foreach (QString tag, tags)
+ m_database->addTag(userId.toInt(), tag);
+}