Merge branch 'master' into situare_interact
[situare] / src / situareservice / situareservice.cpp
index 2ed9fae..aba72cc 100644 (file)
    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),
@@ -43,12 +47,19 @@ SituareService::SituareService(QObject *parent)
             this, SLOT(requestFinished(QNetworkReply*)), Qt::QueuedConnection);
 
     m_imageFetcher = new ImageFetcher(new NetworkAccessManager(this), this);
-    connect(this, SIGNAL(fetchImage(QUrl)),
-            m_imageFetcher, SLOT(fetchImage(QUrl)));
-    connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)),
-            this, SLOT(imageReceived(QUrl, QPixmap)));
+    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()
@@ -64,6 +75,42 @@ 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__;
@@ -96,21 +143,13 @@ void SituareService::updateLocation(const GeoCoordinate &coordinates, const QStr
 {
     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);
 }
 
@@ -189,7 +228,7 @@ QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript,
 }
 
 QString SituareService::formUrlParameters(const GeoCoordinate &coordinates, QString status,
-                                          QString publish)
+                                          bool publish)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
@@ -208,17 +247,14 @@ QString SituareService::formUrlParameters(const GeoCoordinate &coordinates, QStr
     parameters.append(EQUAL_MARK);
     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);
@@ -296,6 +332,69 @@ void SituareService::credentialsReady(const FacebookCredentials &credentials)
     m_credentials = credentials;
 }
 
+void SituareService::parseInterestingPeopleData(const QByteArray &jsonReply)
+{
+    qDebug() << __PRETTY_FUNCTION__;
+
+    QJson::Parser parser;
+    bool ok;
+
+    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();
+
+    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());
+        }
+
+        emit notificationsReceived(notifications);
+    }
+}
+
 void SituareService::parseUserData(const QByteArray &jsonReply)
 {
     qDebug() << __PRETTY_FUNCTION__;
@@ -306,6 +405,7 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
     bool ok;
 
     QVariantMap result = parser.parse (jsonReply, &ok).toMap();
+
     if (!ok) {
         emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
         return;
@@ -324,11 +424,6 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
 
             QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
 
-            if(imageUrl.isEmpty()) {
-                // user doesn't have profile image, so we need to get him a silhouette image
-                m_defaultImage = true;
-            }
-
             QString address = userMap["address"].toString();
             if(address.isEmpty()) {
                 QStringList location;
@@ -341,6 +436,12 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
                           userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
                           true, userMap["uid"].toString());
 
+            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"));
+            }
+
             QList<User> tmpFriendsList;
 
             foreach (QVariant friendsVariant, result["friends"].toList()) {
@@ -352,11 +453,6 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
 
               QUrl imageUrl = friendMap["profile_pic"].toUrl();
 
-              if(imageUrl.isEmpty()) {
-                  // friend doesn't have profile image, so we need to get him a silhouette image
-                  m_defaultImage = true;
-              }
-
               QString address = friendMap["address"].toString();
               if(address.isEmpty()) {
                   QStringList location;
@@ -371,22 +467,29 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
                                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);
             }
 
-            QList<QUrl> imageUrlList; // url list for images
+            QHash<QString, QUrl> imageUrlList; // url list for images
 
             // 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.append(user.profileImageUrl());
+                        imageUrlList.insert(user.userId(), user.profileImageUrl());
                 } else {
                     user.setProfileImage(m_user->profileImage());
                 }
             } else {
                 if(!user.profileImageUrl().isEmpty())
-                    imageUrlList.append(user.profileImageUrl());
+                    imageUrlList.insert(user.userId(), user.profileImageUrl());
             }
 
             // clear old user object
@@ -411,13 +514,13 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
                             }
                         }
                         if(!found && !tmpBuddy.profileImageUrl().isEmpty())
-                            imageUrlList.append(tmpBuddy.profileImageUrl());
+                            imageUrlList.insert(tmpBuddy.userId(), tmpBuddy.profileImageUrl());
                     }
                 }
             } else {
                 foreach(User buddy, tmpFriendsList) {
                     if(!buddy.profileImageUrl().isEmpty())
-                        imageUrlList.append(buddy.profileImageUrl());
+                        imageUrlList.insert(buddy.userId(), buddy.profileImageUrl());
                 }
             }
 
@@ -432,14 +535,18 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
             }
             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.append(QUrl(SILHOUETTE_URL));
+                imageUrlList.insert("", QUrl(SILHOUETTE_URL));
 
             addProfileImages(imageUrlList);
             imageUrlList.clear();
+
         } else {
             QVariant address = result.value("address");
             if(!address.toString().isEmpty()) {
@@ -456,44 +563,25 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
     }
 }
 
-void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
+void SituareService::imageReceived(const QString &id, const QPixmap &image)
 {
     qDebug() << __PRETTY_FUNCTION__;
-    qDebug() << "Image URL: " << url << " size :" << image.size();
-
-    // 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));
-            emit imageReady(m_user);
-        }
-        foreach(User *friendItem, m_friendsList) {
-            if(friendItem->profileImageUrl().isEmpty()) {
-                friendItem->setProfileImage(AvatarImage::create(image, AvatarImage::Small));
-                emit imageReady(friendItem);
-            }
-        }
-    }
 
-    if (m_user->profileImageUrl() == url) {
-        m_user->setProfileImage(AvatarImage::create(image, AvatarImage::Large));
-        emit imageReady(m_user);
-    }
-
-    foreach(User *friendItem, m_friendsList) {
-        if(friendItem->profileImageUrl() == url) {
-            friendItem->setProfileImage(AvatarImage::create(image, AvatarImage::Small));
-            emit imageReady(friendItem);
-        }
-    }
+    if (m_user->userId() == id)
+        emit imageReady(id, AvatarImage::create(image, AvatarImage::Large));
+    else
+        emit imageReady(id, AvatarImage::create(image, AvatarImage::Small));
 }
 
-void SituareService::addProfileImages(const QList<QUrl> &imageUrlList)
+void SituareService::addProfileImages(const QHash<QString, QUrl> &imageUrlList)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    foreach(QUrl url, imageUrlList) {
-        emit fetchImage(url);
+    QHashIterator<QString, QUrl> imageUrlListIterator(imageUrlList);
+
+    while (imageUrlListIterator.hasNext()) {
+        imageUrlListIterator.next();
+        emit fetchImage(imageUrlListIterator.key(), imageUrlListIterator.value());
     }
 }
 
@@ -510,3 +598,18 @@ void SituareService::clearUserData()
     }
     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);
+}