Debian Codegraph @

src/imports/Lomiri/Contacts/contacts.cpp

raw ◀ ▶
6 Debian patches touch this file
1 /*
2 * Copyright (C) 2012-2014 Canonical, Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 #include "contacts.h"
18 #include "imagescalethread.h"
19
20 #include <QtCore/QCoreApplication>
•21 #include <QSettings>
22 #include <QtCore/QStringList>
23 #include <QtCore/QDebug>
24 #include <QtCore/QDir>
25 #include <QtCore/QUrl>
•26 #include <QtCore/QMimeType>
27 #include <QtCore/QMimeDatabase>
28 #include <QtCore/QLockFile>
29 #include <QtCore/QThreadPool>
•30 #include <QtConcurrent/QtConcurrent>
31 #include <QContactManager>
•32 #include <QContactName>
33 #include <QContactFetchByIdRequest>
34 #include <QContactAbstractRequest>
35 #include <QContactFetchRequest>
36 #include <QContactAvatar>
•37 #include <QContactRelationship>
38 #include <QJSEngine>
39 #include <QJSValue>
40 #include <QVersitReader>
41 #include <QVersitResourceHandler>
42 #include <QVersitContactImporter>
•43 #include <QContactCollectionFilter>
44
45 #include "config.h"
•46
47 QTCONTACTS_USE_NAMESPACE
48 QTVERSIT_USE_NAMESPACE
49
50
51 // Helper class to store contact binary data into a temporary file
52 //
53 // QContactVcard only supports URL values for images. During a vcard import if the contact cotains
54 // an avatar, ringtone or any property formated in a binary data, QVersit will use the
55 // ContactExporterResourceHandler to store the binary data.
56 // The default implementation of QVersitResourceHandler does not store any data and that
57 // causes avatar data loss during the import process.
58 // This class will store the data into a temporary file and removes the file when the app gets destroyed.
59 // additionally move the avatar to its final location
60 class ContactExporterResourceHandler : public QVersitResourceHandler
61 {
62 public:
63 ContactExporterResourceHandler()
64 {
65 }
66
67 ~ContactExporterResourceHandler()
68 {
69 foreach (const QString& fileName, m_files) {
70 QFile::remove(fileName);
71 }
72
73 m_files.clear();
74 }
75
76 bool saveResource(const QByteArray& contents,
77 const QVersitProperty& property,
78 QString* location)
79 {
80 const QMimeType mt = QMimeDatabase().mimeTypeForData(contents);
81 QString extension(QStringLiteral("data"));
82 if (mt.isValid())
83 extension = mt.suffixes()[0];
84
85 // use property.name() to create a new file for each binary property (avatar, ringtone, etc...)
86 QTemporaryFile tmpFile(QString::fromLatin1("%1/%2_XXXXXX.%3")
87 .arg(QDir::tempPath())
88 .arg(property.name().toLower())
89 .arg(extension));
90 tmpFile.setAutoRemove(false);
91 if (tmpFile.open()) {
92
93 tmpFile.write(contents);
94 tmpFile.close();
95
96 QString destinationFilePath = tmpFile.fileName();
97 // only avatar for now
98 if (property.name().toLower() == "photo") {
99
100 QFileInfo tmpFileInfo(destinationFilePath);
101 QString targetPath = QDir::homePath() + AVATAR_STORAGE_PATH;
102 destinationFilePath = targetPath + "/" + tmpFileInfo.fileName();
103
104 if (!tmpFile.copy(destinationFilePath)) {
105 qWarning() << "Failed to copy avatar to " << destinationFilePath;
106 return false;
107 }
108 }
109
110 // the location expect a string in url format ex: file:///tmp/filename.png
111 *location = QUrl::fromLocalFile(destinationFilePath).toString();
112 // store temp file path for future removal
113 m_files << tmpFile.fileName();
114
115 return true;
116 }
117 return false;
118 }
119
120 bool loadResource(const QString &location, QByteArray *contents, QString *mimeType)
121 {
122 if (location.isEmpty())
123 return false;
124
125 QFile file(location);
126 if (!file.open(QIODevice::ReadOnly))
127 return false;
128
129 *contents = file.readAll();
130 const QMimeType mt = QMimeDatabase().mimeTypeForData(*contents);
131 if (mt.isValid())
132 *mimeType = mt.suffixes()[0];
133
134 return !contents->isEmpty();
135 }
136
137 QStringList m_files;
138 };
139
140 class ContactsPrivate
141 {
142 public:
143 ContactsPrivate(): mManager(0)
144 {
145 }
146 ~ContactsPrivate()
147 {
148 if (mManager)
149 delete mManager;
150 }
151
152 QContactManager* mManager;
153 QVersitReader mReader;
154 ContactExporterResourceHandler mResourceHandler;
155 };
156
157
158 LomiriContacts::LomiriContacts(QObject *parent)
159 : QObject(parent),
•160 d(new ContactsPrivate)
161 {
162 connect(&d->mReader, SIGNAL(stateChanged(QVersitReader::State)), this, SLOT(startImport(QVersitReader::State)));
163 }
164
165 LomiriContacts::~LomiriContacts()
166 {
167
168 }
169
170 QString LomiriContacts::tempPath() const
•171 {
172 return QDir::tempPath();
173 }
174
•175 QString LomiriContacts::aggregateCollectionId() const
176 {
177 return QString(AGGREGATE_COLLECTION_ID);
178 }
179
180 QString LomiriContacts::contactInitialsFromString(const QString &value)
181 {
182 if (value.isEmpty() || !value.at(0).isLetter()) {
183 return QString();
184 }
185
186 QString initials;
187 QStringList parts = value.split(" ");
188 initials = parts.first().at(0).toUpper();
189 if (parts.size() > 1) {
190 initials += parts.last().at(0).toUpper();
191 }
192
193 return initials;
194 }
195
196 QString LomiriContacts::normalized(const QString &value)
197 {
198 QString s2 = value.normalized(QString::NormalizationForm_D);
199 QString out;
200
201 for (int i=0, j=s2.length(); i<j; i++)
202 {
203 // strip diacritic marks
204 if (s2.at(i).category() != QChar::Mark_NonSpacing &&
205 s2.at(i).category() != QChar::Mark_SpacingCombining) {
206 out.append(s2.at(i));
207 }
208 }
209 return out;
210 }
211
•212 void LomiriContacts::importContacts(const QUrl &url)
213 {
214 // Reader is capable of handling only one request at the time.
215 qDebug() << "start importing url:" << url;
216
217 ImportError importError = ImportNotReadyError;
218 if (d->mReader.state() != QtVersit::QVersitReader::ActiveState) {
219
220 QFile* file = new QFile(url.toLocalFile());
221 bool ok = file->open(QIODevice::ReadOnly);
222 if (ok) {
223 d->mReader.setDevice(file);
224 if (d->mReader.startReading()) {
225 return;
226 }
227 importError = LomiriContacts::ImportError(d->mReader.error());
228 } else {
229 importError = ImportIOError;
230 }
231 }
232
233 qDebug() << "import error" << importError;
234 emit importCompleted(importError, QStringList());
235 }
236
237 void LomiriContacts::removeAggregateContacts(const QStringList &aggregateIds, const QJSValue &callback)
238 {
239
240 QtConcurrent::run([=]() {
241
•242 // we look at read-only collections
243 QContactManager* mManager = new QContactManager(QString(DEFAULT_CONTACT_MANAGER));
•244 QList<QContactCollection> collections = mManager->collections();
245 QList<QString> readOnlyCollections;
246 QSet<QContactCollectionId> roCollections;
247 for (auto &col: collections) {
248 if (col.extendedMetaData("ReadOnly").toBool()) {
249 readOnlyCollections << col.id().toString();
250 roCollections << col.id();
251 }
252 }
253
•254 QList<QContactId> roContacts;
255 if (roCollections.size() > 0) {
256 QContactCollectionFilter collectionFilter;
257 collectionFilter.setCollectionIds(roCollections);
258 // get all readonly-contacts
259 roContacts = mManager->contactIds(collectionFilter);
260 }
261
262 QMap<int, QContactManager::Error> errorMap;
263 bool success = true;
264
•265 const int batchSize = qMin(200, aggregateIds.size());
266 QList<QContactId> ctIdsToRemove;
267 for (auto &aggregateId: aggregateIds) {
268 QList<QContactRelationship> rels = mManager->relationships(QContactRelationship::Aggregates(), QContactId::fromString(aggregateId), QContactRelationship::First);
269 for (auto &rel: rels) {
270 QContactId cid = rel.second();
•271 // we will not remove read-only contact, since it will break sync
272 if (!roContacts.contains(cid)) {
273 ctIdsToRemove << cid;
274 }
275 }
276
277 if (ctIdsToRemove.size() >= batchSize) {
•278 qDebug() << "removing:" << ctIdsToRemove.size() << " contacts";
279 success = mManager->removeContacts(ctIdsToRemove, &errorMap);
280 if (Q_UNLIKELY(!errorMap.isEmpty())) {
281 qWarning() << "Errors while removing contacts:" << errorMap;
282 success = false;
283 }
284 ctIdsToRemove.clear();
285 }
•286 }
287
•288 if (ctIdsToRemove.size() > 0) {
•289 qDebug() << "removing:" << ctIdsToRemove.size() << " contacts";
290 success = mManager->removeContacts(ctIdsToRemove, &errorMap);
•291 if (Q_UNLIKELY(!errorMap.isEmpty())) {
292 qWarning() << "Errors while removing contacts:" << errorMap;
293 success = false;
294 }
295 }
296
297 mManager->deleteLater();
298
299 QJSValue cbCopy(callback);
300 QJSEngine *engine = qjsEngine(this);
301 cbCopy.call(QJSValueList { engine->toScriptValue(success) });
302 });
303
304 }
305
306 void LomiriContacts::startImport(QVersitReader::State state)
307 {
308
309 if (state == QVersitReader::FinishedState || state == QVersitReader::CanceledState) {
310 QVersitContactImporter importer;
311 importer.setResourceHandler(&d->mResourceHandler);
312 importer.importDocuments(d->mReader.results());
313
314 QList<QContact> contacts = importer.contacts();
•315 qDebug() << "Found " << contacts.size() << " contacts";
316
317
318 delete d->mReader.device();
319 d->mReader.setDevice(0);
320
321 QStringList ids;
322 if (!d->mManager) {
323 d->mManager = new QContactManager(QString(DEFAULT_CONTACT_MANAGER));
324 }
325
326 if (d->mManager) {
327
•328 // paginating
329 int offset = 0;
330 int batchSize = 200;
331
332 while (offset <= contacts.size() -1) {
333
334 batchSize = qMin(contacts.size()-offset, 200);
335
336 QMap<int, QContactManager::Error> errorMap;
337 QList<QContact> cts = contacts.mid(offset, batchSize);
338 d->mManager->saveContacts(&cts, &errorMap);
339 if (Q_UNLIKELY(!errorMap.isEmpty())) {
340 qWarning() << "Errors while saving contacts:" << errorMap;
341 emit importCompleted(LomiriContacts::ImportUnspecifiedError, ids);
342 } else {
343 foreach (const QContact &c, cts) {
344 ids << c.id().toString();
345 }
346 }
•347 qDebug() << "imported batch from " << offset << " to " << offset + batchSize;
348 offset += batchSize;
349 }
•350
351
352 }
353
354 emit importCompleted(LomiriContacts::ImportError(d->mReader.error()), ids);
355 }
356 }
357
358 QString LomiriContacts::copyImage(const QUrl &imageUrl)
359 {
360 ImageScaleThread *imgThread = new ImageScaleThread(imageUrl, this);
361 QThreadPool::globalInstance()->start(imgThread);
362 return imgThread->id();
363 }
364
365 QUrl LomiriContacts::storeAvatarImage(const QUrl &imageUrl)
366 {
367
368 QFileInfo tmpFileInfo(imageUrl.toLocalFile());
369 QString targetPath = QDir::homePath() + AVATAR_STORAGE_PATH;
370 QString toFile = targetPath + "/" + tmpFileInfo.fileName();
371
372 if (!QFile::copy(imageUrl.toLocalFile(), toFile)) {
373 qWarning() << "Failed to copy avatar to " << toFile;
374 return imageUrl;
•375 } else {
376 qDebug() << "copied avatar to" << toFile;
377 }
378 return QUrl(toFile);
379 }
380
381 bool LomiriContacts::containsLetters(const QString &value)
382 {
383 foreach (const QChar &c, value) {
384 if (c.isLetter()) {
385 return true;
386 }
387 }
388 return false;
389 }
390
391 bool LomiriContacts::removeFile(const QUrl &file)
392 {
393 QString localFile = file.toLocalFile();
394 if (!localFile.isEmpty() && QFile::exists(localFile)) {
395 return QFile::remove(localFile);
396 }
397 return false;
398 }
399
400 QUrl LomiriContacts::tempFile(const QString &templateName)
401 {
402 QTemporaryFile tmp(QString("%1/%2").arg(tempPath()).arg(templateName));
403 tmp.setAutoRemove(false);
404 if (tmp.open())
405 return QUrl::fromLocalFile(tmp.fileName());
406 else
407 return QUrl();
408 }
409
410 uint LomiriContacts::qHash(const QString &str)
411 {
412 return ::qHash(str);
413 }
414
415 QString LomiriContacts::defaultCollectionId() const
416 {
417 QSettings settings;
418 return settings.value(SETTINGS_DEFAULT_COLLECTION_ID, DEFAULT_COLLECTION_ID).toString();
•419 }
420
421 void LomiriContacts::setDefaultCollectionId(const QString &newDefaultCollectionId)
422 {
423 QSettings settings;
424 settings.setValue(SETTINGS_DEFAULT_COLLECTION_ID, newDefaultCollectionId);
425 settings.sync();
426 emit defaultCollectionIdChanged();
427 }