Removed FacebookLoginBrowser class, replaced with QWebView.
[situare] / src / facebookservice / facebookauthentication.cpp
index 6526502..ca8ac04 100644 (file)
    USA.
 */
 
+#include <qjson/parser.h>
+
 #include <QtDebug>
 #include <QDateTime>
+#include <QNetworkReply>
 #include <QSettings>
 #include <QStringList>
 #include <QVariantMap>
+#include <QWebView>
 
 #ifdef Q_WS_MAEMO_5
 #include <QMaemo5InformationBox>
 #endif // Q_WS_MAEMO_5
 
+#include "common.h"
+#include "error.h"
+#include "network/networkcookiejar.h"
+#include "situareservice/situarecommon.h"
+#include "ui/mainwindow.h"
+
 #include "facebookauthentication.h"
-#include "facebookcommon.h"
-#include "../common.h"
-#include "parser.h"
 
-FacebookAuthentication::FacebookAuthentication(QObject *parent)
-    : QObject(parent),
-    m_loginAttempts(0)
+const QString FB_LOGIN_SUCCESS_URL = "http://www.facebook.com/connect/login_success.html";
+const QString FB_LOGIN_URL = "https://www.facebook.com/login.php";
 
+FacebookAuthentication::FacebookAuthentication(MainWindow *mainWindow, QObject *parent)
+    : QObject(parent),
+      m_browser(0),
+      m_mainWindow(mainWindow)
 {
     qDebug() << __PRETTY_FUNCTION__;
-
-    readCredentials(m_loginCredentials);
 }
 
-void FacebookAuthentication::start()
+void FacebookAuthentication::browserDestroyed()
 {
-    qDebug() << __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);
-    }
+    qWarning() << __PRETTY_FUNCTION__;
 
+    m_browser = 0;
 }
 
-bool FacebookAuthentication::updateCredentials(const QUrl &url)
+void FacebookAuthentication::clearAccountInformation(bool keepUsername)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    bool found = false;
+    ///< @todo (HIGH) clear session from SituareService
+    QSettings settings(SETTINGS_ORGANIZATION_NAME, SETTINGS_APPLICATION_NAME);
 
-    if (url.isValid()){
-         qDebug() << "url is valid";
-
-        QString callbackUrl = url.toString();
-        qDebug() << "callbackUrl:  " << callbackUrl.toAscii();
+    if(!keepUsername) {
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_ENABLED);
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_INTERVAL);
+    }
 
-        if (callbackUrl.indexOf(LOGIN_SUCCESS_REPLY) == 0) {
-            qDebug() << "login success";
+    settings.remove(USER_UNSEND_MESSAGE);
+    settings.remove(USER_UNSEND_MESSAGE_PUBLISH);
 
-            // let's find out session credentials
-            if(callbackUrl.contains(SESSION_KEY)) {
+    NetworkCookieJar::clearCookiesSetting();
+}
 
-                QJson::Parser parser;
-                bool ok;
+void FacebookAuthentication::loadFinished(bool ok)
+{
+    qWarning() << __PRETTY_FUNCTION__ << ok;
 
-                // split string into string part and json part
-                QStringList list = url.toString().split("=");
+    ///< @todo show browsed window if url != redirect url
+}
 
-                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) {
+void FacebookAuthentication::login()
+{
+    qWarning() << __PRETTY_FUNCTION__;
 
-                            qFatal("An error occurred during parsing");
-                            exit (1);
-                        }
-                        qDebug() << "Session Key" << result[SESSION_KEY].toString();
-                        m_loginCredentials.setSessionKey(result[SESSION_KEY].toString());
+    if (!m_browser) {
+        m_browser = new QWebView(m_mainWindow);
 
-//                        // commeted out until qjson parser can handle 64-bit integers
-//                        qDebug() << "userID" << result[USER_ID].toString();
-//                        m_loginCredentials.setUserID(result[USER_ID].toString().toAscii());
+        if (m_browser) {
+            m_browser->page()->networkAccessManager()->setCookieJar(new NetworkCookieJar());
 
-                        // 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();
+            connect(m_browser, SIGNAL(loadFinished(bool)),
+                    this, SLOT(loadFinished(bool)));
 
-                        qDebug() << "Expires" << result[EXPIRES].toString();
-                        m_loginCredentials.setExpires(result[EXPIRES].toString());
+            connect(m_browser, SIGNAL(urlChanged(QUrl)),
+                    this, SLOT(urlChanged(QUrl)));
 
-                        qDebug() << "Session Secret" << result[SESSION_SECRET].toString();
-                        m_loginCredentials.setSessionSecret(result[SESSION_SECRET].toString());
+            connect(m_browser, SIGNAL(destroyed(QObject*)),
+                    this, SLOT(browserDestroyed()));
 
-                        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();
+            connect(m_browser->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
+                    this, SLOT(networkReplyHandler(QNetworkReply*)));
         }
     }
-    else {
-        qDebug() << " Loading of page failed invalid URL" << endl;
-        // we should not get a wrong page at this point
-        emit loginFailure();
-        return false;
+
+    if (m_browser) {
+        QString url = FB_LOGIN_URL + "?";
+        url.append("api_key=" + API_KEY +"&");
+        url.append("display=touch&");
+        url.append("fbconnect=1&");
+        url.append("next=" + FB_LOGIN_SUCCESS_URL + "&");
+        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));
     }
