Parsing the access token from the url
[situare] / src / facebookservice / facebookauthentication.cpp
index 1eefd6f..398e55d 100644 (file)
@@ -21,6 +21,8 @@
    USA.
 */
 
+#include "parser.h"
+
 #include <QtDebug>
 #include <QDateTime>
 #include <QSettings>
 #include <QMaemo5InformationBox>
 #endif // Q_WS_MAEMO_5
 
-#include "facebookauthentication.h"
+#include "common.h"
+#include "error.h"
 #include "facebookcommon.h"
-#include "../common.h"
-#include "parser.h"
+
+#include "facebookauthentication.h"
+
+const QString REDIRECT_URI = "http://www.facebook.com/connect/login_success.html";
 
 FacebookAuthentication::FacebookAuthentication(QObject *parent)
     : QObject(parent),
-    m_loginAttempts(0)
-
+    m_freshLogin(false)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
@@ -52,17 +56,22 @@ void FacebookAuthentication::clearAccountInformation(bool keepUsername)
     m_loginCredentials.clearCredentials();
     QSettings settings(DIRECTORY_NAME, FILE_NAME);
 
-    if(!keepUsername)
+    if(!keepUsername) {
         settings.remove(USERNAME);
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_ENABLED);
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_INTERVAL);
+    }
 
     settings.remove(COOKIES);
+    settings.remove(USER_UNSEND_MESSAGE);
+    settings.remove(USER_UNSEND_MESSAGE_PUBLISH);
 }
 
-QUrl FacebookAuthentication::formLoginPageUrl(const QStringList &urlParts) const
+void FacebookAuthentication::loadFinished(bool ok)
 {
-   qDebug() << __PRETTY_FUNCTION__;
+    qWarning() << __PRETTY_FUNCTION__ << ok;
 
-   return QUrl(urlParts.join(EMPTY));
+    ///< @todo show browsed window if url != redirect url
 }
 
 const QString FacebookAuthentication::loadUsername()
@@ -79,6 +88,24 @@ FacebookCredentials FacebookAuthentication::loginCredentials() const
     return m_loginCredentials;
 }
 
