Fix image get messages image fetching
[situare] / src / situareservice / situareservice.cpp
index 94e4124..9b969ee 100644 (file)
@@ -118,8 +118,8 @@ void SituareService::buildRequest(const QString &script, const QHash<QString, QS
     url.append("?");
 
     // append default api version parameter if not yet specified
-//    if (!parameters.contains(PARAMETER_KEY_API))
-//        url.append(PARAMETER_KEY_API + "=" + PARAMETER_VALUE_API + "&");
+    if (!parameters.contains(PARAMETER_KEY_API))
+        url.append(PARAMETER_KEY_API + "=" + PARAMETER_VALUE_API + "&");
 
     // append parameters
     if (!parameters.isEmpty()) {
@@ -174,10 +174,7 @@ void SituareService::fetchMessages()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    //Request sent to server does not need the UID
-    QByteArray arr = m_database->getNotifications(613374451);
-
-    parseMessagesData(arr);
+    buildRequest(GET_MESSAGES, QHash<QString, QString>());
 }
 
 void SituareService::fetchPeopleWithSimilarInterest(const GeoCoordinate &southWestCoordinates,
@@ -212,6 +209,26 @@ void SituareService::fetchLocations()
     buildRequest(GET_LOCATIONS, parameters);
 }
 
+SituareService::RequestName SituareService::getRequestName(const QUrl &url) const
+{
+    qDebug() << __PRETTY_FUNCTION__;
+
+    if (url.toString().contains(GET_LOCATIONS))
+        return SituareService::RequestGetLocations;
+    else if (url.toString().contains(UPDATE_LOCATION))
+        return SituareService::RequestUpdateLocation;
+    else if (url.toString().contains(REVERSE_GEO))
+        return SituareService::RequestReverseGeo;
+    else if (url.toString().contains(GET_MESSAGES))
+        return SituareService::RequestGetMessages;
+    else if (url.toString().contains(REMOVE_MESSAGE))
+        return SituareService::RequestRemoveMessage;
+    else if (url.toString().contains(SEND_MESSAGE))
+        return SituareService::RequestSendMessage;
+    else
+        return SituareService::RequestUnknown;
+}
+
 QHash<QString, QString> SituareService::getTags(const QString &userId)
 {
     qDebug() << __PRETTY_FUNCTION__;
@@ -306,258 +323,275 @@ void SituareService::parseInterestingPeopleData(const QByteArray &jsonReply)
     }
 }
 
-void SituareService::parseUserData(const QByteArray &jsonReply)
+void SituareService::parseReply(const QByteArray &jsonReply, RequestName requestName)
 {
-    qDebug() << __PRETTY_FUNCTION__;
-
-    m_defaultImage = false;
+    qDebug() << __PRETTY_FUNCTION__ << 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 {
+        QVariant resultStatus = result["ResultStatus"];
+        QVariant resultData = result["ResultData"];
+
+        if (resultStatus.toString() == "ERROR") {
+            QVariantMap errorData = resultData.toMap();
+            emit error(ErrorContext::SITUARE, errorData["ErrorCode"].toInt());
+        } else if (resultStatus.toString() == "OK") {
+            if (requestName == SituareService::RequestGetLocations)
+                parseUserData(resultData);
+            else if (requestName == SituareService::RequestUpdateLocation)
+                emit updateWasSuccessful(SituareService::SuccessfulUpdateLocation);
+            else if (requestName == SituareService::RequestRemoveMessage)
+                emit updateWasSuccessful(SituareService::SuccessfulRemoveMessage);
+            else if (requestName == SituareService::RequestReverseGeo)
+                parseReverseGeoData(resultData);
+            else if (requestName == SituareService::RequestGetMessages)
+                parseMessagesData(resultData);
+            else if (requestName == SituareService::RequestSendMessage)
+                emit updateWasSuccessful((SituareService::SuccessfulSendMessage));
+        }
+    }
+}
 
-        if(result.contains("ErrorCode")) {
-            QVariant errorVariant = result.value("ErrorCode");
-            emit error(ErrorContext::SITUARE, errorVariant.toInt());
-            return;
-        } else if(result.contains("user")) {
+void SituareService::parseReverseGeoData(const QVariant &reverseGeoData)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-            QVariant userVariant = result.value("user");
-            QMap<QString, QVariant> userMap = userVariant.toMap();
+    QVariantMap result = reverseGeoData.toMap();
 
-            GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
+    if (result.contains("address") && !result["address"].toString().isEmpty()) {
+        emit reverseGeoReady(result["address"].toString());
+    } else {
+        QStringList coordinates;
+        coordinates.append(result["lat"].toString());
+        coordinates.append(result["lon"].toString());
+        emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
+        emit reverseGeoReady(coordinates.join(", "));
+    }
+}
 
