Merge branch 'master' into login_browser
[situare] / src / facebookservice / facebookauthentication.cpp
index e02391e..4c2d804 100644 (file)
@@ -4,6 +4,7 @@
 
        Ville Tiensuu - ville.tiensuu@ixonos.com
        Kaj Wallin - kaj.wallin@ixonos.com
+       Henri Lampela - henri.lampela@ixonos.com
 
    Situare is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    USA.
 */
 
-#include "facebookauthentication.h"
-#include <QtGui>
+#include <qjson/parser.h>
+
 #include <QtDebug>
 #include <QDateTime>
+#include <QSettings>
+#include <QStringList>
+#include <QVariantMap>
 
-FacebookAuthentication::FacebookAuthentication(QWidget *parent)
-    : QMainWindow(parent)
-{
-    qDebug() << __PRETTY_FUNCTION__;
-
-    webView = new QWebView;
-    mainlayout = new QHBoxLayout;
+#ifdef Q_WS_MAEMO_5
+#include <QMaemo5InformationBox>
+#endif // Q_WS_MAEMO_5
 
-    QString facebookLoginBase = "http://www.facebook.com/login.php?";
-    QString situarePublicFacebookApiKey = "api_key=4197c64da2fb6b927236feaea32d7d81";
-    //QString situareDeveloperFacebookApiKey = "api_key=cf77865a5070f2c2ba3b52cbf3371579";
-    QString interval1 = "&connect_display=popup&v=1.0&next=";
-    QString situareLoginSuccess = "http://www.facebook.com/connect/login_success.html";
-    QString interval2 = "&cancel_url=";
-    QString situareLoginFailure = "http://www.facebook.com/connect/login_failure.html";
-    QString facebookLoginEnding = "&fbconnect=true&return_session=true&";
+#include "common.h"
+#include "error.h"
+#include "facebookcommon.h"
+#include "ui/facebookloginbrowser.h"
 
-    facebookLoginPage.append(facebookLoginBase);
-    facebookLoginPage.append(situarePublicFacebookApiKey);
-    facebookLoginPage.append(interval1);
-    facebookLoginPage.append(situareLoginSuccess);
-    facebookLoginPage.append(interval2);
-    facebookLoginPage.append(situareLoginFailure);
-    facebookLoginPage.append(facebookLoginEnding);
-
-    connect(webView, SIGNAL(urlChanged(const QUrl &)), this, SLOT(updateCredentials(const QUrl &)));   
-
-    readCredentials(loginCredentials);
-
-    if (!verifyCredentials(loginCredentials))
-        start();
-    else
-        emit credentialsReady();
+#include "facebookauthentication.h"
 
-}
+const QString REDIRECT_URI = "http://www.facebook.com/connect/login_success.html";
 
-FacebookAuthentication::~FacebookAuthentication()
+FacebookAuthentication::FacebookAuthentication(QObject *parent)
+    : QObject(parent),
+      m_browser(0)
 {
     qDebug() << __PRETTY_FUNCTION__;
-    delete webView;
-    delete mainlayout;
+
 }
 
-void FacebookAuthentication::start()
+void FacebookAuthentication::browserDestroyed()
 {
-    qDebug() << __PRETTY_FUNCTION__;
+    qWarning() << __PRETTY_FUNCTION__;
 
-    const double fontSizeLarge = 1.2;
-    //const double fontSizeNormal = 1.0;
+    ///< @todo (HIGH) Is newer called!
 
-    webView->setZoomFactor(fontSizeLarge);
-    webView->load(facebookLoginPage);
-    setCentralWidget(webView);    
+    m_browser = 0;
 }
 