+QString FacebookAuthentication::parseAccessToken(const QUrl &url)
+{
+    qWarning() << __PRETTY_FUNCTION__;
+
+    const QString ACCESS_TOKEN_PARAMETER("#access_token=");
+    const QString EXPIRATION_PARAMETER("&expires_in=");
+
+    QString urlString = url.toString();
+
+    int begin = urlString.indexOf(ACCESS_TOKEN_PARAMETER) + ACCESS_TOKEN_PARAMETER.length();
+    int end = urlString.indexOf(EXPIRATION_PARAMETER);
+
+    if ((begin > -1) && (end > begin))
+        return urlString.mid(begin, end - begin);
+    else
+        return QString();
+}
+
 void FacebookAuthentication::saveUsername(const QString &username)
 {
     qDebug() << __PRETTY_FUNCTION__;
@@ -91,33 +118,25 @@ void FacebookAuthentication::start()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    QStringList list;
-    list.append(FACEBOOK_LOGINBASE);
-    list.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
-    list.append(INTERVAL1);
-    list.append(SITUARE_LOGIN_SUCCESS);
-    list.append(INTERVAL2);
-    list.append(SITUARE_LOGIN_FAILURE);
-    list.append(FACEBOOK_LOGIN_ENDING);
-
     QSettings settings(DIRECTORY_NAME, FILE_NAME);
 
-    QString cookies = settings.value(COOKIES, EMPTY).toString();
+    QStringList cookies = settings.value(COOKIES).toStringList();
     if(!cookies.isEmpty()) {
         emit loginUsingCookies();
     }
     else {
-        emit newLoginRequest(formLoginPageUrl(list));
+        m_freshLogin = true;
+        emit newLoginRequest();
     }
 }
 
 bool FacebookAuthentication::updateCredentials(const QUrl &url)
 {
-    qDebug() << __PRETTY_FUNCTION__;
+    qDebug() << __PRETTY_FUNCTION__ << url.toString();
 
     bool found = false;
 
-    if (url.isValid()){
+    if (url.isValid()) {
          qDebug() << "url is valid";
 
         QString callbackUrl = url.toString();
@@ -140,64 +159,72 @@ bool FacebookAuthentication::updateCredentials(const QUrl &url)
                     if(list.at(i).startsWith("{")) {
                         QByteArray jsonString = list.at(i).toAscii();
                         QVariantMap result = parser.parse (jsonString, &ok).toMap();
-                        if (!ok) {
 
-                            qFatal("An error occurred during parsing");
-                            exit (1);
+                        if (!ok) {
+                            emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
+                            found = false;
+                        } else {
+                            qDebug() << "Session Key" << result[SESSION_KEY].toString();
+                            m_loginCredentials.setSessionKey(result[SESSION_KEY].toString());
+
+    //                        // commeted out until qjson parser can handle 64-bit integers
+    //                        qDebug() << "userID" << result[USER_ID].toString();
+    //                        m_loginCredentials.setUserID(result[USER_ID].toString().toAscii());
+
+                            // dirty fix, get user id from session_key
+                            QStringList list = result[SESSION_KEY].toString().split("-");
+                            m_loginCredentials.setUserID(list.at(1));
+                            qDebug() << m_loginCredentials.userID();
+
+                            qDebug() << "Expires" << result[EXPIRES].toString();
+                            m_loginCredentials.setExpires(result[EXPIRES].toString());
+
+                            qDebug() << "Session Secret" << result[SESSION_SECRET].toString();
+                            m_loginCredentials.setSessionSecret(result[SESSION_SECRET].toString());
+
+                            qDebug() << "Signature" << result[SIGNATURE].toString();
+                            m_loginCredentials.setSig(result[SIGNATURE].toString());
+
+                            found = true;
+                            m_freshLogin = false;
+                            emit saveCookiesRequest();
+                            emit credentialsReady(m_loginCredentials);
                         }
-                        qDebug() << "Session Key" << result[SESSION_KEY].toString();
-                        m_loginCredentials.setSessionKey(result[SESSION_KEY].toString());
-
-//                        // commeted out until qjson parser can handle 64-bit integers
-//                        qDebug() << "userID" << result[USER_ID].toString();
-//                        m_loginCredentials.setUserID(result[USER_ID].toString().toAscii());
-
-                        // dirty fix, get user id from session_key
-                        QStringList list = result[SESSION_KEY].toString().split("-");
-                        m_loginCredentials.setUserID(list.at(1));
-                        qDebug() << m_loginCredentials.userID();
-
-                        qDebug() << "Expires" << result[EXPIRES].toString();
-                        m_loginCredentials.setExpires(result[EXPIRES].toString());
-
-                        qDebug() << "Session Secret" << result[SESSION_SECRET].toString();
-                        m_loginCredentials.setSessionSecret(result[SESSION_SECRET].toString());
-
-                        qDebug() << "Signature" << result[SIGNATURE].toString();
-                        m_loginCredentials.setSig(result[SIGNATURE].toString());
                     }
                 }
-                found = true;
-                emit saveCookiesRequest();
             }
-            emit credentialsReady(m_loginCredentials);
-        }
-        else if ( callbackUrl.indexOf(LOGIN_FAILURE_REPLY) == 0){
-            qWarning() << "login failure" << endl;
+        } else if ( callbackUrl.indexOf(LOGIN_FAILURE_REPLY) == 0) {
+            qDebug() << "login failure";
             qDebug() << callbackUrl;
-            ++m_loginAttempts;
-            /* emit loginFailure for every second login attemps, since webview loads login
-               error page (loadingDone() signal is emitted) and we need to avoid that because
-               at this point we don't have new login parameters */
-            if(m_loginAttempts % 2) {
-                clearAccountInformation(true);
-                emit loginFailure();
+            clearAccountInformation(true);
+            if(m_freshLogin) {
+                emit error(ErrorContext::SITUARE, SituareError::LOGIN_FAILED);
+            } else {
+                m_freshLogin = true;
+                emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
             }
-        }
-        else if(callbackUrl.indexOf(LOGIN_PAGE) == 0) {
+        } else if(callbackUrl.indexOf(LOGIN_PAGE) == 0) {
             qDebug() << "correct loginPage";
-        }
-        else {
+        } else {
             qDebug() << "totally wrong webPage";
             // we should not get a wrong page at this point
-            emit loginFailure();
+            emit error(ErrorContext::SITUARE, SituareError::LOGIN_FAILED);
         }
-    }
-    else {
+    } else {
         qDebug() << " Loading of page failed invalid URL" << endl;
         // we should not get a wrong page at this point
-        emit loginFailure();
-        return false;
+        emit error(ErrorContext::SITUARE, SituareError::LOGIN_FAILED);
     }
     return found;
 }
+
+void FacebookAuthentication::urlChanged(const QUrl &url)
+{
+    qWarning() << __PRETTY_FUNCTION__ << url.toString();
+
+    // if login succeeded
+    if (url.toString().startsWith(REDIRECT_URI)) {
+        ///< @todo hide browser dialog
+        qWarning() << __PRETTY_FUNCTION__ << "access_token:" << parseAccessToken(url);
+    }
+}