summaryrefslogtreecommitdiff
path: root/src/sync/googlesynchandler.cpp
blob: 90de34b4f6f4f1591aaea239a3bede80ab16c545 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/* ============================================================
*
* This file is a part of the rekonq project
*
* Copyright (C) 2012 by Siteshwar Vashisht <siteshwar at gmail dot com>
* Copyright (C) 2011 by Andrea Diamantini <adjam7 at gmail dot com>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License or (at your option) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* ============================================================ */


// Self Includes
#include "googlesynchandler.h"
#include "googlesynchandler.moc"

// Auto Includes
#include "rekonq.h"

// Local Includes
#include "application.h"
#include "bookmarkmanager.h"

// KDE Includes
#include <KStandardDirs>
#include <klocalizedstring.h>
#include <kbookmarkmanager.h>

#include <QList>
#include <QWebPage>
#include <QWebFrame>
#include <QWebElement>
#include <QUrl>
#include <QWebSettings>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDomDocument>


GoogleSyncHandler::GoogleSyncHandler(QObject *parent)
    : SyncHandler(parent)
    , _mode(RECEIVE_CHANGES)
    , _doLogin(false)
    , _isSyncing(false)
    , _reply(0)
    , _requestCount(0)
{
    kDebug() << "Creating Google Bookmarks handler...";
    _webPage.settings()->setAttribute(QWebSettings::AutoLoadImages, false);
    _webPage.settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
    connect(&_webPage, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
}


void GoogleSyncHandler::initialLoadAndCheck()
{
    if (!ReKonfig::syncEnabled())
    {
        _firstTimeSynced = false;
        return;
    }

    // Bookmarks
    if (ReKonfig::syncBookmarks())
    {
        _mode = RECEIVE_CHANGES;
        startLogin();
    }

    if (ReKonfig::syncHistory())
    {
        emit syncStatus(Rekonq::History, false, i18n("Not supported!"));
    }

    if (ReKonfig::syncHistory())
    {
        emit syncStatus(Rekonq::Passwords, false, i18n("Not supported!"));
    }
}


bool GoogleSyncHandler::syncRelativeEnabled(bool check)
{
    if (!ReKonfig::syncEnabled())
        return false;

    if (!_firstTimeSynced)
        return false;

    return check;
}


// ---------------------------------------------------------------------------------------


void GoogleSyncHandler::syncHistory()
{
    kDebug() << "Syncing history not supported!";
    emit syncStatus(Rekonq::History, false, i18n("Syncing history not supported!"));
    emit syncHistoryFinished(false);
}


void GoogleSyncHandler::syncPasswords()
{
    kDebug() << "Syncing passwords not supported!";
    emit syncStatus(Rekonq::Passwords, false, i18n("Syncing passwords not supported!"));
    emit syncPasswordsFinished(false);
}


void GoogleSyncHandler::syncBookmarks()
{

    if (_isSyncing)
    {
        kDebug() << "Sync already in progress!";
        return;
    }
    _mode = SEND_CHANGES;
    startLogin();
}

void GoogleSyncHandler::startLogin()
{
    if (ReKonfig::syncUser().isEmpty() || ReKonfig::syncPass().isEmpty())
    {
        kDebug() << "No username or password!";
        emit syncStatus(Rekonq::Bookmarks, false, i18n("No username or password!"));
        emit syncBookmarksFinished(false);
        return;
    }

    _isSyncing = true;

    _doLogin = true;

    kDebug() << "Loading login page...";
    _webPage.mainFrame()->load(QUrl("http://bookmarks.google.com/"));
}

//Loading a webpage finished, what action to take is decided based on url we have loaded.
void GoogleSyncHandler::loadFinished(bool ok)
{
    kDebug() << "Load Finished" << ok;
    if (!ok)
    {
        kDebug() << "Error loading: " << _webPage.mainFrame()->url();
        emit syncStatus(Rekonq::Bookmarks, false, i18n("Error loading: " + _webPage.mainFrame()->url().toEncoded()));

        _isSyncing = false;
        return;
    }

    kDebug() << _webPage.mainFrame()->url();
    kDebug() << "Path : " << _webPage.mainFrame()->url().path();

    QString path = _webPage.mainFrame()->url().path();

    if (path == "/ServiceLogin" && _doLogin == true)
    {
        // Let's login to our Google account
        QWebFrame *frame = _webPage.mainFrame();

        QWebElement email = frame->findFirstElement("#Email");
        QWebElement passwd = frame->findFirstElement("#Passwd");
        QWebElement form = frame->findFirstElement("#gaia_loginform");



        email.setAttribute("value", ReKonfig::syncUser());
        passwd.setAttribute("value", ReKonfig::syncPass());
        form.evaluateJavaScript("this.submit();");
        emit syncStatus(Rekonq::Bookmarks, true, i18n("Signing in..."));

        // Login only once
        _doLogin = false;
    }
    else if (path == "/bookmarks/")
    {
        // We get to this page after successful login, let's fetch the bookmark list in Xml format.
        QNetworkAccessManager *qnam = _webPage.networkAccessManager();
        QNetworkRequest request;
        request.setUrl(QUrl("http://www.google.com/bookmarks/?output=xml"));
        _reply = qnam->get(request);
        emit syncStatus(Rekonq::Bookmarks, true, i18n("Fetching bookmarks from server..."));
        connect(_reply, SIGNAL(finished()), this, SLOT(fetchingBookmarksFinished()));
    }
    else if (path == "/ServiceLoginAuth")
    {
        emit syncStatus(Rekonq::Bookmarks, false, i18n("Login failed!"));
        _isSyncing = false;
    }
    else if (path == "/bookmarks/mark")
    {
        QWebFrame *frame = _webPage.mainFrame();

        QString sigKey = frame->findFirstElement("input[name=sig]").attribute("value");
        kDebug() << "Signature Key is : " << sigKey;

        QNetworkAccessManager *qnam = _webPage.networkAccessManager();

        if (!_bookmarksToDelete.isEmpty())
        {

            for (QSet<QString>::const_iterator iter = _bookmarksToDelete.constBegin(); iter != _bookmarksToDelete.end(); ++iter)
            {
                QNetworkRequest request;
                request.setUrl(QUrl("https://www.google.com/bookmarks/mark?dlq=" + *iter + "&sig=" + sigKey));

                kDebug() << "Delete url is : " << request.url();
                QNetworkReply *r = qnam->get(request);
                connect(r, SIGNAL(finished()), this, SLOT(updateBookmarkFinished()));
                ++_requestCount;
            }
        }

        if (!_bookmarksToAdd.isEmpty())
        {
            emit syncStatus(Rekonq::Bookmarks, true, i18n("Adding bookmarks on server..."));
            for (QSet<KUrl>::const_iterator iter = _bookmarksToAdd.constBegin(); iter != _bookmarksToAdd.end(); ++iter)
            {
                KBookmark bookmark = rApp->bookmarkManager()->bookmarkForUrl(*iter);
                QByteArray postData;
                postData.append("bkmk=" + QUrl::toPercentEncoding(bookmark.url().url().toUtf8()));
                postData.append("&title=" + QUrl::toPercentEncoding(bookmark.text().toUtf8()));
                postData.append("&annotation=");
                postData.append("&labels=");
                postData.append("&prev=/lookup");
                postData.append("&sig=" + sigKey.toUtf8());

                QNetworkRequest request;
                request.setUrl(QUrl("https://www.google.com/bookmarks/mark?sig=" + sigKey + "&btnA"));
                request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
                kDebug() << "Url: " << request.url();
                kDebug() << "Post data is :" << postData;
                QNetworkReply *r = qnam->post(request, postData);
                connect(r, SIGNAL(finished()), this, SLOT(updateBookmarkFinished()));
                ++_requestCount;
            }
        }

        _bookmarksToDelete.clear();
        _bookmarksToAdd.clear();

    }
    else if (path == "/Logout")
    {
        //Session finished
        emit syncStatus(Rekonq::Bookmarks, true, i18n("Done!"));
        emit syncBookmarksFinished(true);
        _isSyncing = false;
    }
    else
    {
        kDebug() << "Unknown Response!";
        _isSyncing = false;
    }

}

//We received bookmarks stored on server in xml format, now take the action based on which mode we are in.
void GoogleSyncHandler::fetchingBookmarksFinished()
{
    QString data = _reply->readAll();

    QDomDocument doc("bookmarks");
    doc.setContent(data);

    QDomNodeList bookmarksOnServer = doc.elementsByTagName("bookmark");
    emit syncStatus(Rekonq::Bookmarks, true, i18n("Reading bookmarks..."));

    BookmarkManager *manager = rApp->bookmarkManager();
    KBookmarkGroup root = manager->rootGroup();


    if (_mode == RECEIVE_CHANGES)
    {

        for (int i = 0; i < bookmarksOnServer.size(); ++i)
        {

            QString title = getChildElement(bookmarksOnServer.at(i), "title");
            QString url = getChildElement(bookmarksOnServer.at(i), "url");

            KBookmark bookmark = manager->bookmarkForUrl(KUrl(url));
            if (bookmark.isNull())
            {
                //Add bookmark
                kDebug() << "Add bookmark";
                emit syncStatus(Rekonq::Bookmarks, true, i18n("Adding bookmark "));
                root.addBookmark(title.isEmpty() ? url : title, KUrl(url));
                manager->manager()->emitChanged(root);
            }

        }

        // After receiving changes, we compare local bookmarks with Google bookmarks and if some bookmarks exist locally but not on Google Bookmarks, we add them.
        checkToAddGB(root, bookmarksOnServer);

        if (!_bookmarksToAdd.isEmpty())
        {
            kDebug() << "Getting sigkey";
            _webPage.mainFrame()->load(QUrl("https://www.google.com/bookmarks/mark?op=add&hl=en"));
        }
        else
        {
            _webPage.mainFrame()->load(QUrl("https://accounts.google.com/Logout?hl=en"));
            emit syncStatus(Rekonq::Bookmarks, true, i18n("Signing out..."));
        }
    }
    else
    {
        checkToAddGB(root, bookmarksOnServer);
        checkToDeleteGB(manager, bookmarksOnServer);

        if (!_bookmarksToAdd.isEmpty() || !_bookmarksToDelete.isEmpty())
        {
            kDebug() << "Getting sigkey";
            _webPage.mainFrame()->load(QUrl("https://www.google.com/bookmarks/mark?op=add&hl=en"));
        }
        else
        {
            _webPage.mainFrame()->load(QUrl("https://accounts.google.com/Logout?hl=en"));
            emit syncStatus(Rekonq::Bookmarks, true, i18n("Signing out..."));
        }
    }

    _reply->deleteLater();
}

//Get value of a child element of a dom node
QString GoogleSyncHandler::getChildElement(const QDomNode &node, QString name)
{
    QDomNodeList nodes = node.childNodes();

    for (int j = 0; j < nodes.size(); ++j)
    {
        QDomElement element = nodes.at(j).toElement();

        if (nodes.at(j).nodeName() == name)
        {
            //kDebug() << "Url : " << element.text();
            return element.text();
        }
    }
    return NULL;
}

//This method checks whether we have any other bookmarks than the ones which exist on the server
void GoogleSyncHandler::checkToAddGB(const KBookmarkGroup &root, const QDomNodeList &bookmarksOnServer)
{
    KBookmark current = root.first();

    while (!current.isNull())
    {
        kDebug() << "Checking Url to add on Google Bookmarks: " << current.url();
        bool found = false;
        for (int i = 0; i < bookmarksOnServer.count(); ++i)
        {
            if (current.isGroup())
            {
                kDebug() << "Checking group" << current.text();
                checkToAddGB(current.toGroup(), bookmarksOnServer);
                //skip adding a blank in _bookmarksToAdd
                found = true;
                break;
            }
            else if (current.url().url() == getChildElement(bookmarksOnServer.at(i), "url"))
            {
                found = true;
            }
        }

        if (!found)
        {
            kDebug() <<  "Adding to Google Bookmarks: " << current.url().url();
            _bookmarksToAdd.insert(current.url());
        }
        current = root.next(current);
    }
}

//Check whether we need to delete bookmarks while sending changes to Google Bookmarks
void GoogleSyncHandler::checkToDeleteGB(BookmarkManager *manager, const QDomNodeList &bookmarksOnServer)
{

    for (int i = 0; i < bookmarksOnServer.count(); ++i)
    {
        QString url = getChildElement(bookmarksOnServer.at(i), "url");

        KBookmark result = manager->bookmarkForUrl(KUrl(url));
        if (result.isNull())
        {
            kDebug() <<  "Deleting from Google Bookmarks: " << url;
            _bookmarksToDelete.insert(getChildElement(bookmarksOnServer.at(i), "id"));
        }
    }

}


//Added or deleted a bookmark on server, check whether we succeed here, and logout when all requests are done!
void GoogleSyncHandler::updateBookmarkFinished()
{
    --_requestCount;
    QNetworkReply *reply = dynamic_cast<QNetworkReply*>(sender());
    if (reply->error() != QNetworkReply::NoError)
        kDebug() << "Network Error while adding bookmark to server, code is: " << reply->error();
    else if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) != 302)
        kDebug() << "Unexpected reply : " << reply->readAll();
    else
        kDebug() << "Success!";

    if (_requestCount <= 0)
    {
        _webPage.mainFrame()->load(QUrl("https://accounts.google.com/Logout?hl=en"));
        emit syncStatus(Rekonq::Bookmarks, true, i18n("Signing out..."));
    }

}