Merge branch 'master' into situare_interact
[situare] / src / situareservice / situareservice.cpp
index cab8d89..aba72cc 100644 (file)
@@ -47,16 +47,16 @@ 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->createMessageTable();
+    m_database->createNotificationTable();
     m_database->createUserTable();
     m_database->createTagTable();
     m_database->createUserTagTable();
@@ -75,24 +75,28 @@ SituareService::~SituareService()
     m_friendsList.clear();
 }
 
-void SituareService::fetchMessages()
+void SituareService::fetchNotifications()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-//    QList<Message> messages = m_database->getMessages(m_user->userId().toULongLong());
+//    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 (Message message, messages)
-//            if (message.senderId() == user->userId())
-//                message.setSenderAvatarImage(user->profileImage());
+//        foreach (Notification *notification, notifications)
+//            if (notification->senderId() == user->userId())
+//                notification->setImage(user->profileImage());
 //    }
 
-//    emit messagesReceived(messages);
+//    emit notificationsReceived(notifications);
 
+    QByteArray arr = m_database->getNotifications(m_user->userId().toULongLong());
 
-//    qWarning() << m_credentials.userID();
-//    qWarning() << m_credentials.sessionKey();
-//    qWarning() << m_credentials.sessionSecret();
+    parseNotificationsData(arr);
 }
 
 void SituareService::fetchPeopleWithSimilarInterest(const GeoCoordinate &southWestCoordinates,
@@ -100,17 +104,11 @@ void SituareService::fetchPeopleWithSimilarInterest(const GeoCoordinate &southWe
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    QList<User *> interestingPeople;
-    QStringList userIds = m_database->getInterestingPeople(m_user->userId().toULongLong(),
-                                                           southWestCoordinates,
-                                                           northEastCoordinates);
-    qWarning() << userIds;
-    foreach (User *user, m_friendsList) {
-        if (userIds.contains(user->userId()))
-            interestingPeople.append(user);
-    }
+    QByteArray arr = m_database->getInterestingPeople(m_user->userId().toULongLong(),
+                                                      southWestCoordinates,
+                                                      northEastCoordinates);
 
-    emit interestingPeopleReceived(interestingPeople);
+    parseInterestingPeopleData(arr);
 }
 
 void SituareService::fetchLocations()
@@ -206,7 +204,7 @@ QString SituareService::formCookie(const QString &apiKeyValue, QString expiresVa
     cookie.append(BREAK_MARK);
     cookie.append(locale);
 
-    qWarning() << cookie;
+    qDebug() << cookie;
 
     return cookie;
 }
@@ -334,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__;
@@ -344,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;
@@ -362,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;
@@ -379,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()) {
@@ -390,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;
@@ -409,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
@@ -449,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());
                 }
             }
 
@@ -477,14 +542,11 @@ void SituareService::parseUserData(const QByteArray &jsonReply)
 
             // set silhouette image to imageUrlList for downloading
             if(m_defaultImage)
-                imageUrlList.append(QUrl(SILHOUETTE_URL));
+                imageUrlList.insert("", QUrl(SILHOUETTE_URL));
 
             addProfileImages(imageUrlList);
             imageUrlList.clear();
 
-            //REMOVE WHEN NOT NEEDED! fetch messages
-            fetchMessages();
-
         } else {
             QVariant address = result.value("address");
             if(!address.toString().isEmpty()) {
@@ -501,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());
     }
 }