/* * Copyright (C) 2012-2014 Canonical, Ltd. * * 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; version 3. * * 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 . */ #include "contacts.h" #include "imagescalethread.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "config.h" QTCONTACTS_USE_NAMESPACE QTVERSIT_USE_NAMESPACE // Helper class to store contact binary data into a temporary file // // QContactVcard only supports URL values for images. During a vcard import if the contact cotains // an avatar, ringtone or any property formated in a binary data, QVersit will use the // ContactExporterResourceHandler to store the binary data. // The default implementation of QVersitResourceHandler does not store any data and that // causes avatar data loss during the import process. // This class will store the data into a temporary file and removes the file when the app gets destroyed. // additionally move the avatar to its final location class ContactExporterResourceHandler : public QVersitResourceHandler { public: ContactExporterResourceHandler() { } ~ContactExporterResourceHandler() { foreach (const QString& fileName, m_files) { QFile::remove(fileName); } m_files.clear(); } bool saveResource(const QByteArray& contents, const QVersitProperty& property, QString* location) { const QMimeType mt = QMimeDatabase().mimeTypeForData(contents); QString extension(QStringLiteral("data")); if (mt.isValid()) extension = mt.suffixes()[0]; // use property.name() to create a new file for each binary property (avatar, ringtone, etc...) QTemporaryFile tmpFile(QString::fromLatin1("%1/%2_XXXXXX.%3") .arg(QDir::tempPath()) .arg(property.name().toLower()) .arg(extension)); tmpFile.setAutoRemove(false); if (tmpFile.open()) { tmpFile.write(contents); tmpFile.close(); QString destinationFilePath = tmpFile.fileName(); // only avatar for now if (property.name().toLower() == "photo") { QFileInfo tmpFileInfo(destinationFilePath); QString targetPath = QDir::homePath() + AVATAR_STORAGE_PATH; destinationFilePath = targetPath + "/" + tmpFileInfo.fileName(); if (!tmpFile.copy(destinationFilePath)) { qWarning() << "Failed to copy avatar to " << destinationFilePath; return false; } } // the location expect a string in url format ex: file:///tmp/filename.png *location = QUrl::fromLocalFile(destinationFilePath).toString(); // store temp file path for future removal m_files << tmpFile.fileName(); return true; } return false; } bool loadResource(const QString &location, QByteArray *contents, QString *mimeType) { if (location.isEmpty()) return false; QFile file(location); if (!file.open(QIODevice::ReadOnly)) return false; *contents = file.readAll(); const QMimeType mt = QMimeDatabase().mimeTypeForData(*contents); if (mt.isValid()) *mimeType = mt.suffixes()[0]; return !contents->isEmpty(); } QStringList m_files; }; class ContactsPrivate { public: ContactsPrivate(): mManager(0) { } ~ContactsPrivate() { if (mManager) delete mManager; } QContactManager* mManager; QVersitReader mReader; ContactExporterResourceHandler mResourceHandler; }; LomiriContacts::LomiriContacts(QObject *parent) : QObject(parent), d(new ContactsPrivate) { connect(&d->mReader, SIGNAL(stateChanged(QVersitReader::State)), this, SLOT(startImport(QVersitReader::State))); } LomiriContacts::~LomiriContacts() { } QString LomiriContacts::tempPath() const { return QDir::tempPath(); } QString LomiriContacts::aggregateCollectionId() const { return QString(AGGREGATE_COLLECTION_ID); } QString LomiriContacts::contactInitialsFromString(const QString &value) { if (value.isEmpty() || !value.at(0).isLetter()) { return QString(); } QString initials; QStringList parts = value.split(" "); initials = parts.first().at(0).toUpper(); if (parts.size() > 1) { initials += parts.last().at(0).toUpper(); } return initials; } QString LomiriContacts::normalized(const QString &value) { QString s2 = value.normalized(QString::NormalizationForm_D); QString out; for (int i=0, j=s2.length(); imReader.state() != QtVersit::QVersitReader::ActiveState) { QFile* file = new QFile(url.toLocalFile()); bool ok = file->open(QIODevice::ReadOnly); if (ok) { d->mReader.setDevice(file); if (d->mReader.startReading()) { return; } importError = LomiriContacts::ImportError(d->mReader.error()); } else { importError = ImportIOError; } } qDebug() << "import error" << importError; emit importCompleted(importError, QStringList()); } void LomiriContacts::removeAggregateContacts(const QStringList &aggregateIds, const QJSValue &callback) { QtConcurrent::run([=]() { // we look at read-only collections QContactManager* mManager = new QContactManager(QString(DEFAULT_CONTACT_MANAGER)); QList collections = mManager->collections(); QList readOnlyCollections; QSet roCollections; for (auto &col: collections) { if (col.extendedMetaData("ReadOnly").toBool()) { readOnlyCollections << col.id().toString(); roCollections << col.id(); } } QList roContacts; if (roCollections.size() > 0) { QContactCollectionFilter collectionFilter; collectionFilter.setCollectionIds(roCollections); // get all readonly-contacts roContacts = mManager->contactIds(collectionFilter); } QMap errorMap; bool success = true; const int batchSize = qMin(200, aggregateIds.size()); QList ctIdsToRemove; for (auto &aggregateId: aggregateIds) { QList rels = mManager->relationships(QContactRelationship::Aggregates(), QContactId::fromString(aggregateId), QContactRelationship::First); for (auto &rel: rels) { QContactId cid = rel.second(); // we will not remove read-only contact, since it will break sync if (!roContacts.contains(cid)) { ctIdsToRemove << cid; } } if (ctIdsToRemove.size() >= batchSize) { qDebug() << "removing:" << ctIdsToRemove.size() << " contacts"; success = mManager->removeContacts(ctIdsToRemove, &errorMap); if (Q_UNLIKELY(!errorMap.isEmpty())) { qWarning() << "Errors while removing contacts:" << errorMap; success = false; } ctIdsToRemove.clear(); } } if (ctIdsToRemove.size() > 0) { qDebug() << "removing:" << ctIdsToRemove.size() << " contacts"; success = mManager->removeContacts(ctIdsToRemove, &errorMap); if (Q_UNLIKELY(!errorMap.isEmpty())) { qWarning() << "Errors while removing contacts:" << errorMap; success = false; } } mManager->deleteLater(); QJSValue cbCopy(callback); QJSEngine *engine = qjsEngine(this); cbCopy.call(QJSValueList { engine->toScriptValue(success) }); }); } void LomiriContacts::startImport(QVersitReader::State state) { if (state == QVersitReader::FinishedState || state == QVersitReader::CanceledState) { QVersitContactImporter importer; importer.setResourceHandler(&d->mResourceHandler); importer.importDocuments(d->mReader.results()); QList contacts = importer.contacts(); qDebug() << "Found " << contacts.size() << " contacts"; delete d->mReader.device(); d->mReader.setDevice(0); QStringList ids; if (!d->mManager) { d->mManager = new QContactManager(QString(DEFAULT_CONTACT_MANAGER)); } if (d->mManager) { // paginating int offset = 0; int batchSize = 200; while (offset <= contacts.size() -1) { batchSize = qMin(contacts.size()-offset, 200); QMap errorMap; QList cts = contacts.mid(offset, batchSize); d->mManager->saveContacts(&cts, &errorMap); if (Q_UNLIKELY(!errorMap.isEmpty())) { qWarning() << "Errors while saving contacts:" << errorMap; emit importCompleted(LomiriContacts::ImportUnspecifiedError, ids); } else { foreach (const QContact &c, cts) { ids << c.id().toString(); } } qDebug() << "imported batch from " << offset << " to " << offset + batchSize; offset += batchSize; } } emit importCompleted(LomiriContacts::ImportError(d->mReader.error()), ids); } } QString LomiriContacts::copyImage(const QUrl &imageUrl) { ImageScaleThread *imgThread = new ImageScaleThread(imageUrl, this); QThreadPool::globalInstance()->start(imgThread); return imgThread->id(); } QUrl LomiriContacts::storeAvatarImage(const QUrl &imageUrl) { QFileInfo tmpFileInfo(imageUrl.toLocalFile()); QString targetPath = QDir::homePath() + AVATAR_STORAGE_PATH; QString toFile = targetPath + "/" + tmpFileInfo.fileName(); if (!QFile::copy(imageUrl.toLocalFile(), toFile)) { qWarning() << "Failed to copy avatar to " << toFile; return imageUrl; } else { qDebug() << "copied avatar to" << toFile; } return QUrl(toFile); } bool LomiriContacts::containsLetters(const QString &value) { foreach (const QChar &c, value) { if (c.isLetter()) { return true; } } return false; } bool LomiriContacts::removeFile(const QUrl &file) { QString localFile = file.toLocalFile(); if (!localFile.isEmpty() && QFile::exists(localFile)) { return QFile::remove(localFile); } return false; } QUrl LomiriContacts::tempFile(const QString &templateName) { QTemporaryFile tmp(QString("%1/%2").arg(tempPath()).arg(templateName)); tmp.setAutoRemove(false); if (tmp.open()) return QUrl::fromLocalFile(tmp.fileName()); else return QUrl(); } uint LomiriContacts::qHash(const QString &str) { return ::qHash(str); } QString LomiriContacts::defaultCollectionId() const { QSettings settings; return settings.value(SETTINGS_DEFAULT_COLLECTION_ID, DEFAULT_COLLECTION_ID).toString(); } void LomiriContacts::setDefaultCollectionId(const QString &newDefaultCollectionId) { QSettings settings; settings.setValue(SETTINGS_DEFAULT_COLLECTION_ID, newDefaultCollectionId); settings.sync(); emit defaultCollectionIdChanged(); }