-            QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
+void SituareService::parseUserData(const QVariant &userData)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-            if(imageUrl.isEmpty()) {
-                // user doesn't have profile image, so we need to get him a silhouette image
-                m_defaultImage = true;
-            }
+    m_defaultImage = false;
 
-            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(", ");
-            }
+    QVariantMap result = userData.toMap();
 
-            User user = User(address, coordinates, userMap["name"].toString(),
-                          userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
-                          true, userMap["uid"].toString());
+    if (result.contains("user")) {
 
-            if(imageUrl.isEmpty()) {
-                // user doesn't have profile image, so we need to get him a silhouette image
-                m_defaultImage = true;
-                user.setProfileImage(AvatarImage::create(
-                        QPixmap(":/res/images/empty_avatar_big.png"), AvatarImage::Large));
-            }
+        QVariant userVariant = result.value("user");
+        QMap<QString, QVariant> userMap = userVariant.toMap();
 
-            QList<User> tmpFriendsList;
+        GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
 
-            foreach (QVariant friendsVariant, result["friends"].toList()) {
-              QMap<QString, QVariant> friendMap = friendsVariant.toMap();
-              QVariant distance = friendMap["distance"];
-              QMap<QString, QVariant> distanceMap = distance.toMap();
+        QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
 
-              GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
+        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;
+            location.append(QString::number(coordinates.latitude()));
+            location.append(QString::number(coordinates.longitude()));
+            address = location.join(", ");
+        }
 
-              QUrl imageUrl = friendMap["profile_pic"].toUrl();
+        User user = User(address, coordinates, userMap["name"].toString(),
+                      userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
+                      true, userMap["uid"].toString());
 
-              if(imageUrl.isEmpty()) {
-                  // friend doesn't have profile image, so we need to get him a silhouette image
-                  m_defaultImage = true;
-              }
+        if(imageUrl.isEmpty()) {
+            // user doesn't have profile image, so we need to get him a silhouette image
+            m_defaultImage = true;
+            user.setProfileImage(AvatarImage::create(
+                    QPixmap(":/res/images/empty_avatar_big.png"), AvatarImage::Large));
+        }
 
-              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(", ");
-              }
+        QList<User> tmpFriendsList;
 
-              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());
+        foreach (QVariant friendsVariant, result["friends"].toList()) {
+          QMap<QString, QVariant> friendMap = friendsVariant.toMap();
+          QVariant distance = friendMap["distance"];
+          QMap<QString, QVariant> distanceMap = distance.toMap();
 
-              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));
-              }
+          GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
 
-              tmpFriendsList.append(buddy);
-            }
+          QUrl imageUrl = friendMap["profile_pic"].toUrl();
 
-            QHash<QString, QUrl> imageUrlList; // url list for images
+          if(imageUrl.isEmpty()) {
+              // friend doesn't have profile image, so we need to get him a silhouette image
+              m_defaultImage = true;
+          }
 
-            // 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 {
+          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);
+        }
+
+        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.insert(user.userId(), user.profileImageUrl());
+            } else {
+                user.setProfileImage(m_user->profileImage());
             }
+        } else {
+            if(!user.profileImageUrl().isEmpty())
+                imageUrlList.insert(user.userId(), user.profileImageUrl());
+        }
 
-            // clear old user object
-            if(m_user) {
-                delete m_user;
-                m_user = 0;
-            }
+        // 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;
-                            }
+        // 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());
+                    if(!found && !tmpBuddy.profileImageUrl().isEmpty())
+                        imageUrlList.insert(tmpBuddy.userId(), tmpBuddy.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);
+        } else {
+            foreach(User buddy, tmpFriendsList) {
+                if(!buddy.profileImageUrl().isEmpty())
+                    imageUrlList.insert(buddy.userId(), buddy.profileImageUrl());
             }
-            tmpFriendsList.clear();
+        }
 
