Refactored to match server v2.0 changes.
authorJussi Laitinen <jussi.laitinen@ixonos.com>
Thu, 18 Nov 2010 12:14:13 +0000 (14:14 +0200)
committerJussi Laitinen <jussi.laitinen@ixonos.com>
Thu, 18 Nov 2010 12:14:13 +0000 (14:14 +0200)
src/error.h
src/situareservice/situareservice.cpp
src/situareservice/situareservice.h

index 054135f..6f7b3fd 100644 (file)
@@ -28,8 +28,7 @@ namespace SituareError {
     enum errors {
         ERROR_GENERAL = 0,          // an unknown/unspecified error
         ERROR_MISSING_ARGUMENT,     // missing mandatory argument for requested action
-        SESSION_EXPIRED = 10,       // situare session credentials expired
-        UPDATE_FAILED,              // location update to situare failed
+        UPDATE_FAILED = 10,              // location update to situare failed
         DATA_RETRIEVAL_FAILED,      // user/friends list retrieval failed
         ADDRESS_RETRIEVAL_FAILED,   // reversegeo request failed
         IMAGE_DOWNLOAD_FAILED,      // image download failed from facebook
@@ -37,7 +36,8 @@ namespace SituareError {
         GPS_INITIALIZATION_FAILED,  // GPS intialization failed
         INVALID_JSON,               // JSON parsing failed i.e. invalid JSON string
         ERROR_ROUTING_FAILED,       // routing failed
-        ERROR_LOCATION_SEARCH_FAILED
+        ERROR_LOCATION_SEARCH_FAILED,// location search failed
+        SESSION_EXPIRED = 601       // situare session credentials expired
     };
 }
 
index aee9f8e..964ae40 100644 (file)
@@ -96,8 +96,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()) {
@@ -158,6 +158,20 @@ 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
+        return SituareService::RequestUnknown;
+}
+
 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
 {
     qDebug() << __PRETTY_FUNCTION__;
@@ -190,162 +204,196 @@ void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
     }
 }
 
-void SituareService::parseUserData(const QByteArray &jsonReply)
+void SituareService::parseReply(const QByteArray &jsonReply, RequestName requestName)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    m_defaultImage = false;
-
     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();
+            else if (requestName == SituareService::RequestReverseGeo)
+                parseReverseGeoData(resultData);
+        }
+    }
+}
+
+void SituareService::parseReverseGeoData(const QVariant &reverseGeoData)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-        if(result.contains("ErrorCode")) {
-            QVariant errorVariant = result.value("ErrorCode");
-            emit error(ErrorContext::SITUARE, errorVariant.toInt());
-            return;
-        } else if(result.contains("user")) {
+    QVariantMap result = reverseGeoData.toMap();
 
-            QVariant userVariant = result.value("user");
-            QMap<QString, QVariant> userMap = userVariant.toMap();
+    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(", "));
+    }
+}
 
-            GeoCoordinate coordinates(userMap["latitude"].toReal(), userMap["longitude"].toReal());
+void SituareService::parseUserData(const QVariant &userData)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-            QUrl imageUrl = userMap[NORMAL_SIZE_PROFILE_IMAGE].toUrl();
+    m_defaultImage = false;
 
-            if(imageUrl.isEmpty()) {
-                // user doesn't have profile image, so we need to get him a silhouette image
-                m_defaultImage = true;
-            }
+    QVariantMap result = userData.toMap();
 
-            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(", ");
-            }
+     if (result.contains("user")) {
 
-            User user = User(address, coordinates, userMap["name"].toString(),
-                          userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
-                          true, userMap["uid"].toString());
+        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;
+        }
 
-              QUrl imageUrl = friendMap["profile_pic"].toUrl();
+        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(", ");
+        }
 
-              if(imageUrl.isEmpty()) {
-                  // friend doesn't have profile image, so we need to get him a silhouette image
-                  m_defaultImage = true;
-              }
+        User user = User(address, coordinates, userMap["name"].toString(),
+                      userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
+                      true, userMap["uid"].toString());
 
-              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();
 
-              tmpFriendsList.append(buddy);
-            }
+          GeoCoordinate coordinates(friendMap["latitude"].toReal(),friendMap["longitude"].toReal());
 