-
-bool FacebookAuthentication::updateCredentials(const QUrl &url)
-{    
+void FacebookAuthentication::clearAccountInformation(bool keepUsername)
+{
     qDebug() << __PRETTY_FUNCTION__;
-//    setCurrentUrl(url);
-
-    bool foundSessionKey = FALSE;
-    bool foundUserID = FALSE;
-    bool foundExpires = FALSE;
-    bool foundSessionSecret = FALSE;
-    bool foundSig = FALSE;
-
-    if (url.isValid()){
-         //qDebug() << "url is valid" << endl;
-
-        QString callbackUrl = url.toString(); //tmpUrl.toString();
-        QString urlEdit(callbackUrl);
-        //qDebug() << "callbackUrl:  " << endl << callbackUrl.toAscii() << endl;
-        //qDebug() << "webView zoom factor" << webView->zoomFactor() << endl;
-
-        if ( callbackUrl.indexOf("http://www.facebook.com/connect/login_success.html") == 0 ){
-            //qDebug() << "login success" << endl;
-
-            // let's find out session key            
-            int indexOfCredential = callbackUrl.indexOf("session_key");
-            int index2;
-
-            if (indexOfCredential != -1){
-                foundSessionKey = TRUE;
-
-                indexOfCredential += 14; //lenght of string "session_key"
-                index2 = callbackUrl.indexOf("uid");
-                index2 -= 4;
-                urlEdit.remove(0,indexOfCredential);
-                index2 = urlEdit.indexOf("uid");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove("\",\"");
-
-                //qDebug() << "session_key" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setSessionKey(urlEdit);
-            }
-
-            // let's find out uid            
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("uid");
-
-            if (indexOfCredential != -1){
-                foundUserID = TRUE;
-                indexOfCredential += 5; //length of string "uid"
-                urlEdit.remove(0,indexOfCredential);
-
-                index2 = urlEdit.indexOf("expires");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove(",\"");
-                //qDebug() << "urlEdit" << endl << urlEdit.toStdString() << endl;
-
-                //qDebug() << "userID" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setUserID(urlEdit);
-            }
-
-            // let's find out expires           
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("expires");
-
-            if (indexOfCredential != -1){
-                foundExpires = TRUE;
-
-                indexOfCredential += 9; //length of string "expires"
-                urlEdit.remove(0,indexOfCredential);
-                index2 = urlEdit.indexOf("secret");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove(",\"");
-
-                //qDebug() << "expires" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setExpires(urlEdit);
-            }
-
-            // let's find out sessionsecret            
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("secret");
-
-            if (indexOfCredential != -1){
-                foundSessionSecret = TRUE;
-
-                indexOfCredential += 9; //" length of "secret"
-                urlEdit.remove(0,indexOfCredential);
-                index2 = urlEdit.indexOf("sig");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove("\",\"");
-
-                //*sessionSecret = urlEdit;
-                //qDebug() << "sessionSecret" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setSessionSecret(urlEdit);
-            }
-
-            // let's find out sig            
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("sig");
-
-            if (indexOfCredential != -1){
-                foundSig = TRUE;
-
-                indexOfCredential += 6; //" length of sig":"
-                urlEdit.remove(0,indexOfCredential);
-                urlEdit.remove("\"}");
-
-                //qDebug() << "sig" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setSig(urlEdit);
-            }
-
-
-            webView->hide(); //let's close the webview after successful login.
-            emit credentialsReady();
-            writeCredentials(loginCredentials);
-        }
-
-        else if ( callbackUrl.indexOf("https://login.facebook.com/login.php?login_attempt=") == 0){
-            qWarning() << "login failure" << endl;
-            emit loginFailure();
-        }
-
-        else if ( callbackUrl.indexOf("http://www.facebook.com/login.php?api_key=") == 0){
-            //qDebug() << "correct loginPage";
-        }
-
-        else { // totally wrong webPage. User will be redirected to basic login page...
-            //qDebug() << "totally wrong webPage";
-            emit loginFailure();
-            start();
-        }
-    }
 
+    ///< @todo (HIGH) clear session from SituareService
+    QSettings settings(DIRECTORY_NAME, FILE_NAME);
 
-    else { // show error message that page cant be loaded in QWebView
-        //qDebug() << " Loading of page failed invalid URL" << endl;
-        emit loginFailure();
-        return FALSE;
+    if(!keepUsername) {
+        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);
+}
+
+void FacebookAuthentication::loadFinished(bool ok)
+{
+    qWarning() << __PRETTY_FUNCTION__ << ok;
 
-    return (foundSessionKey && foundUserID && foundExpires && foundSessionSecret && foundSig);
+    ///< @todo show browsed window if url != redirect url
 }
 
-void FacebookAuthentication::writeCredentials(const FacebookCredentials &credentials)
+void FacebookAuthentication::login()
 {
-    qDebug() << __PRETTY_FUNCTION__;
-    QSettings settings("Ixonos", "Situare");
+    qWarning() << __PRETTY_FUNCTION__;
 
-    settings.setValue("Session Key", credentials.getSessionKey());
-    settings.setValue("User ID", credentials.getUserID());
-    settings.setValue("Expires", credentials.getExpires());
-    settings.setValue("Session Secret", credentials.getSessionSecret());
-    settings.setValue("Sig", credentials.getSig());
+    emit buildLoginBrowser();
 }
 
-void FacebookAuthentication::readCredentials(FacebookCredentials &credentialsFromFile)
+QString FacebookAuthentication::parseSession(const QUrl &url)
 {
-    qDebug() << __PRETTY_FUNCTION__;
+    qWarning() << __PRETTY_FUNCTION__;
+
+    const QString BEGIN("session={");
+    const QString END("}");
 
-    QSettings settings("Ixonos", "Situare");
+    QString urlString = url.toString();
 
-    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("Sig", "Error").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::getLoginCredentials() const
- {
-     qDebug() << __PRETTY_FUNCTION__;
-     return loginCredentials;
- }
+void FacebookAuthentication::setBrowser(FacebookLoginBrowser *browser)
+{
+    qWarning() << __PRETTY_FUNCTION__;
+
+    m_browser = browser;
 
- bool FacebookAuthentication::verifyCredentials(const FacebookCredentials &credentials) const
- {
-     QString expires = credentials.getExpires();
-     QDateTime expireTime;
-     expireTime.setTime_t(expires.toInt());
-     QString expiresString = expireTime.toString("dd.MM.yyyy  hh:mm:ss");
-     qDebug() << expiresString.toAscii();
+    if (m_browser) {
+        connect(m_browser, SIGNAL(loadFinished(bool)),
+                this, SLOT(loadFinished(bool)));
 
-     QDateTime currentTime;
-     currentTime = QDateTime::currentDateTime();
-     QString currentTimeString = currentTime.toString("dd.MM.yyyy  hh:mm:ss");
-     qDebug() << currentTimeString.toAscii();
+        connect(m_browser, SIGNAL(urlChanged(QUrl)),
+                this, SLOT(urlChanged(QUrl)));
 
-     return currentTime < expireTime;
- }
+        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);
+    }
+}