-            //REMOVE WHEN NOT NEEDED! get user tags and set tags to the user
-            m_user->setTags(getTags(m_user->userId()));
+        // clear old friendlist
+        qDeleteAll(m_friendsList.begin(), m_friendsList.end());
+        m_friendsList.clear();
 
-            emit userDataChanged(m_user, m_friendsList);
+        // populate new friendlist with temporary friendlist's data
+        foreach(User tmpFriendItem, tmpFriendsList) {
+            User *friendItem = new User(tmpFriendItem);
+            m_friendsList.append(friendItem);
+        }
+        tmpFriendsList.clear();
 
-            // set silhouette image to imageUrlList for downloading
-            if(m_defaultImage)
-                imageUrlList.insert("", QUrl(SILHOUETTE_URL));
+        //REMOVE WHEN NOT NEEDED! get user tags and set tags to the user
+        m_user->setTags(getTags(m_user->userId()));
 
-            addProfileImages(imageUrlList);
-            imageUrlList.clear();
+        emit userDataChanged(m_user, m_friendsList);
 
-        } 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());
+        // set silhouette image to imageUrlList for downloading
+        if(m_defaultImage)
+            imageUrlList.insert("", QUrl(SILHOUETTE_URL));
 
-                emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
-                emit reverseGeoReady(coordinates.join(", "));
-            }
-        }
+        addProfileImages(imageUrlList);
+        imageUrlList.clear();
     }
 }
 
