Debian Codegraph @

src/imports/Lomiri/Contacts/contacts.cpp

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