-            QList<QUrl> imageUrlList; // url list for images
+          QUrl imageUrl = friendMap["profile_pic"].toUrl();
 
-            // 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());
-                } else {
-                    user.setProfileImage(m_user->profileImage());
-                }
-            } else {
+          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;
+              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());
+
+          tmpFriendsList.append(buddy);
+        }
+
+        QList<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());
+            } else {
+                user.setProfileImage(m_user->profileImage());
             }
+        } else {
+            if(!user.profileImageUrl().isEmpty())
+                imageUrlList.append(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.append(tmpBuddy.profileImageUrl());
                     }
+                    if(!found && !tmpBuddy.profileImageUrl().isEmpty())
+                        imageUrlList.append(tmpBuddy.profileImageUrl());
                 }
-            } else {
-                foreach(User buddy, tmpFriendsList) {
-                    if(!buddy.profileImageUrl().isEmpty())
-                        imageUrlList.append(buddy.profileImageUrl());
-                }
             }
+        } else {
+            foreach(User buddy, tmpFriendsList) {
+                if(!buddy.profileImageUrl().isEmpty())
+                    imageUrlList.append(buddy.profileImageUrl());
+            }
+        }
 
-            // clear old friendlist
-            qDeleteAll(m_friendsList.begin(), m_friendsList.end());
-            m_friendsList.clear();
+        // 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();
+        // populate new friendlist with temporary friendlist's data
+        foreach(User tmpFriendItem, tmpFriendsList) {
+            User *friendItem = new User(tmpFriendItem);
+            m_friendsList.append(friendItem);
+        }
+        tmpFriendsList.clear();
 
-            emit userDataChanged(m_user, m_friendsList);
+        emit userDataChanged(m_user, m_friendsList);
 
-            // set silhouette image to imageUrlList for downloading
-            if(m_defaultImage)
-                imageUrlList.append(QUrl(SILHOUETTE_URL));
+        // set silhouette image to imageUrlList for downloading
+        if(m_defaultImage)
+            imageUrlList.append(QUrl(SILHOUETTE_URL));
 
-            addProfileImages(imageUrlList);
-            imageUrlList.clear();
+        addProfileImages(imageUrlList);
+        imageUrlList.clear();
+    } else {
+        QVariant address = result.value("address");
+        if(!address.toString().isEmpty()) {
+            emit reverseGeoReady(address.toString());
         } 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());
+            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(", "));
-            }
+            emit error(ErrorContext::SITUARE, SituareError::ADDRESS_RETRIEVAL_FAILED);
+            emit reverseGeoReady(coordinates.join(", "));
         }
     }
 }
@@ -357,38 +405,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();
-                } 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();
     }
index a740c48..77096cb 100644 (file)
@@ -45,8 +45,16 @@ class SituareService : public QObject
 {
     Q_OBJECT
 
-public:
+private:
+    /**
+    * @brief Request name enum
+    */
+    enum RequestName { RequestUnknown,
+                       RequestGetLocations,
+                       RequestUpdateLocation,
+                       RequestReverseGeo};
 
+public:
     /**
     * @brief Default constructor
     *
@@ -134,11 +142,33 @@ private:
     QString degreesToString(double degrees);
 
     /**
+    * @brief Returns reuquest script's name.
+    *
+    * @param url url to check
+    * @return RequestName
+    */
+    SituareService::RequestName getRequestName(const QUrl &url) const;
+
+    /**
+    * @brief Parses reply from JSON string
+    *
+    * Calls different parse methods or emits error signal if response contains error status.
+    */
+    void parseReply(const QByteArray &jsonReply, RequestName requestName);
+
+    /**
+    * @brief Parses reverse geo data
+    *
+    * @param reverseGeoData reverse geo data QVariant tree
+    */
+    void parseReverseGeoData(const QVariant &reverseGeoData);
+
+    /**
     * @brief Parses user and friend data from JSON string
     *
-    * @param jsonReply JSON string
+    * @param userData user data QVariant tree
     */
-    void parseUserData(const QByteArray &jsonReply);
+    void parseUserData(const QVariant &userData);
 
     /**
       * @brief Build and send request