Merge branch 'master' into login_browser
[situare] / src / facebookservice / facebookauthentication.cpp
index 1213895..4c2d804 100644 (file)
@@ -21,6 +21,8 @@
    USA.
 */
 
+#include <qjson/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 "ui/facebookloginbrowser.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_browser(0)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    readCredentials(m_loginCredentials);
 }
 
-void FacebookAuthentication::start()
+void FacebookAuthentication::browserDestroyed()
 {
-    qDebug() << __PRETTY_FUNCTION__;
+    qWarning() << __PRETTY_FUNCTION__;
 
-    if (!verifyCredentials(m_loginCredentials)) {
-        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);
-
-        emit newLoginRequest(formLoginPageUrl(list));
-    }
-    else {
-        emit credentialsReady(false, m_loginCredentials);
-    }
+    ///< @todo (HIGH) Is newer called!
 
+    m_browser = 0;
 }
 
-bool FacebookAuthentication::updateCredentials(const QUrl &url)
+void FacebookAuthentication::clearAccountInformation(bool keepUsername)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    bool found = false;
-
-    if (url.isValid()){
-         qDebug() << "url is valid";
-
-        QString callbackUrl = url.toString();
-        qDebug() << "callbackUrl:  " << callbackUrl.toAscii();
-
-        if (callbackUrl.indexOf(LOGIN_SUCCESS_REPLY) == 0) {
-            qDebug() << "login success";
-
-            // let's find out session credentials
-            if(callbackUrl.contains(SESSION_KEY)) {
-
-                QJson::Parser parser;
-                bool ok;
-
-                // split string into string part and json part
-                QStringList list = url.toString().split("=");
-
-                for(int i=0;i<list.count();i++) {
-                    // if string starts with json item
-                    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);
-                        }
-                        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;
-            }
-            writeCredentials(m_loginCredentials);
-            emit credentialsReady(true, m_loginCredentials);
-        }
-        else if ( callbackUrl.indexOf(LOGIN_FAILURE_REPLY) == 0){
-            qWarning() << "login failure" << endl;
-            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) {
-                emit loginFailure();
-            }
-        }
-        else if(callbackUrl.indexOf(LOGIN_PAGE) == 0) {
-            qDebug() << "correct loginPage";
-        }
-        else {
-            qDebug() << "totally wrong webPage";
-            // we should not get a wrong page at this point
-            emit loginFailure();
-        }
-    }
-    else {
-        qDebug() << " Loading of page failed invalid URL" << endl;
-        // we should not get a wrong page at this point
-        emit loginFailure();
-        return false;
+    ///< @todo (HIGH) clear session from SituareService
+    QSettings settings(DIRECTORY_NAME, FILE_NAME);
+
+    if(!keepUsername) {
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_ENABLED);
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_INTERVAL);
     }
-    return found;
+
+    settings.remove(COOKIES);
+    settings.remove(USER_UNSEND_MESSAGE);
+    settings.remove(USER_UNSEND_MESSAGE_PUBLISH);
 }
 
-void FacebookAuthentication::writeCredentials(const FacebookCredentials &credentials)
+void FacebookAuthentication::loadFinished(bool ok)
 {
-    qDebug() << __PRETTY_FUNCTION__;
-    QSettings settings(DIRECTORY_NAME, FILE_NAME);
+    qWarning() << __PRETTY_FUNCTION__ << ok;
 
-    settings.setValue(SESSION_KEY, credentials.sessionKey());
-    settings.setValue(USER_ID, credentials.userID());
-    settings.setValue(EXPIRES, credentials.expires());
-    settings.setValue(SESSION_SECRET, credentials.sessionSecret());
-    settings.setValue(SIGNATURE, credentials.sig());
+    ///< @todo show browsed window if url != redirect url
 }
 
-void FacebookAuthentication::readCredentials(FacebookCredentials &credentialsFromFile)
+void FacebookAuthentication::login()
 {
-    qDebug() << __PRETTY_FUNCTION__;
+    qWarning() << __PRETTY_FUNCTION__;
 
-    QSettings settings(DIRECTORY_NAME, FILE_NAME);
+    emit buildLoginBrowser();
+}
 
-    credentialsFromFile.setSessionKey(settings.value(SESSION_KEY, ERROR).toString());
-    credentialsFromFile.setUserID(settings.value(USER_ID, ERROR).toString());
-    credentialsFromFile.setExpires(settings.value(EXPIRES, ERROR).toString());
-    credentialsFromFile.setSessionSecret(settings.value(SESSION_SECRET, ERROR).toString());
-    credentialsFromFile.setSig(settings.value(SIGNATURE, ERROR).toString());
+QString FacebookAuthentication::parseSession(const QUrl &url)
+{
+    qWarning() << __PRETTY_FUNCTION__;
+
+    const QString BEGIN("session={");
+    const QString END("}");
+
+    QString urlString = url.toString();
+
+    int begin = urlString.indexOf(BEGIN);
+    int end = urlString.indexOf(END, begin);
+
+    if ((begin > -1) && (end > -1))
+        return urlString.mid(begin, end - begin + 1);
+    else
+        return QString();
 }
 