-void SituareService::parseMessagesData(const QByteArray &jsonReply)
+void SituareService::parseMessagesData(const QVariant &messagesData)
 {
-    QJson::Parser parser;
-    bool ok;
-
-    QVariantMap result = parser.parse(jsonReply, &ok).toMap();
-
-    if (!ok) {
-        emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
-        return;
-    } else {
-        QVariant messages = result["messages"];
-
-        QList<Message> received;
-        QList<Message> sent;
-
-        foreach (QVariant messageVariant, messages.toMap().value("received").toList()) {
-            Message message(Message::MessageTypeReceived);
-            QMap<QString, QVariant> messageMap = messageVariant.toMap();
-            message.setId(messageMap["id"].toString());
-            message.setSenderId(messageMap["sender_id"].toString());
-            message.setReceiverId(messageMap["receiver_id"].toString());
-            message.setSenderName(messageMap["sender_name"].toString());
-            uint timestampSeconds = messageMap["timestamp"].toUInt();
-            message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
-            message.setText(messageMap["text"].toString());
-            message.setImage(AvatarImage::create(
-                    QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
-
-            bool latOk;
-            qreal latitude = messageMap["latitude"].toReal(&latOk);
-            bool lonOk;
-            qreal longitude = messageMap["longitude"].toReal(&lonOk);
-
-            if (latOk && lonOk) {
-                message.setAddress(messageMap["address"].toString());
-                message.setCoordinates(GeoCoordinate(latitude, longitude));
-            }
-
-            received.append(message);
-
-            //emit fetchImage(message.id(), messageMap["image_url"].toString());
+    QVariantMap result = messagesData.toMap();
+
+    QList<Message> received;
+    QList<Message> sent;
+
+    foreach (QVariant messageVariant, result["received"].toList()) {
+        Message message(Message::MessageTypeReceived);
+        QMap<QString, QVariant> messageMap = messageVariant.toMap();
+        message.setId(messageMap["mid"].toString());
+        message.setSenderId(messageMap["sid"].toString());
+        message.setReceiverId(messageMap["rid"].toString());
+        message.setSenderName(messageMap["name"].toString());
+        uint timestampSeconds = messageMap["timestamp"].toUInt();
+        message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
+        message.setText(messageMap["message"].toString());
+        message.setImage(AvatarImage::create(
+                QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
+
+        bool latOk;
+        qreal latitude = messageMap["lat"].toReal(&latOk);
+        bool lonOk;
+        qreal longitude = messageMap["lon"].toReal(&lonOk);
+
+        if (latOk && lonOk) {
+            message.setAddress(messageMap["address"].toString());
+            message.setCoordinates(GeoCoordinate(latitude, longitude));
         }
 
-        foreach (QVariant messageVariant, messages.toMap().value("sent").toList()) {
-            Message message(Message::MessageTypeSent);
-            QMap<QString, QVariant> messageMap = messageVariant.toMap();
-            message.setId(messageMap["id"].toString());
-            message.setSenderId(messageMap["sender_id"].toString());
-            message.setReceiverId(messageMap["receiver_id"].toString());
-            message.setSenderName(messageMap["sender_name"].toString());
-            uint timestampSeconds = messageMap["timestamp"].toUInt();
-            message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
-            message.setText(messageMap["text"].toString());
-            message.setImage(AvatarImage::create(
-                    QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
-
-            bool latOk;
-            qreal latitude = messageMap["latitude"].toReal(&latOk);
-            bool lonOk;
-            qreal longitude = messageMap["longitude"].toReal(&lonOk);
-
-            if (latOk && lonOk) {
-                message.setAddress(messageMap["address"].toString());
-                message.setCoordinates(GeoCoordinate(latitude, longitude));
-            }
+        received.append(message);
 
-            sent.append(message);
+        emit fetchImage(message.id(), messageMap["pic_square"].toString());
+    }
 
-            //emit fetchImage(message.id(), messageMap["image_url"].toString());
+    foreach (QVariant messageVariant, result["sent"].toList()) {
+        Message message(Message::MessageTypeSent);
+        QMap<QString, QVariant> messageMap = messageVariant.toMap();
+        message.setId(messageMap["mid"].toString());
+        message.setSenderId(messageMap["sid"].toString());
+        message.setReceiverId(messageMap["rid"].toString());
+        message.setSenderName(messageMap["name"].toString());
+        uint timestampSeconds = messageMap["timestamp"].toUInt();
+        message.setTimestamp(QDateTime::fromTime_t(timestampSeconds));
+        message.setText(messageMap["message"].toString());
+        message.setImage(AvatarImage::create(
+                QPixmap(":/res/images/empty_avatar.png"), AvatarImage::Small));
+
+        bool latOk;
+        qreal latitude = messageMap["lat"].toReal(&latOk);
+        bool lonOk;
+        qreal longitude = messageMap["lon"].toReal(&lonOk);
+
+        if (latOk && lonOk) {
+            message.setAddress(messageMap["address"].toString());
+            message.setCoordinates(GeoCoordinate(latitude, longitude));
         }
 
-        emit messagesReceived(received, sent);
+        sent.append(message);
+
+        emit fetchImage(message.id(), messageMap["pic_square"].toString());
     }
+
+    emit messagesReceived(received, sent);
 }
 
 void SituareService::parsePopularTagsData(const QByteArray &jsonReply)
@@ -588,8 +622,10 @@ void SituareService::removeMessage(const QString &id)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    if (m_database->removeMessage(613374451, id))
-        emit updateWasSuccessful(SituareService::SuccessfulRemoveMessage);
+    QHash<QString, QString> parameters;
+    parameters.insert("mid", id);
+
+    buildRequest(REMOVE_MESSAGE, parameters);
 }
 
 
@@ -607,39 +643,11 @@ void SituareService::requestFinished(QNetworkReply *reply)
 
     //Reply from situare
     if (m_currentRequests.contains(reply)) {
-
-        qDebug() << "BytesAvailable: " << reply->bytesAvailable();
-
-        if (reply->error()) {
+        if (reply->error())
             emit error(ErrorContext::NETWORK, reply->error());
-        } else {
-            QByteArray replyArray = reply->readAll();
-            qDebug() << "Reply from: " << reply->url() << "reply " << replyArray;
-
-            if(replyArray == ERROR_LAT.toAscii()) {
-                qDebug() << "Error: " << ERROR_LAT;
-                emit error(ErrorContext::SITUARE, SituareError::UPDATE_FAILED);
-            } else if(replyArray == ERROR_LON.toAscii()) {
-                qDebug() << "Error: " << ERROR_LON;
-                emit error(ErrorContext::SITUARE, SituareError::UPDATE_FAILED);
-            } else if(replyArray.contains(ERROR_SESSION.toAscii())) {
-                qDebug() << "Error: " << ERROR_SESSION;
-                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(reply->url().toString().contains(UPDATE_LOCATION.toAscii())) {
-                    emit updateWasSuccessful(SituareService::SuccessfulUpdateLocation);
-                } else {
-                    // session credentials are invalid
-                    emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
-                }
-            } else {
-                // unknown reply
-                emit error(ErrorContext::SITUARE, SituareError::ERROR_GENERAL);
-            }
-        }
+        else
+            parseReply(reply->readAll(), getRequestName(reply->url()));
+
         m_currentRequests.removeAll(reply);
         reply->deleteLater();
     }