-    return found;
 }
 
-void FacebookAuthentication::writeCredentials(const FacebookCredentials &credentials)
+void FacebookAuthentication::networkReplyHandler(QNetworkReply *reply)
 {
-    qDebug() << __PRETTY_FUNCTION__;
-    QSettings settings(DIRECTORY_NAME, FILE_NAME);
+    qWarning() <<__PRETTY_FUNCTION__;
 
-    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());
+    if (reply->error() != QNetworkReply::NoError) {
+        qCritical() << __PRETTY_FUNCTION__ << "error:" << reply->error() << reply->errorString();
+        /// @todo Emit error signal
+    }
 }
 
-void FacebookAuthentication::readCredentials(FacebookCredentials &credentialsFromFile)
+QString FacebookAuthentication::parseSession(const QUrl &url)
 {
-    qDebug() << __PRETTY_FUNCTION__;
-
-    QSettings settings(DIRECTORY_NAME, FILE_NAME);
-
-    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());
-}
-
- 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__;
-
-    return QUrl(urlParts.join(EMPTY));
- }
+    qWarning() << __PRETTY_FUNCTION__;
 
- void FacebookAuthentication::saveUsername(const QString &username)
- {
-     qDebug() << __PRETTY_FUNCTION__;
+    const QString BEGIN("session={");
+    const QString END("}");
 
-     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-     settings.setValue(USERNAME, username);
- }
+    QString urlString = url.toString();
 
- const QString FacebookAuthentication::loadUsername()
- {
-     qDebug() << __PRETTY_FUNCTION__;
+    int begin = urlString.indexOf(BEGIN);
+    int end = urlString.indexOf(END, begin);
 
-     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-     return settings.value(USERNAME, EMPTY).toString();
- }
-
- void FacebookAuthentication::clearAccountInformation()
- {
-     qDebug() << __PRETTY_FUNCTION__;
-
-     m_loginCredentials.clearCredentials();
-     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-     settings.remove(USERNAME);
-     settings.remove(USER_ID);
-     settings.remove(SESSION_KEY);
-     settings.remove(SESSION_SECRET);
-     settings.remove(EXPIRES);
-     settings.remove(SIGNATURE);
+    if ((begin > -1) && (end > -1))
+        return urlString.mid(begin, end - begin + 1);
+    else
+        return QString();
+}
 
-     emit credentialsChanged(m_loginCredentials);
- }
+void FacebookAuthentication::urlChanged(const QUrl &url)
+{
+    qWarning() << __PRETTY_FUNCTION__ << url.toString();
+
+    /*
+      Redirects:
+        * Login with cookie failed:
+            1) http://m.facebook.com/login.php?api_key=cf77865a5070f2c2ba3b52cbf3371579&cancel_url=http://www.facebook.com/connect/login_failure.html&display=touch&fbconnect=1&next=http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&display=touch&cancel_url=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_failure.html&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&return_session=1&session_version=3&v=1.0&req_perms=publish_stream&app_id=286811277465&refsrc=http://www.facebook.com/login.php&fbb=ra985c5e9
+
+        * Login with cookie succeeded:
+            1) http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http://www.facebook.com/connect/login_success.html&display=touch&cancel_url=http://www.facebook.com/connect/login_failure.html&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&session={"session_key":"2.iHXi5fLKlHktva2R71xSAw__.3600.1289228400-100001006647973","uid":100001006647973,"expires":1289228400,"secret":"q4_Hn5qRdxnVT_qh3ztv5w__","sig":"c9d29ca857bacec48b952e7d2826a3ca"}&fbb=rb28f24e5
+            2) http://www.facebook.com/connect/login_success.html?perms=publish_stream&selected_profiles=100001006647973&session={"session_key":"2.iHXi5fLKlHktva2R71xSAw__.3600.1289228400-100001006647973","uid":"100001006647973","expires":1289228400,"secret":"q4_Hn5qRdxnVT_qh3ztv5w__","access_token":"286811277465|2.iHXi5fLKlHktva2R71xSAw__.3600.1289228400-100001006647973|LVTHGW82A98SGvv6Fl43DlCrFT0","sig":"8edd8d611047bcd162abbe9983b25a56"}
+     */
+
+    if (!url.toString().contains("session={")) {
+        // url parameter doesn't contain session data, so login with cookies failed
+        qWarning() << __PRETTY_FUNCTION__ << "working credentials required";
+        m_mainWindow->buildLoginDialog(m_browser);
+    } else if (url.toString().startsWith(FB_LOGIN_SUCCESS_URL)) {
+        // login succeeded
+        const QString session = parseSession(url);
+        qWarning() << __PRETTY_FUNCTION__ << "login finished, parsed session:" << session;
+        if (!session.isEmpty()) {
+            m_mainWindow->destroyLoginDialog();
+            m_browser->deleteLater();
+            emit loggedIn(session);
+        }
+    }
+    else {
+        qWarning() << __PRETTY_FUNCTION__ << "credentials accepted, getting the access_token";
+    }
+}