- FacebookCredentials FacebookAuthentication::loginCredentials() const
- {
-     qDebug() << __PRETTY_FUNCTION__;
-     return m_loginCredentials;
- }
-
- bool FacebookAuthentication::verifyCredentials(const FacebookCredentials &credentials) const
- {
-     qDebug() << __PRETTY_FUNCTION__;
-
-     // if expires value is 0, then credentials are valid forever
-     if(credentials.expires() == "0") {
-         return true;
-     }
-     else {
-         const QString dateTimeFormat = "dd.MM.yyyy  hh:mm:ss";
-         QString expires = credentials.expires();
-         QDateTime expireTime;
-         expireTime.setTime_t(expires.toInt());
-         QString expiresString = expireTime.toString(dateTimeFormat);
-         qDebug() << expiresString.toAscii();
-
-         QDateTime currentTime;
-         currentTime = QDateTime::currentDateTime();
-         QString currentTimeString = currentTime.toString(dateTimeFormat);
-         qDebug() << currentTimeString.toAscii();
-
-         return currentTime < expireTime;
-     }
- }
-
- QUrl FacebookAuthentication::formLoginPageUrl(const QStringList &urlParts) const
- {
-    qDebug() << __PRETTY_FUNCTION__;
+void FacebookAuthentication::setBrowser(FacebookLoginBrowser *browser)
+{
+    qWarning() << __PRETTY_FUNCTION__;
+
+    m_browser = browser;
+
+    if (m_browser) {
+        connect(m_browser, SIGNAL(loadFinished(bool)),
+                this, SLOT(loadFinished(bool)));
+
+        connect(m_browser, SIGNAL(urlChanged(QUrl)),
+                this, SLOT(urlChanged(QUrl)));
 
-    return QUrl(urlParts.join(EMPTY));
- }
-
- void FacebookAuthentication::saveUsername(const QString &username)
- {
-     qDebug() << __PRETTY_FUNCTION__;
-
-     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-     settings.setValue(USERNAME, username);
- }
-
- const QString FacebookAuthentication::loadUsername()
- {
-     qDebug() << __PRETTY_FUNCTION__;
-
-     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-     return settings.value(USERNAME, EMPTY).toString();
- }
-
- void FacebookAuthentication::clearAccountInformation(bool keepUsername)
- {
-     qDebug() << __PRETTY_FUNCTION__;
-
-     m_loginCredentials.clearCredentials();
-     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-     if(!keepUsername) {
-        settings.remove(USERNAME);
-     }
-     settings.remove(USER_ID);
-     settings.remove(SESSION_KEY);
-     settings.remove(SESSION_SECRET);
-     settings.remove(EXPIRES);
-     settings.remove(SIGNATURE);
-
-     emit credentialsChanged(m_loginCredentials);
- }
+        connect(m_browser, SIGNAL(destroyed()),
+                this, SLOT(browserDestroyed()));
+
+        //    browser->load(QUrl("https://graph.facebook.com/oauth/authorize?client_id=4197c64da2fb6b927236feaea32d7d81&redirect_uri=http://www.facebook.com/connect/login_success.html&display=touch&type=user_agent"));
+
+        QString url = "https://www.facebook.com/login.php?";
+        url.append("api_key=cf77865a5070f2c2ba3b52cbf3371579&"); ///< @todo hard coded test server api key
+        url.append("cancel_url=http://www.facebook.com/connect/login_failure.html&");
+        url.append("display=popup&");
+        url.append("fbconnect=1&");
+        url.append("next=http://www.facebook.com/connect/login_success.html&");
+        url.append("return_session=1&");
+        url.append("session_version=3&");
+        url.append("v=1.0&");
+        url.append("req_perms=publish_stream");
+
+        m_browser->load(QUrl(url));
+    }
+}
+
+void FacebookAuthentication::urlChanged(const QUrl &url)
+{
+    qWarning() << __PRETTY_FUNCTION__ << url.toString();
+
+    // if login succeeded
+    if (url.toString().startsWith(REDIRECT_URI)) {
+        const QString session = parseSession(url);
+        qWarning() << __PRETTY_FUNCTION__ << "parsed session:" << session;
+        if (!session.isEmpty())
+            emit loggedIn(session);
+    }
+}