Debian Codegraph @

src/imports/Lomiri/Contacts/contacts.cpp

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