source: SMSSender/frontend/business/contactimporter/googlecontactimporter_base.cpp @ 402:7a70b0942920

Last change on this file since 402:7a70b0942920 was 402:7a70b0942920, checked in by Sämy Zehnder <saemy.zehnder@…>, 6 years ago
  • Prints error when the import of a contact fails.
  • Fixes bug where the base and not the frontend specific google contact importer was used.
File size: 6.8 KB
Line 
1/*
2 smssender - A frontend for fast and easy SMS sending over different gateways.
3 Copyright (C) 2007-2014, gorrión. See http://smssender.gorrion.ch
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18#include "googlecontactimporter_base.h"
19
20#include <QRegExp>
21
22#include "common/domain/scontact.h"
23#include "common/domain/snumber.h"
24#include "common/exceptions/eexception.h"
25#include "common/network/snetworkreply.h"
26#include "frontend/business/contactimporter/googlecontactimporter.h"
27
28BaseGoogleContactImporter::BaseGoogleContactImporter(const BaseGoogleContactImporter::AuthData &authData)
29    : m_authData(authData)
30{
31    m_httpHelper.addTrustedCA(":/certs/Equifax_Secure_Certificate_Authority.crt");
32}
33
34void BaseGoogleContactImporter::importContacts(QSet<SContact *> *contacts) {
35    // TODO Use OAuth2
36    requestAuthToken();
37    m_httpHelper.defaultHeaders().insert("GData-Version", "3.0");
38
39    QString nextUrl = "http://www.google.com/m8/feeds/contacts/default/full?max-results=10000";
40    do {
41        QString contactsFeed =
42                QString::fromUtf8(m_httpHelper.syncGet(nextUrl)->readAll());
43        contactsFeed = SNetworkHelper::urldecodeString(contactsFeed);
44        parseContactsFeed(contactsFeed, contacts);
45
46        QRegExp rx("<link rel='next' type='application/atom\\+xml' href='([^']+)'/>");
47        if (rx.indexIn(contactsFeed) != -1) {
48            nextUrl = rx.cap(1);
49        } else {
50            break;
51        }
52    } while (true);
53}
54
55void BaseGoogleContactImporter::parseContactsFeed(const QString &feed, QSet<SContact *> *contacts) {
56    /*<entry gd:etag=""SXszeTVSLyt7ImA9WxFbFk8ORQU."">
57        <id>http://www.google.com/m8/feeds/contacts/saemy.zehnder%40gmail.com/base/59ea8d658e87e360</id>
58        <updated>2010-07-08T21:23:38.581Z</updated>
59        <app:edited>2010-07-08T21:23:38.581Z</app:edited>
60        <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/>
61        <title>test2</title>
62        <link rel="http://schemas.google.com/contacts/2008/rel#photo" type="image/%avoidwarninghere%*" href="http://www.google.com/m8/feeds/photos/media/saemy.zehnder%40gmail.com/59ea8d658e87e360" gd:etag=""VxFIFH0fSit7ImA0G0AqEU8PIQEjJkMyazA.""/>
63        <link rel="self" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/saemy.zehnder%40gmail.com/thin/59ea8d658e87e360"/>
64        <link rel="edit" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/saemy.zehnder%40gmail.com/thin/59ea8d658e87e360"/>
65        <gd:name>
66            <gd:fullName>test2</gd:fullName>
67            <gd:givenName>test2</gd:givenName>
68        </gd:name>
69        <gContact:nickname>nick1</gContact:nickname>
70        <gd:phoneNumber rel="http://schemas.google.com/g/2005#mobile">+41 079 12345 67</gd:phoneNumber>
71        <gd:phoneNumber rel="http://schemas.google.com/g/2005#mobile">+41 079 12345 68</gd:phoneNumber>
72        <gContact:groupMembershipInfo deleted="false" href="http://www.google.com/m8/feeds/groups/saemy.zehnder%40gmail.com/base/6"/>
73      </entry> */
74    QRegExp rx("<entry.*>(.*)</entry>");
75    rx.setMinimal(true);
76
77    int pos = 0;
78    while ((pos = rx.indexIn(feed, pos)) != -1) {
79        pos += rx.matchedLength();
80
81        try {
82            QString entry = rx.cap(1);
83
84            QRegExp rx2;
85            rx2.setMinimal(true);
86
87            rx2.setPattern("<gd:name>.*<gd:fullName>(.*)</gd:fullName>.*</gd:name>");
88            if (rx2.indexIn(entry) == -1) continue;
89            QString name = rx2.cap(1);
90
91            rx2.setPattern("<gd:phoneNumber rel='http://schemas.google.com/g/2005#mobile'.*>(.*)</gd:phoneNumber>");
92            if (rx2.indexIn(entry) == -1) continue;
93            SNumber number(rx2.cap(1));
94
95            if (!name.isEmpty() && number.isValid()) {
96                QScopedPointer<SContact> contact(new SContact);
97                contact->setName(name);
98                contact->setNumber(number);
99
100                parseEntry(entry, contact.data());
101
102                contacts->insert(contact.take());
103            }
104        } catch (EException &e) {
105            // don't fail to import all contacts because of one...
106            qWarning() << "Failed to import contact: " << e.chainedWhat();
107        } catch (...) {
108            qWarning() << "Failed to import contact: Unknown reason.";
109        }
110    }
111}
112
113void BaseGoogleContactImporter::parseEntry(const QString &entry, SContact *contact) {
114    QRegExp rx("<gContact:nickname>(.*)</gContact:nickname>");
115    rx.setMinimal(true);
116
117    if ((rx.indexIn(entry) != -1) && !rx.cap(1).isEmpty()) {
118        //qDebug() << rx.cap(1);
119        QStringList aliases;
120        aliases.append(rx.cap(1));
121        contact->setAliases(aliases);
122    }
123
124}
125
126void BaseGoogleContactImporter::requestAuthToken() {
127    QList<IParam*> posts;
128    posts.append(new SKeyValueParam("accountType", "GOOGLE"));
129    posts.append(new SKeyValueParam("Email", m_authData.username.toUtf8()));
130    posts.append(new SKeyValueParam("Passwd", m_authData.password.toUtf8()));
131    posts.append(new SKeyValueParam("service", "cp"));
132    posts.append(new SKeyValueParam("source", "gorrion-smssender-3"));
133
134    QString result;
135    try {
136        result = m_httpHelper.syncPost(QUrl::fromEncoded("https://www.google.com/accounts/ClientLogin"), posts)->readAll();
137    } catch (EException &e) {
138        result = "";
139    }
140
141    QRegExp rx("Auth=(\\S+)");
142    if (rx.indexIn(result) != -1) {
143        m_httpHelper.defaultHeaders().insert("Authorization", QString("GoogleLogin auth=" + rx.cap(1)).toUtf8());
144    } else {
145        EException("Login failed. You have probably entered incorrect userdata.")
146                .raise();
147    }
148}
149
150SNetworkHelper *BaseGoogleContactImporter::httpHelper() {
151    return &m_httpHelper;
152}
153
154
155/********************************** BUILDER ***********************************/
156
157
158QString BaseGoogleContactImporter::Builder::description() const {
159    return QObject::tr("Import contacts from Google contacts.");
160}
161
162bool BaseGoogleContactImporter::Builder::isApplicable() const {
163    return true;
164}
165
166void BaseGoogleContactImporter::Builder::init() {
167    m_authData.username.clear();
168    m_authData.password.clear();
169}
170
171void BaseGoogleContactImporter::Builder::createImporters(
172        QSet<IContactImporter *> *importers) {
173    importers->insert(new GoogleContactImporter(m_authData));
174}
Note: See TracBrowser for help on using the repository browser.