address-book-service-0.1.1+14.04.20140408.3/0000755000015301777760000000000012321057642020267 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/contacts/0000755000015301777760000000000012321057642022105 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/contacts/contacts-service.cpp0000644000015301777760000006454512321057334026101 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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-service.h" #include "qcontact-engineid.h" #include "request-data.h" #include "common/vcard-parser.h" #include "common/filter.h" #include "common/fetch-hint.h" #include "common/sort-clause.h" #include "common/dbus-service-defs.h" #include "common/source.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define FETCH_PAGE_SIZE 100 using namespace QtVersit; using namespace QtContacts; namespace //private { static QContact parseSource(const galera::Source &source, const QString &managerUri) { QContact contact; // contact group type contact.setType(QContactType::TypeGroup); // id galera::GaleraEngineId *engineId = new galera::GaleraEngineId(source.id(), managerUri); QContactId newId = QContactId(engineId); contact.setId(newId); // guid QContactGuid guid; guid.setGuid(source.id()); contact.saveDetail(&guid); // display name QContactDisplayLabel displayLabel; displayLabel.setLabel(source.displayLabel()); contact.saveDetail(&displayLabel); // read-only QContactExtendedDetail readOnly; readOnly.setName("READ-ONLY"); readOnly.setData(source.isReadOnly()); contact.saveDetail(&readOnly); // Primary QContactExtendedDetail primary; primary.setName("IS-PRIMARY"); primary.setData(source.isPrimary()); contact.saveDetail(&primary); return contact; } } namespace galera { GaleraContactsService::GaleraContactsService(const QString &managerUri) : m_selfContactId(), m_managerUri(managerUri), m_serviceIsReady(false), m_iface(0) { RequestData::registerMetaType(); Source::registerMetaType(); m_serviceWatcher = new QDBusServiceWatcher(CPIM_SERVICE_NAME, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange, this); connect(m_serviceWatcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)), this, SLOT(serviceOwnerChanged(QString,QString,QString))); initialize(); } GaleraContactsService::GaleraContactsService(const GaleraContactsService &other) : m_selfContactId(other.m_selfContactId), m_managerUri(other.m_managerUri), m_iface(other.m_iface) { } GaleraContactsService::~GaleraContactsService() { while(!m_pendingRequests.isEmpty()) { QPointer request = m_pendingRequests.takeFirst(); if (request) { request->cancel(); request->waitForFinished(); } } m_runningRequests.clear(); delete m_serviceWatcher; } void GaleraContactsService::serviceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) { Q_UNUSED(oldOwner); if (name == CPIM_SERVICE_NAME) { if (!newOwner.isEmpty()) { // service appear initialize(); } else if (!m_iface.isNull()) { // lost service deinitialize(); } } } void GaleraContactsService::onServiceReady() { m_serviceIsReady = true; while(!m_pendingRequests.isEmpty()) { QPointer request = m_pendingRequests.takeFirst(); if (request) { addRequest(request); } } } void GaleraContactsService::initialize() { if (m_iface.isNull()) { m_iface = QSharedPointer(new QDBusInterface(CPIM_SERVICE_NAME, CPIM_ADDRESSBOOK_OBJECT_PATH, CPIM_ADDRESSBOOK_IFACE_NAME)); if (!m_iface->lastError().isValid()) { m_serviceIsReady = m_iface.data()->property("isReady").toBool(); connect(m_iface.data(), SIGNAL(ready()), this, SLOT(onServiceReady())); connect(m_iface.data(), SIGNAL(contactsAdded(QStringList)), this, SLOT(onContactsAdded(QStringList))); connect(m_iface.data(), SIGNAL(contactsRemoved(QStringList)), this, SLOT(onContactsRemoved(QStringList))); connect(m_iface.data(), SIGNAL(contactsUpdated(QStringList)), this, SLOT(onContactsUpdated(QStringList))); Q_EMIT serviceChanged(); } else { qWarning() << "Fail to connect with service:" << m_iface->lastError(); m_iface.clear(); } } } void GaleraContactsService::deinitialize() { Q_FOREACH(RequestData* rData, m_runningRequests) { rData->cancel(); rData->request()->waitForFinished(); rData->setError(QContactManager::UnspecifiedError); } if (!m_iface.isNull()) { m_id.clear(); Q_EMIT serviceChanged(); } // this will make the service re-initialize m_iface->call("ping"); if (m_iface->lastError().isValid()) { qWarning() << m_iface->lastError(); m_iface.clear(); m_serviceIsReady = false; } else { m_serviceIsReady = m_iface.data()->property("isReady").toBool(); } } bool GaleraContactsService::isOnline() const { return !m_iface.isNull(); } void GaleraContactsService::fetchContactsById(QtContacts::QContactFetchByIdRequest *request) { if (!isOnline()) { qWarning() << "Server is not online"; RequestData::setError(request); return; } QContactIdFilter filter; filter.setIds(request->contactIds()); QString filterStr = Filter(filter).toString(); QDBusMessage result = m_iface->call("query", filterStr, "", QStringList()); if (result.type() == QDBusMessage::ErrorMessage) { qWarning() << result.errorName() << result.errorMessage(); RequestData::setError(request); return; } QDBusObjectPath viewObjectPath = result.arguments()[0].value(); QDBusInterface *view = new QDBusInterface(CPIM_SERVICE_NAME, viewObjectPath.path(), CPIM_ADDRESSBOOK_VIEW_IFACE_NAME); RequestData *requestData = new RequestData(request, view, FetchHint()); m_runningRequests << requestData; QMetaObject::invokeMethod(this, "fetchContactsPage", Qt::QueuedConnection, Q_ARG(galera::RequestData*, requestData)); } void GaleraContactsService::fetchContacts(QtContacts::QContactFetchRequest *request) { if (!isOnline()) { qWarning() << "Server is not online"; RequestData::setError(request); return; } // Only return the sources names if the filter is set as contact group type if (request->filter().type() == QContactFilter::ContactDetailFilter) { QContactDetailFilter dFilter = static_cast(request->filter()); if ((dFilter.detailType() == QContactDetail::TypeType) && (dFilter.detailField() == QContactType::FieldType) && (dFilter.value() == QContactType::TypeGroup)) { QDBusPendingCall pcall = m_iface->asyncCall("availableSources"); if (pcall.isError()) { qWarning() << pcall.error().name() << pcall.error().message(); RequestData::setError(request); return; } RequestData *requestData = new RequestData(request); m_runningRequests << requestData; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, 0); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *call) { this->fetchContactsGroupsContinue(requestData, call); }); return; } } QString sortStr = SortClause(request->sorting()).toString(); QString filterStr = Filter(request->filter()).toString(); FetchHint fetchHint = FetchHint(request->fetchHint()).toString(); QDBusPendingCall pcall = m_iface->asyncCall("query", filterStr, sortStr, QStringList()); if (pcall.isError()) { qWarning() << pcall.error().name() << pcall.error().message(); RequestData::setError(request); return; } RequestData *requestData = new RequestData(request, 0, fetchHint); m_runningRequests << requestData; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, 0); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *call) { this->fetchContactsContinue(requestData, call); }); } void GaleraContactsService::fetchContactsContinue(RequestData *request, QDBusPendingCallWatcher *call) { if (!request->isLive()) { destroyRequest(request); return; } QDBusPendingReply reply = *call; if (reply.isError()) { qWarning() << reply.error().name() << reply.error().message(); destroyRequest(request); } else { QDBusObjectPath viewObjectPath = reply.value(); QDBusInterface *view = new QDBusInterface(CPIM_SERVICE_NAME, viewObjectPath.path(), CPIM_ADDRESSBOOK_VIEW_IFACE_NAME); request->updateView(view); QMetaObject::invokeMethod(this, "fetchContactsPage", Qt::QueuedConnection, Q_ARG(galera::RequestData*, request)); } } void GaleraContactsService::fetchContactsPage(RequestData *request) { if (!isOnline() || !request->isLive()) { qWarning() << "Server is not online"; destroyRequest(request); return; } // Load contacs async QDBusPendingCall pcall = request->view()->asyncCall("contactsDetails", request->fields(), request->offset(), FETCH_PAGE_SIZE); if (pcall.isError()) { qWarning() << pcall.error().name() << pcall.error().message(); request->setError(QContactManager::UnspecifiedError); destroyRequest(request); return; } QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, 0); request->updateWatcher(watcher); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *call) { this->fetchContactsDone(request, call); }); } void GaleraContactsService::fetchContactsDone(RequestData *request, QDBusPendingCallWatcher *call) { if (!request->isLive()) { destroyRequest(request); return; } QContactManager::Error opError = QContactManager::NoError; QContactAbstractRequest::State opState = QContactAbstractRequest::FinishedState; QDBusPendingReply reply = *call; if (reply.isError()) { qWarning() << reply.error().name() << reply.error().message(); request->update(QList(), QContactAbstractRequest::FinishedState, QContactManager::UnspecifiedError); destroyRequest(request); } else { const QStringList vcards = reply.value(); if (vcards.size()) { VCardParser *parser = new VCardParser(this); parser->setProperty("DATA", QVariant::fromValue(request)); connect(parser, &VCardParser::contactsParsed, this, &GaleraContactsService::onVCardsParsed); parser->vcardToContact(vcards); } else { request->update(QList(), QContactAbstractRequest::FinishedState); destroyRequest(request); } } } void GaleraContactsService::onVCardsParsed(QList contacts) { QObject *sender = QObject::sender(); RequestData *request = static_cast(sender->property("DATA").value()); if (!request->isLive()) { destroyRequest(request); return; } QList::iterator contact; for (contact = contacts.begin(); contact != contacts.end(); ++contact) { if (!contact->isEmpty()) { QContactGuid detailId = contact->detail(); GaleraEngineId *engineId = new GaleraEngineId(detailId.guid(), m_managerUri); QContactId newId = QContactId(engineId); contact->setId(newId); // set tag to be used when creating sections QContactName detailName = contact->detail(); if (!detailName.firstName().isEmpty() && QString(detailName.firstName().at(0)).contains(QRegExp("([a-z]|[A-Z])"))) { contact->addTag(detailName.firstName().at(0).toUpper()); } else if (!detailName.lastName().isEmpty() && QString(detailName.lastName().at(0)).contains(QRegExp("([a-z]|[A-Z])"))) { contact->addTag(detailName.lastName().at(0).toUpper()); } else { contact->addTag("#"); } } } if (contacts.size() == FETCH_PAGE_SIZE) { request->update(contacts, QContactAbstractRequest::ActiveState); request->updateOffset(FETCH_PAGE_SIZE); request->updateWatcher(0); QMetaObject::invokeMethod(this, "fetchContactsPage", Qt::QueuedConnection, Q_ARG(galera::RequestData*, request)); } else { request->update(contacts, QContactAbstractRequest::FinishedState); destroyRequest(request); } sender->deleteLater(); } void GaleraContactsService::fetchContactsGroupsContinue(RequestData *request, QDBusPendingCallWatcher *call) { if (!request->isLive()) { destroyRequest(request); return; } QList contacts; QContactManager::Error opError = QContactManager::NoError; QDBusPendingReply reply = *call; if (reply.isError()) { qWarning() << reply.error().name() << reply.error().message(); opError = QContactManager::UnspecifiedError; } else { Q_FOREACH(const Source &source, reply.value()) { QContact c = parseSource(source, m_managerUri); if (source.isPrimary()) { contacts.prepend(c); } else { contacts << c; } } } request->update(contacts, QContactAbstractRequest::FinishedState, opError); destroyRequest(request); } void GaleraContactsService::saveContact(QtContacts::QContactSaveRequest *request) { QList contacts = request->contacts(); QStringList oldContacts; QStringList newContacts; QStringList sources; QStringList newSources; Q_FOREACH(const QContact &contact, contacts) { if (contact.id().isNull()) { if (contact.type() == QContactType::TypeGroup) { newSources << contact.detail().label(); } else { newContacts << VCardParser::contactToVcard(contact); // sources where the new contacts will be saved QContactSyncTarget syncTarget = contact.detail(); sources << syncTarget.syncTarget(); } } else { oldContacts << VCardParser::contactToVcard(contact); } } if (!oldContacts.isEmpty()) { updateContacts(request, oldContacts); } if (!newContacts.isEmpty()) { createContacts(request, newContacts, sources); } if (!newSources.isEmpty()) { createSources(request, newSources); } } void GaleraContactsService::createContacts(QtContacts::QContactSaveRequest *request, QStringList contacts, QStringList sources) { if (!isOnline()) { qWarning() << "Server is not online"; RequestData::setError(request); return; } if (contacts.count() > 1) { qWarning() << "TODO: implement contact creation support to more then one contact."; return; } int i = 0; Q_FOREACH(QString contact, contacts) { QDBusPendingCall pcall = m_iface->asyncCall("createContact", contact, sources[i++]); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, 0); RequestData *requestData = new RequestData(request, watcher); m_runningRequests << requestData; QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *call) { this->createContactsDone(requestData, call); }); } } void GaleraContactsService::createContactsDone(RequestData *request, QDBusPendingCallWatcher *call) { if (!request->isLive()) { destroyRequest(request); return; } QDBusPendingReply reply = *call; QList contacts; QContactManager::Error opError = QContactManager::NoError; if (reply.isError()) { qWarning() << reply.error().name() << reply.error().message(); opError = QContactManager::UnspecifiedError; } else { const QString vcard = reply.value(); if (!vcard.isEmpty()) { contacts = static_cast(request->request())->contacts(); QContact contact = VCardParser::vcardToContact(vcard); QContactGuid detailId = contact.detail(); GaleraEngineId *engineId = new GaleraEngineId(detailId.guid(), m_managerUri); QContactId newId = QContactId(engineId); contact.setId(newId); contacts.insert(0, contact); } else { opError = QContactManager::UnspecifiedError; } } request->update(contacts, QContactAbstractRequest::FinishedState, opError); destroyRequest(request); } void GaleraContactsService::createSources(QtContacts::QContactSaveRequest *request, QStringList &sources) { if (!isOnline()) { qWarning() << "Server is not online"; RequestData::setError(request); return; } QList contacts; QMap errorMap; int index = 0; Q_FOREACH(QString sourceName, sources) { QDBusReply result = m_iface->call("createSource", sourceName); if (result.isValid()) { contacts << parseSource(result.value(), m_managerUri); } else { errorMap.insert(index, QContactManager::UnspecifiedError); } index++; } QContactManagerEngine::updateContactSaveRequest(request, contacts, QContactManager::NoError, errorMap, QContactAbstractRequest::FinishedState); } void GaleraContactsService::removeContact(QContactRemoveRequest *request) { if (!isOnline()) { qWarning() << "Server is not online"; RequestData::setError(request); return; } QStringList ids; Q_FOREACH(QContactId contactId, request->contactIds()) { // TODO: find a better way to get the contactId ids << contactId.toString().split(":").last(); } QDBusPendingCall pcall = m_iface->asyncCall("removeContacts", ids); if (pcall.isError()) { qWarning() << "Error" << pcall.error().name() << pcall.error().message(); RequestData::setError(request); } else { QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, 0); RequestData *requestData = new RequestData(request, watcher); m_runningRequests << requestData; QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *call) { this->removeContactDone(requestData, call); }); } } void GaleraContactsService::removeContactDone(RequestData *request, QDBusPendingCallWatcher *call) { if (!request->isLive()) { destroyRequest(request); return; } QDBusPendingReply reply = *call; QContactManager::Error opError = QContactManager::NoError; QMap errorMap; if (reply.isError()) { qWarning() << reply.error().name() << reply.error().message(); opError = QContactManager::UnspecifiedError; } request->update(QContactAbstractRequest::FinishedState, opError); destroyRequest(request); } void GaleraContactsService::updateContacts(QtContacts::QContactSaveRequest *request, QStringList contacts) { if (!isOnline()) { qWarning() << "Server is not online"; RequestData::setError(request); return; } QDBusPendingCall pcall = m_iface->asyncCall("updateContacts", contacts); if (pcall.isError()) { qWarning() << "Error" << pcall.error().name() << pcall.error().message(); RequestData::setError(request); } else { QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, 0); RequestData *requestData = new RequestData(request, watcher); m_runningRequests << requestData; QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *call) { this->updateContactDone(requestData, call); }); } } void GaleraContactsService::updateContactDone(RequestData *request, QDBusPendingCallWatcher *call) { if (!request->isLive()) { destroyRequest(request); return; } QDBusPendingReply reply = *call; QList contacts; QMap saveError; QContactManager::Error opError = QContactManager::NoError; if (reply.isError()) { qWarning() << reply.error().name() << reply.error().message(); opError = QContactManager::UnspecifiedError; } else { const QStringList vcards = reply.value(); if (!vcards.isEmpty()) { QMap importErrors; //TODO report parse errors contacts = VCardParser::vcardToContactSync(vcards); Q_FOREACH(int key, importErrors.keys()) { saveError.insert(key, QContactManager::BadArgumentError); } } } request->update(contacts, QContactAbstractRequest::FinishedState, opError, saveError); destroyRequest(request); } void GaleraContactsService::cancelRequest(QtContacts::QContactAbstractRequest *request) { Q_FOREACH(RequestData* rData, m_runningRequests) { if (rData->request() == request) { rData->cancel(); return; } } } void GaleraContactsService::waitRequest(QtContacts::QContactAbstractRequest *request) { Q_FOREACH(RequestData* rData, m_runningRequests) { if (rData->request() == request) { rData->wait(); return; } } } void GaleraContactsService::addRequest(QtContacts::QContactAbstractRequest *request) { if (!isOnline()) { qWarning() << "Server is not online"; QContactManagerEngine::updateRequestState(request, QContactAbstractRequest::FinishedState); return; } if (!m_serviceIsReady) { m_pendingRequests << QPointer(request); return; } Q_ASSERT(request->state() == QContactAbstractRequest::ActiveState); switch (request->type()) { case QContactAbstractRequest::ContactFetchRequest: fetchContacts(static_cast(request)); break; case QContactAbstractRequest::ContactFetchByIdRequest: fetchContactsById(static_cast(request)); break; case QContactAbstractRequest::ContactIdFetchRequest: qWarning() << "Not implemented: ContactIdFetchRequest"; break; case QContactAbstractRequest::ContactSaveRequest: saveContact(static_cast(request)); break; case QContactAbstractRequest::ContactRemoveRequest: removeContact(static_cast(request)); break; case QContactAbstractRequest::RelationshipFetchRequest: qWarning() << "Not implemented: RelationshipFetchRequest"; break; case QContactAbstractRequest::RelationshipRemoveRequest: qWarning() << "Not implemented: RelationshipRemoveRequest"; break; case QContactAbstractRequest::RelationshipSaveRequest: qWarning() << "Not implemented: RelationshipSaveRequest"; break; break; default: // unknown request type. break; } } void GaleraContactsService::destroyRequest(RequestData *request) { m_runningRequests.remove(request); delete request; } QList GaleraContactsService::parseIds(const QStringList &ids) const { QList contactIds; Q_FOREACH(QString id, ids) { GaleraEngineId *engineId = new GaleraEngineId(id, m_managerUri); contactIds << QContactId(engineId); } return contactIds; } void GaleraContactsService::onContactsAdded(const QStringList &ids) { Q_EMIT contactsAdded(parseIds(ids)); } void GaleraContactsService::onContactsRemoved(const QStringList &ids) { Q_EMIT contactsRemoved(parseIds(ids)); } void GaleraContactsService::onContactsUpdated(const QStringList &ids) { Q_EMIT contactsUpdated(parseIds(ids)); } } //namespace address-book-service-0.1.1+14.04.20140408.3/contacts/qcontact-backend.h0000644000015301777760000001335112321057324025457 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALER_QCONTACT_BACKEND_H__ #define __GALER_QCONTACT_BACKEND_H__ #include #include #include #include #include #include namespace galera { class GaleraContactsService; class GaleraEngineFactory : public QtContacts::QContactManagerEngineFactory { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QContactManagerEngineFactoryInterface" FILE "galera.json") public: QtContacts::QContactManagerEngine* engine(const QMap ¶meters, QtContacts::QContactManager::Error*); QString managerName() const; QtContacts::QContactEngineId* createContactEngineId(const QMap ¶meters, const QString &engineIdString) const; }; class GaleraManagerEngine : public QtContacts::QContactManagerEngine { Q_OBJECT public: static GaleraManagerEngine *createEngine(const QMap ¶meters); ~GaleraManagerEngine(); /* URI reporting */ QString managerName() const; QMap managerParameters() const; /*! \reimp */ int managerVersion() const; /* Filtering */ virtual QList contactIds(const QtContacts::QContactFilter &filter, const QList &sortOrders, QtContacts::QContactManager::Error *error) const; virtual QList contacts(const QtContacts::QContactFilter &filter, const QList& sortOrders, const QtContacts::QContactFetchHint &fetchHint, QtContacts::QContactManager::Error *error) const; virtual QList contacts(const QList &contactIds, const QtContacts::QContactFetchHint& fetchHint, QMap *errorMap, QtContacts::QContactManager::Error *error) const; virtual QtContacts::QContact contact(const QtContacts::QContactId &contactId, const QtContacts::QContactFetchHint &fetchHint, QtContacts::QContactManager::Error *error) const; virtual bool saveContact(QtContacts::QContact *contact, QtContacts::QContactManager::Error *error); virtual bool removeContact(const QtContacts::QContactId &contactId, QtContacts::QContactManager::Error *error); virtual bool saveRelationship(QtContacts::QContactRelationship *relationship, QtContacts::QContactManager::Error *error); virtual bool removeRelationship(const QtContacts::QContactRelationship &relationship, QtContacts::QContactManager::Error *error); virtual bool saveContacts(QList *contacts, QMap *errorMap, QtContacts::QContactManager::Error *error); virtual bool saveContacts(QList *contacts, const QList &typeMask, QMap *errorMap, QtContacts::QContactManager::Error *error); virtual bool removeContacts(const QList &contactIds, QMap *errorMap, QtContacts::QContactManager::Error *error); /* "Self" contact id (MyCard) */ virtual bool setSelfContactId(const QtContacts::QContactId &contactId, QtContacts::QContactManager::Error *error); virtual QtContacts::QContactId selfContactId(QtContacts::QContactManager::Error *error) const; /* Relationships between contacts */ virtual QList relationships(const QString &relationshipType, const QtContacts::QContact& participant, QtContacts::QContactRelationship::Role role, QtContacts::QContactManager::Error *error) const; virtual bool saveRelationships(QList *relationships, QMap* errorMap, QtContacts::QContactManager::Error *error); virtual bool removeRelationships(const QList &relationships, QMap *errorMap, QtContacts::QContactManager::Error *error); /* Validation for saving */ virtual bool validateContact(const QtContacts::QContact &contact, QtContacts::QContactManager::Error *error) const; /* Asynchronous Request Support */ virtual void requestDestroyed(QtContacts::QContactAbstractRequest *req); virtual bool startRequest(QtContacts::QContactAbstractRequest *req); virtual bool cancelRequest(QtContacts::QContactAbstractRequest *req); virtual bool waitForRequestFinished(QtContacts::QContactAbstractRequest *req, int msecs); /* Capabilities reporting */ virtual bool isRelationshipTypeSupported(const QString &relationshipType, QtContacts::QContactType::TypeValues contactType) const; virtual bool isFilterSupported(const QtContacts::QContactFilter &filter) const; virtual QList supportedDataTypes() const; private: GaleraManagerEngine(); QList contactIds(const QList &contacts) const; GaleraContactsService *m_service; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/contacts/contacts-service.h0000644000015301777760000001043012321057324025525 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __CONTACTS_SERVICE_H__ #define __CONTACTS_SERVICE_H__ #include #include #include #include #include #include #include #include #include #include #include #include class QDBusInterface; using namespace QtContacts; // necessary for signal signatures namespace galera { class RequestData; class GaleraContactsService : public QObject { Q_OBJECT public: GaleraContactsService(const QString &managerUri); GaleraContactsService(const GaleraContactsService &other); ~GaleraContactsService(); QList engines() const; void appendEngine(QtContacts::QContactManagerEngine *engine); void removeEngine(QtContacts::QContactManagerEngine *engine); QList relationships() const; void addRequest(QtContacts::QContactAbstractRequest *request); void cancelRequest(QtContacts::QContactAbstractRequest *request); void waitRequest(QtContacts::QContactAbstractRequest *request); Q_SIGNALS: void contactsAdded(QList ids); void contactsRemoved(QList ids); void contactsUpdated(QList ids); void serviceChanged(); private Q_SLOTS: void onContactsAdded(const QStringList &ids); void onContactsRemoved(const QStringList &ids); void onContactsUpdated(const QStringList &ids); void serviceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner); void onServiceReady(); void onVCardsParsed(QList contacts); void fetchContactsDone(RequestData *request, QDBusPendingCallWatcher *call); private: QString m_id; QtContacts::QContactId m_selfContactId; // the "MyCard" contact id QString m_managerUri; // for faster lookup. QDBusServiceWatcher *m_serviceWatcher; bool m_serviceIsReady; QSharedPointer m_iface; QSet m_runningRequests; QQueue > m_pendingRequests; Q_INVOKABLE void initialize(); Q_INVOKABLE void deinitialize(); bool isOnline() const; void fetchContacts(QtContacts::QContactFetchRequest *request); void fetchContactsContinue(RequestData *request, QDBusPendingCallWatcher *call); void fetchContactsGroupsContinue(RequestData *request, QDBusPendingCallWatcher *call); void fetchContactsById(QtContacts::QContactFetchByIdRequest *request); Q_INVOKABLE void fetchContactsPage(galera::RequestData *request); void saveContact(QtContacts::QContactSaveRequest *request); void createContacts(QtContacts::QContactSaveRequest *request, QStringList contacts, QStringList sources); void createSources(QtContacts::QContactSaveRequest *request, QStringList &sources); void updateContacts(QtContacts::QContactSaveRequest *request, QStringList contacts); void updateContactDone(RequestData *request, QDBusPendingCallWatcher *call); void createContactsDone(RequestData *request, QDBusPendingCallWatcher *call); void removeContact(QtContacts::QContactRemoveRequest *request); void removeContactDone(RequestData *request, QDBusPendingCallWatcher *call); void destroyRequest(RequestData *request); QList parseIds(const QStringList &ids) const; }; } #endif address-book-service-0.1.1+14.04.20140408.3/contacts/qcontact-engineid.cpp0000644000015301777760000000560212321057324026205 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "qcontact-engineid.h" #include using namespace QtContacts; namespace galera { GaleraEngineId::GaleraEngineId() : m_contactId("") { } GaleraEngineId::GaleraEngineId(const QString &contactId, const QString &managerUri) : m_contactId(contactId), m_managerUri(managerUri) { } GaleraEngineId::~GaleraEngineId() { } GaleraEngineId::GaleraEngineId(const GaleraEngineId &other) : m_contactId(other.m_contactId), m_managerUri(other.m_managerUri) { } GaleraEngineId::GaleraEngineId(const QMap ¶meters, const QString &engineIdString) { m_contactId = engineIdString; m_managerUri = QContactManager::buildUri("galera", parameters); } bool GaleraEngineId::isEqualTo(const QtContacts::QContactEngineId *other) const { if (m_contactId != static_cast(other)->m_contactId) return false; return true; } bool GaleraEngineId::isLessThan(const QtContacts::QContactEngineId *other) const { const GaleraEngineId *otherPtr = static_cast(other); if (m_managerUri < otherPtr->m_managerUri) return true; if (m_contactId < otherPtr->m_contactId) return true; return false; } QString GaleraEngineId::managerUri() const { return m_managerUri; } QString GaleraEngineId::toString() const { return m_contactId; } QtContacts::QContactEngineId* GaleraEngineId::clone() const { return new GaleraEngineId(m_contactId, m_managerUri); } #ifndef QT_NO_DEBUG_STREAM QDebug& GaleraEngineId::debugStreamOut(QDebug &dbg) const { dbg.nospace() << "EngineId(" << m_managerUri << "," << m_contactId << ")"; return dbg.maybeSpace(); } #endif uint GaleraEngineId::hash() const { return qHash(m_contactId); } #ifndef QT_NO_DATASTREAM QDataStream& operator<<(QDataStream& out, const GaleraEngineId& engineId) { out << engineId.m_managerUri << engineId.m_contactId; return out; } QDataStream& operator>>(QDataStream& in, GaleraEngineId& engineId) { QString managerUri; QString contactId; in >> managerUri; in >> contactId; engineId.m_contactId = contactId; engineId.m_managerUri = managerUri; //= GaleraEngineId(contactId, managerUri); return in; } #endif } address-book-service-0.1.1+14.04.20140408.3/contacts/request-data.cpp0000644000015301777760000001510512321057324025207 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "request-data.h" #include #include using namespace QtContacts; namespace galera { RequestData::RequestData(QContactAbstractRequest *request, QDBusInterface *view, const FetchHint &hint, QDBusPendingCallWatcher *watcher) : m_offset(0), m_hint(hint), m_canceled(false), m_eventLoop(0) { init(request, view, watcher); } RequestData::RequestData(QtContacts::QContactAbstractRequest *request, QDBusPendingCallWatcher *watcher) : m_offset(0), m_canceled(false), m_eventLoop(0) { init(request, 0, watcher); } RequestData::~RequestData() { if (!m_request.isNull() && m_canceled) { update(QContactAbstractRequest::CanceledState); } m_request.clear(); } void RequestData::init(QtContacts::QContactAbstractRequest *request, QDBusInterface *view, QDBusPendingCallWatcher *watcher) { m_request = request; if (view) { updateView(view); } if (watcher) { m_watcher = QSharedPointer(watcher, RequestData::deleteWatcher); } } QContactAbstractRequest* RequestData::request() const { return m_request.data(); } int RequestData::offset() const { return m_offset; } bool RequestData::isLive() const { return !m_request.isNull() && (m_request->state() == QContactAbstractRequest::ActiveState); } void RequestData::cancel() { m_watcher.clear(); m_canceled = true; } bool RequestData::canceled() const { return m_canceled; } void RequestData::wait() { if (m_eventLoop) { qWarning() << "Recursive wait call"; Q_ASSERT(false); } if (isLive()) { QEventLoop eventLoop; m_eventLoop = &eventLoop; eventLoop.exec(); m_eventLoop = 0; } } QDBusInterface* RequestData::view() const { return m_view.data(); } void RequestData::updateView(QDBusInterface* view) { m_view = QSharedPointer(view, RequestData::deleteView); } QStringList RequestData::fields() const { return m_hint.fields(); } void RequestData::updateWatcher(QDBusPendingCallWatcher *watcher) { m_watcher.clear(); if (watcher) { m_watcher = QSharedPointer(watcher, RequestData::deleteWatcher); } } void RequestData::updateOffset(int offset) { m_offset += offset; } void RequestData::setError(QContactManager::Error error) { m_result.clear(); m_fullResult.clear(); update(QContactAbstractRequest::FinishedState, error); if (m_eventLoop) { m_eventLoop->quit(); } } void RequestData::update(QList result, QContactAbstractRequest::State state, QContactManager::Error error, QMap errorMap) { m_fullResult += result; m_result = result; update(state, error, errorMap); } void RequestData::update(QContactAbstractRequest::State state, QContactManager::Error error, QMap errorMap) { if (!isLive()) { return; } QList result; // only send the full contact list at the finish state if (false) { //state == QContactAbstractRequest::FinishedState) { result = m_fullResult; } else { result = m_result; } switch (m_request->type()) { case QContactAbstractRequest::ContactFetchRequest: QContactManagerEngine::updateContactFetchRequest(static_cast(m_request.data()), m_fullResult, error, state); break; case QContactAbstractRequest::ContactFetchByIdRequest: QContactManagerEngine::updateContactFetchByIdRequest(static_cast(m_request.data()), m_fullResult, error, errorMap, state); break; case QContactAbstractRequest::ContactSaveRequest: QContactManagerEngine::updateContactSaveRequest(static_cast(m_request.data()), m_result, error, QMap(), state); case QContactAbstractRequest::ContactRemoveRequest: QContactManagerEngine::updateContactRemoveRequest(static_cast(m_request.data()), error, errorMap, state); break; default: break; } if (m_eventLoop && (state != QContactAbstractRequest::ActiveState)) { m_eventLoop->quit(); } } void RequestData::registerMetaType() { qRegisterMetaType(); } void RequestData::setError(QContactAbstractRequest *request, QContactManager::Error error) { RequestData r(request); r.setError(error); } void RequestData::deleteView(QDBusInterface *view) { if (view) { view->call("close"); view->deleteLater(); } } void RequestData::deleteWatcher(QDBusPendingCallWatcher *watcher) { if (watcher) { watcher->deleteLater(); } } } //namespace address-book-service-0.1.1+14.04.20140408.3/contacts/qcontact-backend.cpp0000644000015301777760000002600612321057324026013 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "qcontact-backend.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "contacts-service.h" #include "qcontact-engineid.h" using namespace QtContacts; namespace galera { QtContacts::QContactManagerEngine* GaleraEngineFactory::engine(const QMap ¶meters, QtContacts::QContactManager::Error *error) { Q_UNUSED(error); GaleraManagerEngine *engine = GaleraManagerEngine::createEngine(parameters); return engine; } QtContacts::QContactEngineId* GaleraEngineFactory::createContactEngineId(const QMap ¶meters, const QString &engineIdString) const { return new GaleraEngineId(parameters, engineIdString); } QString GaleraEngineFactory::managerName() const { return QString::fromLatin1("galera"); } GaleraManagerEngine* GaleraManagerEngine::createEngine(const QMap ¶meters) { GaleraManagerEngine *engine = new GaleraManagerEngine(); return engine; } /*! * Constructs a new in-memory backend which shares the given \a data with * other shared memory engines. */ GaleraManagerEngine::GaleraManagerEngine() : m_service(new GaleraContactsService(managerUri())) { connect(m_service, SIGNAL(contactsAdded(QList)), this, SIGNAL(contactsAdded(QList))); connect(m_service, SIGNAL(contactsRemoved(QList)), this, SIGNAL(contactsRemoved(QList))); connect(m_service, SIGNAL(contactsUpdated(QList)), this, SIGNAL(contactsChanged(QList))); connect(m_service, SIGNAL(serviceChanged()), this, SIGNAL(dataChanged())); } /*! Frees any memory used by this engine */ GaleraManagerEngine::~GaleraManagerEngine() { delete m_service; } /* URI reporting */ QString GaleraManagerEngine::managerName() const { return "galera"; } QMap GaleraManagerEngine::managerParameters() const { QMap parameters; return parameters; } int GaleraManagerEngine::managerVersion() const { return 1; } /* Filtering */ QList GaleraManagerEngine::contactIds(const QtContacts::QContactFilter &filter, const QList &sortOrders, QtContacts::QContactManager::Error *error) const { QContactFetchHint hint; hint.setDetailTypesHint(QList() << QContactDetail::TypeGuid); QList clist = contacts(filter, sortOrders, hint, error); /* Extract the ids */ QList ids; Q_FOREACH(const QContact &c, clist) ids.append(c.id()); return ids; } QList GaleraManagerEngine::contacts(const QtContacts::QContactFilter &filter, const QList& sortOrders, const QContactFetchHint &fetchHint, QtContacts::QContactManager::Error *error) const { Q_UNUSED(fetchHint); Q_UNUSED(error); QContactFetchRequest request; request.setFilter(filter); request.setSorting(sortOrders); const_cast(this)->startRequest(&request); const_cast(this)->waitForRequestFinished(&request, -1); if (error) { *error = request.error(); } return request.contacts(); } QList GaleraManagerEngine::contacts(const QList &contactIds, const QContactFetchHint &fetchHint, QMap *errorMap, QContactManager::Error *error) const { QContactFetchByIdRequest request; request.setIds(contactIds); request.setFetchHint(fetchHint); const_cast(this)->startRequest(&request); const_cast(this)->waitForRequestFinished(&request, -1); if (errorMap) { *errorMap = request.errorMap(); } if (error) { *error = request.error(); } return request.contacts(); } QContact GaleraManagerEngine::contact(const QContactId &contactId, const QContactFetchHint &fetchHint, QContactManager::Error *error) const { QContactFetchByIdRequest request; request.setIds(QList() << contactId); request.setFetchHint(fetchHint); const_cast(this)->startRequest(&request); const_cast(this)->waitForRequestFinished(&request, -1); if (error) { *error = request.error(); } return request.contacts().value(0, QContact()); } bool GaleraManagerEngine::saveContact(QtContacts::QContact *contact, QtContacts::QContactManager::Error *error) { QContactSaveRequest request; request.setContact(*contact); startRequest(&request); waitForRequestFinished(&request, -1); *error = QContactManager::NoError; // FIXME: GaleraContactsService::updateContactDone doesn't return contacts if (contact->id().isNull()) { *contact = request.contacts()[0]; } return true; } bool GaleraManagerEngine::removeContact(const QtContacts::QContactId &contactId, QtContacts::QContactManager::Error *error) { *error = QContactManager::NoError; contact(contactId, QContactFetchHint(), error); if (*error == QContactManager::DoesNotExistError) { return false; } QContactRemoveRequest request; request.setContactId(contactId); startRequest(&request); waitForRequestFinished(&request, -1); *error = QContactManager::NoError; return true; } bool GaleraManagerEngine::saveRelationship(QtContacts::QContactRelationship *relationship, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } bool GaleraManagerEngine::removeRelationship(const QtContacts::QContactRelationship &relationship, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } bool GaleraManagerEngine::saveContacts(QList *contacts, QMap *errorMap, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } bool GaleraManagerEngine::saveContacts(QList *contacts, const QList &typeMask, QMap *errorMap, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } bool GaleraManagerEngine::removeContacts(const QList &contactIds, QMap *errorMap, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } /* "Self" contact id (MyCard) */ bool GaleraManagerEngine::setSelfContactId(const QtContacts::QContactId &contactId, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } QtContacts::QContactId GaleraManagerEngine::selfContactId(QtContacts::QContactManager::Error *error) const { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return QContactId(); } /* Relationships between contacts */ QList GaleraManagerEngine::relationships(const QString &relationshipType, const QContact& participant, QContactRelationship::Role role, QtContacts::QContactManager::Error *error) const { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return QList(); } bool GaleraManagerEngine::saveRelationships(QList *relationships, QMap* errorMap, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } bool GaleraManagerEngine::removeRelationships(const QList &relationships, QMap *errorMap, QtContacts::QContactManager::Error *error) { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } /* Validation for saving */ bool GaleraManagerEngine::validateContact(const QtContacts::QContact &contact, QtContacts::QContactManager::Error *error) const { qDebug() << Q_FUNC_INFO; *error = QContactManager::NoError; return true; } /* Asynchronous Request Support */ void GaleraManagerEngine::requestDestroyed(QtContacts::QContactAbstractRequest *req) { } bool GaleraManagerEngine::startRequest(QtContacts::QContactAbstractRequest *req) { if (!req) { return false; } QPointer checkDeletion(req); updateRequestState(req, QContactAbstractRequest::ActiveState); if (!checkDeletion.isNull()) { m_service->addRequest(req); } return true; } bool GaleraManagerEngine::cancelRequest(QtContacts::QContactAbstractRequest *req) { if (req) { m_service->cancelRequest(req); return true; } else { return false; } } bool GaleraManagerEngine::waitForRequestFinished(QtContacts::QContactAbstractRequest *req, int msecs) { Q_UNUSED(msecs); m_service->waitRequest(req); return true; } /* Capabilities reporting */ bool GaleraManagerEngine::isRelationshipTypeSupported(const QString &relationshipType, QtContacts::QContactType::TypeValues contactType) const { qDebug() << Q_FUNC_INFO; return true; } bool GaleraManagerEngine::isFilterSupported(const QtContacts::QContactFilter &filter) const { qDebug() << Q_FUNC_INFO; return true; } QList GaleraManagerEngine::supportedDataTypes() const { QList st; st.append(QVariant::String); st.append(QVariant::Date); st.append(QVariant::DateTime); st.append(QVariant::Time); st.append(QVariant::Bool); st.append(QVariant::Char); st.append(QVariant::Int); st.append(QVariant::UInt); st.append(QVariant::LongLong); st.append(QVariant::ULongLong); st.append(QVariant::Double); return st; } } // namespace address-book-service-0.1.1+14.04.20140408.3/contacts/request-data.h0000644000015301777760000000650612321057324024661 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_REQUEST_DATA_H__ #define __GALERA_REQUEST_DATA_H__ #include #include #include #include #include #include #include #include namespace galera { class RequestData { public: RequestData(QtContacts::QContactAbstractRequest *request, QDBusInterface *view, const FetchHint &hint, QDBusPendingCallWatcher *watcher=0); RequestData(QtContacts::QContactAbstractRequest *request, QDBusPendingCallWatcher *watcher=0); ~RequestData(); QtContacts::QContactAbstractRequest* request() const; QDBusInterface* view() const; QStringList fields() const; void updateWatcher(QDBusPendingCallWatcher *watcher); void updateView(QDBusInterface* view); void updateOffset(int offset); int offset() const; bool isLive() const; void cancel(); bool canceled() const; void wait(); void setError(QtContacts::QContactManager::Error error); void update(QList result, QtContacts::QContactAbstractRequest::State state, QtContacts::QContactManager::Error error = QtContacts::QContactManager::NoError, QMap errorMap = QMap()); void update(QtContacts::QContactAbstractRequest::State state, QtContacts::QContactManager::Error error = QtContacts::QContactManager::NoError, QMap errorMap = QMap()); static void setError(QtContacts::QContactAbstractRequest *request, QtContacts::QContactManager::Error error = QtContacts::QContactManager::UnspecifiedError); static void registerMetaType(); private: QPointer m_request; QSharedPointer m_view; QSharedPointer m_watcher; QList m_result; QList m_fullResult; int m_offset; FetchHint m_hint; bool m_canceled; QEventLoop *m_eventLoop; void init(QtContacts::QContactAbstractRequest *request, QDBusInterface *view, QDBusPendingCallWatcher *watcher); static void deleteRequest(QtContacts::QContactAbstractRequest *obj); static void deleteView(QDBusInterface *view); static void deleteWatcher(QDBusPendingCallWatcher *watcher); }; } Q_DECLARE_METATYPE(galera::RequestData*) #endif address-book-service-0.1.1+14.04.20140408.3/contacts/CMakeLists.txt0000644000015301777760000000153012321057324024641 0ustar pbusernogroup00000000000000project(qtcontacts_galera) set(QCONTACTS_BACKEND qtcontacts_galera) set(QCONTACTS_BACKEND_SRCS qcontact-backend.cpp qcontact-engineid.cpp contacts-service.cpp request-data.cpp ) set(QCONTACTS_BACKEND_HDRS qcontact-backend.h qcontact-engineid.h contacts-service.h request-data.h ) add_library(${QCONTACTS_BACKEND} MODULE ${QCONTACTS_BACKEND_SRCS} ${QCONTACTS_BACKEND_HDRS} ) include_directories( ${CMAKE_SOURCE_DIR} ) target_link_libraries(${QCONTACTS_BACKEND} galera-common ) qt5_use_modules(${QCONTACTS_BACKEND} Core Contacts DBus Versit) add_definitions(-std=gnu++11) execute_process( COMMAND qmake -query QT_INSTALL_PLUGINS OUTPUT_VARIABLE QT_INSTALL_PLUGINS OUTPUT_STRIP_TRAILING_WHITESPACE ) install(TARGETS ${QCONTACTS_BACKEND} LIBRARY DESTINATION ${QT_INSTALL_PLUGINS}/contacts) address-book-service-0.1.1+14.04.20140408.3/contacts/galera.json0000644000015301777760000000003512321057324024226 0ustar pbusernogroup00000000000000{ "Keys": [ "galera" ] } address-book-service-0.1.1+14.04.20140408.3/contacts/qcontact-engineid.h0000644000015301777760000000335612321057324025656 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_QCONTACT_ENGINEID_H__ #define __GALERA_QCONTACT_ENGINEID_H__ #include namespace galera { class GaleraEngineId : public QtContacts::QContactEngineId { public: GaleraEngineId(); ~GaleraEngineId(); GaleraEngineId(const QString &contactId, const QString &managerUri); GaleraEngineId(const GaleraEngineId &other); GaleraEngineId(const QMap ¶meters, const QString &engineIdString); bool isEqualTo(const QtContacts::QContactEngineId *other) const; bool isLessThan(const QtContacts::QContactEngineId *other) const; QString managerUri() const; QContactEngineId* clone() const; QString toString() const; #ifndef QT_NO_DEBUG_STREAM QDebug& debugStreamOut(QDebug &dbg) const; #endif #ifndef QT_NO_DATASTREAM friend QDataStream& operator<<(QDataStream& out, const GaleraEngineId& filter); friend QDataStream& operator>>(QDataStream& in, GaleraEngineId& filter); #endif uint hash() const; private: QString m_contactId; QString m_managerUri; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/cmake/0000755000015301777760000000000012321057642021347 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/cmake/lcov.cmake0000644000015301777760000000506012321057324023312 0ustar pbusernogroup00000000000000# - This module creates a new 'lcov' target which generates # a coverage analysis html output. # LCOV is a graphical front-end for GCC's coverage testing tool gcov. Please see # http://ltp.sourceforge.net/coverage/lcov.php # # Usage: you must add an option to your CMakeLists.txt to build your application # with coverage support. Then you need to include this file to the lcov target. # # Example: # IF(BUILD_WITH_COVERAGE) # SET(CMAKE_C_FLAGS "-g -O0 -Wall -fprofile-arcs -ftest-coverage") # SET(CMAKE_CXX_FLAGS "-g -O0 -Wall -fprofile-arcs -ftest-coverage") # SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") # include(${CMAKE_SOURCE_DIR}/cmake/lcov.cmake) # ENDIF(BUILD_WITH_COVERAGE) #============================================================================= # Copyright 2010 ascolab GmbH # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distributed this file outside of CMake, substitute the full # License text for the above reference.) set(REMOVE_PATTERN q*.h folks/*.h dummy-*.c internal_0_9_2.c *.moc moc_*.cpp locale_facets.h new move.h) ## lcov target ADD_CUSTOM_TARGET(lcov) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND mkdir -p coverage WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND lcov --directory . --zerocounters WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND make test WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND lcov --directory . --capture --output-file ./coverage/stap_all.info --checksum -f WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND lcov --directory . -r ./coverage/stap_all.info ${REMOVE_PATTERN} --output-file ./coverage/stap.info WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND genhtml -o ./coverage --title "Code Coverage" --legend --show-details --demangle-cpp ./coverage/stap.info WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) ADD_CUSTOM_COMMAND(TARGET lcov COMMAND echo "Open ${CMAKE_BINARY_DIR}/coverage/index.html to view the coverage analysis results." WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) address-book-service-0.1.1+14.04.20140408.3/cmake/vala/0000755000015301777760000000000012321057642022272 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/cmake/vala/UseVala.cmake0000644000015301777760000001557212321057324024643 0ustar pbusernogroup00000000000000## # Compile vala files to their c equivalents for further processing. # # The "vala_precompile" function takes care of calling the valac executable on # the given source to produce c files which can then be processed further using # default cmake functions. # # The first parameter provided is a variable, which will be filled with a list # of c files outputted by the vala compiler. This list can than be used in # conjuction with functions like "add_executable" or others to create the # neccessary compile rules with CMake. # # The following sections may be specified afterwards to provide certain options # to the vala compiler: # # SOURCES # A list of .vala files to be compiled. Please take care to add every vala # file belonging to the currently compiled project or library as Vala will # otherwise not be able to resolve all dependencies. # # PACKAGES # A list of vala packages/libraries to be used during the compile cycle. The # package names are exactly the same, as they would be passed to the valac # "--pkg=" option. # # OPTIONS # A list of optional options to be passed to the valac executable. This can be # used to pass "--thread" for example to enable multi-threading support. # # DEFINITIONS # A list of symbols to be used for conditional compilation. They are the same # as they would be passed using the valac "--define=" option. # # CUSTOM_VAPIS # A list of custom vapi files to be included for compilation. This can be # useful to include freshly created vala libraries without having to install # them in the system. # # GENERATE_VAPI # Pass all the needed flags to the compiler to create a vapi for # the compiled library. The provided name will be used for this and a # .vapi file will be created. # # GENERATE_HEADER # Let the compiler generate a header file for the compiled code. There will # be a header file as well as an internal header file being generated called # .h and _internal.h # # The following call is a simple example to the vala_precompile macro showing # an example to every of the optional sections: # # find_package(Vala "0.12" REQUIRED) # include(${VALA_USE_FILE}) # # vala_precompile(VALA_C # SOURCES # source1.vala # source2.vala # source3.vala # PACKAGES # gtk+-2.0 # gio-1.0 # posix # DIRECTORY # gen # OPTIONS # --thread # CUSTOM_VAPIS # some_vapi.vapi # GENERATE_VAPI # myvapi # GENERATE_HEADER # myheader # ) # # Most important is the variable VALA_C which will contain all the generated c # file names after the call. ## ## # Copyright 2009-2010 Jakob Westhoff. All rights reserved. # Copyright 2010-2011 Daniel Pfeifer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY JAKOB WESTHOFF ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL JAKOB WESTHOFF OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of Jakob Westhoff ## include(CMakeParseArguments) function(vala_precompile output) cmake_parse_arguments(ARGS "" "DIRECTORY;GENERATE_HEADER;GENERATE_VAPI" "SOURCES;PACKAGES;OPTIONS;DEFINITIONS;CUSTOM_VAPIS" ${ARGN}) if(ARGS_DIRECTORY) get_filename_component(DIRECTORY ${ARGS_DIRECTORY} ABSOLUTE) else(ARGS_DIRECTORY) set(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) endif(ARGS_DIRECTORY) include_directories(${DIRECTORY}) set(vala_pkg_opts "") foreach(pkg ${ARGS_PACKAGES}) list(APPEND vala_pkg_opts "--pkg=${pkg}") endforeach(pkg ${ARGS_PACKAGES}) set(vala_define_opts "") foreach(def ${ARGS_DEFINTIONS}) list(APPEND vala_define_opts "--define=${def}") endforeach(def ${ARGS_DEFINTIONS}) set(in_files "") set(out_files "") foreach(src ${ARGS_SOURCES} ${ARGS_UNPARSED_ARGUMENTS}) list(APPEND in_files "${CMAKE_CURRENT_SOURCE_DIR}/${src}") string(REPLACE ".vala" ".c" src ${src}) string(REPLACE ".gs" ".c" src ${src}) set(out_file "${DIRECTORY}/${src}") list(APPEND out_files "${DIRECTORY}/${src}") endforeach(src ${ARGS_SOURCES} ${ARGS_UNPARSED_ARGUMENTS}) set(custom_vapi_arguments "") if(ARGS_CUSTOM_VAPIS) foreach(vapi ${ARGS_CUSTOM_VAPIS}) list(APPEND custom_vapi_arguments ${vapi}) endforeach(vapi ${ARGS_CUSTOM_VAPIS}) endif(ARGS_CUSTOM_VAPIS) set(vapi_arguments "") if(ARGS_GENERATE_VAPI) list(APPEND out_files "${DIRECTORY}/${ARGS_GENERATE_VAPI}.vapi") set(vapi_arguments "--vapi=${ARGS_GENERATE_VAPI}.vapi") # Header and internal header is needed to generate internal vapi if (NOT ARGS_GENERATE_HEADER) set(ARGS_GENERATE_HEADER ${ARGS_GENERATE_VAPI}) endif(NOT ARGS_GENERATE_HEADER) endif(ARGS_GENERATE_VAPI) set(header_arguments "") if(ARGS_GENERATE_HEADER) list(APPEND out_files "${DIRECTORY}/${ARGS_GENERATE_HEADER}.h") list(APPEND out_files "${DIRECTORY}/${ARGS_GENERATE_HEADER}_internal.h") list(APPEND header_arguments "--header=${DIRECTORY}/${ARGS_GENERATE_HEADER}.h") list(APPEND header_arguments "--internal-header=${DIRECTORY}/${ARGS_GENERATE_HEADER}_internal.h") endif(ARGS_GENERATE_HEADER) add_custom_command(OUTPUT ${out_files} COMMAND ${VALA_EXECUTABLE} ARGS "-C" ${header_arguments} ${vapi_arguments} "-b" ${CMAKE_CURRENT_SOURCE_DIR} "-d" ${DIRECTORY} ${vala_pkg_opts} ${vala_define_opts} ${ARGS_OPTIONS} ${in_files} ${custom_vapi_arguments} DEPENDS ${in_files} ${ARGS_CUSTOM_VAPIS} ) set(${output} ${out_files} PARENT_SCOPE) endfunction(vala_precompile) address-book-service-0.1.1+14.04.20140408.3/cmake/vala/FindVala.cmake0000644000015301777760000000611312321057324024756 0ustar pbusernogroup00000000000000## # Find module for the Vala compiler (valac) # # This module determines wheter a Vala compiler is installed on the current # system and where its executable is. # # Call the module using "find_package(Vala) from within your CMakeLists.txt. # # The following variables will be set after an invocation: # # VALA_FOUND Whether the vala compiler has been found or not # VALA_EXECUTABLE Full path to the valac executable if it has been found # VALA_VERSION Version number of the available valac # VALA_USE_FILE Include this file to define the vala_precompile function ## ## # Copyright 2009-2010 Jakob Westhoff. All rights reserved. # Copyright 2010-2011 Daniel Pfeifer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY JAKOB WESTHOFF ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL JAKOB WESTHOFF OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of Jakob Westhoff ## # Search for the valac executable in the usual system paths # Some distributions rename the valac to contain the major.minor in the binary name find_program(VALA_EXECUTABLE NAMES valac valac-0.20 valac-0.18 valac-0.16 valac-0.14 valac-0.12 valac-0.10) mark_as_advanced(VALA_EXECUTABLE) # Determine the valac version if(VALA_EXECUTABLE) execute_process(COMMAND ${VALA_EXECUTABLE} "--version" OUTPUT_VARIABLE VALA_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE) string(REPLACE "Vala " "" VALA_VERSION "${VALA_VERSION}") endif(VALA_EXECUTABLE) # Handle the QUIETLY and REQUIRED arguments, which may be given to the find call. # Furthermore set VALA_FOUND to TRUE if Vala has been found (aka. # VALA_EXECUTABLE is set) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Vala REQUIRED_VARS VALA_EXECUTABLE VERSION_VAR VALA_VERSION) set(VALA_USE_FILE "${CMAKE_CURRENT_LIST_DIR}/UseVala.cmake") address-book-service-0.1.1+14.04.20140408.3/upstart/0000755000015301777760000000000012321057642021771 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/upstart/address-book-service.conf0000644000015301777760000000032712321057324026652 0ustar pbusernogroup00000000000000description "address-book-service" author "Bill Filler " start on started unity8 stop on session-end respawn exec /usr/lib/arm-linux-gnueabihf/address-book-service/address-book-service address-book-service-0.1.1+14.04.20140408.3/examples/0000755000015301777760000000000012321057642022105 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/examples/contacts.py0000644000015301777760000000664112321057324024301 0ustar pbusernogroup00000000000000#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # # Copyright 2013 Canonical Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # import dbus import argparse VCARD_JOE = """ BEGIN:VCARD VERSION:3.0 N:Gump;Forrest FN:Forrest Gump TEL;TYPE=WORK,VOICE;PID=1.1:(111) 555-1212 TEL;TYPE=HOME,VOICE;PID=1.2:(404) 555-1212 EMAIL;TYPE=PREF,INTERNET;PID=1.1:forrestgump@example.com END:VCARD """ class Contacts(object): def __init__(self): self.bus = None self.addr = None self.addr_iface = None def connect(self): self.bus = dbus.SessionBus() self.addr = self.bus.get_object('com.canonical.pim', '/com/canonical/pim/AddressBook') self.addr_iface = dbus.Interface(self.addr, dbus_interface='com.canonical.pim.AddressBook') def query(self, fields = '', query = '', sources = []): view_path = self.addr_iface.query(fields, query, []) view = self.bus.get_object('com.canonical.pim', view_path) view_iface = dbus.Interface(view, dbus_interface='com.canonical.pim.AddressBookView') contacts = view_iface.contactsDetails([], 0, -1) view.close() return contacts def update(self, vcard): return self.addr_iface.updateContacts([vcard]) def create(self, vcard): return self.addr_iface.createContact(vcard, "") def delete(self, ids): return self.addr_iface.removeContacts(ids) service = Contacts() service.connect() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('command', choices=['query','create','update', 'delete','load']) parser.add_argument('filename', action='store', nargs='?') args = parser.parse_args() if args.command == 'query': contacts = service.query() if contacts: for contact in contacts: print (contact) else: print ("No contacts found") if args.command == 'update': vcard = VCARD_JOE contactId = service.create(vcard) vcard = vcard.replace("VERSION:3.0", "VERSION:3.0\nUID:%s" % (contactId)) vcard = vcard.replace("N:Gump;Forrest", "N:Hanks;Tom") vcard = vcard.replace("FN:Forrest Gump", "FN:Tom Hanks") print (service.update(vcard)) if args.command == 'create': print ("New UID:", service.create(VCARD_JOE)) if args.command == 'delete': vcard = VCARD_JOE contactId = service.create(vcard) print ("Deleted contact: %d" % service.delete([contactId])) if args.command == 'load': if args.filename: f = open(args.filename, 'r') vcard = f.read() print ("New UID:", service.create(vcard)) else: print ("You must supply a path to a VCARD") address-book-service-0.1.1+14.04.20140408.3/tests/0000755000015301777760000000000012321057642021431 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/tests/data/0000755000015301777760000000000012321057642022342 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/tests/data/backend-store-key-file-data.ini0000644000015301777760000000025512321057324030175 0ustar pbusernogroup00000000000000#export FOLKS_BACKEND_KEY_FILE_PATH [0] __alias=Renato Araujo msn=renato@msn.com [1] __alias=Rodrigo Almeida msn=kiko@msn.com [2] __alias=Raphael Almeida msn=rafa@msn.com address-book-service-0.1.1+14.04.20140408.3/tests/data/CMakeLists.txt0000644000015301777760000000035012321057324025075 0ustar pbusernogroup00000000000000project(test-data) set(FOLKS_BACKEND_CONFIG_FILE "${CMAKE_CURRENT_SOURCE_DIR}/backend-store-key-file-only.ini" PARENT_SCOPE) set(FOLKS_KEY_FILE_DATA_FILE "${CMAKE_CURRENT_SOURCE_DIR}/backend-store-key-file-data.ini" PARENT_SCOPE) address-book-service-0.1.1+14.04.20140408.3/tests/CMakeLists.txt0000644000015301777760000000006212321057324024164 0ustar pbusernogroup00000000000000add_subdirectory(data) add_subdirectory(unittest) address-book-service-0.1.1+14.04.20140408.3/tests/unittest/0000755000015301777760000000000012321057642023310 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/tests/unittest/dummy-backend.h0000644000015301777760000001201012321057324026170 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __DUMMY_BACKEND_TEST_H__ #define __DUMMY_BACKEND_TEST_H__ #include "dummy-backend-defs.h" #include "lib/qindividual.h" #include #include #include #include #include #include #include #include class DummyBackendAdaptor; class DummyBackendProxy: public QObject { Q_OBJECT public: DummyBackendProxy(); ~DummyBackendProxy(); void start(bool useDBus = false); bool isReady() const; QString createContact(const QtContacts::QContact &qcontact); QString updateContact(const QString &contactId, const QtContacts::QContact &qcontact); QList contacts() const; QList individuals() const; FolksIndividualAggregator *aggregator() const; public Q_SLOTS: void shutdown(); QStringList listContacts() const; void reset(); void contactUpdated(const QString &contactId, const QString &errorMsg); Q_SIGNALS: void ready(); void stopped(); private: QTemporaryDir m_tmpDir; DummyBackendAdaptor *m_adaptor; FolksDummyBackend *m_backend; FolksDummyPersonaStore *m_primaryPersonaStore; FolksBackendStore *m_backendStore; QEventLoop *m_eventLoop; FolksIndividualAggregator *m_aggregator; bool m_isReady; int m_individualsChangedDetailedId; QHash m_contacts; bool m_contactUpdated; bool m_useDBus; bool registerObject(); void initFolks(); void configurePrimaryStore(); void initEnviroment(); void prepareAggregator(); void mkpath(const QString &path) const; static void checkError(GError *error); static void backendEnabled(FolksBackendStore *backendStore, GAsyncResult *res, DummyBackendProxy *self); static void backendStoreLoaded(FolksBackendStore *backendStore, GAsyncResult *res, DummyBackendProxy *self); static void individualAggregatorPrepared(FolksIndividualAggregator *fia, GAsyncResult *res, DummyBackendProxy *self); static void individualAggregatorAddedPersona(FolksIndividualAggregator *fia, GAsyncResult *res, DummyBackendProxy *self); static void individualsChangedCb(FolksIndividualAggregator *individualAggregator, GeeMultiMap *changes, DummyBackendProxy *self); }; class DummyBackendAdaptor: public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", DUMMY_IFACE_NAME) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") Q_PROPERTY(bool isReady READ isReady NOTIFY ready) public: DummyBackendAdaptor(const QDBusConnection &connection, DummyBackendProxy *parent); virtual ~DummyBackendAdaptor(); bool isReady(); public Q_SLOTS: bool ping(); void quit(); void reset(); QStringList listContacts(); QString createContact(const QString &vcard); QString updateContact(const QString &contactId, const QString &vcard); void enableAutoLink(bool flag); Q_SIGNALS: void ready(); void stopped(); private: QDBusConnection m_connection; DummyBackendProxy *m_proxy; }; #endif address-book-service-0.1.1+14.04.20140408.3/tests/unittest/vcardparser-test.cpp0000644000015301777760000003252512321057324027311 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 #include #include #include #include "common/vcard-parser.h" using namespace QtContacts; using namespace galera; typedef QList QContactList; class VCardParseTest : public QObject { Q_OBJECT private: QStringList m_vcards; QList m_contacts; void compareContact(const QtContacts::QContact &contact, const QtContacts::QContact &other) { // name QCOMPARE(contact.detail(QtContacts::QContactDetail::TypeName), other.detail(QtContacts::QContactDetail::TypeName)); // phone - this is necessary because: // 1 ) the QContactDetail::FieldDetailUri can change based on the detail order // 2 ) the phone number can be returned in different order QList phones = contact.details(QtContacts::QContactDetail::TypePhoneNumber); QList otherPhones = other.details(QtContacts::QContactDetail::TypePhoneNumber); QCOMPARE(phones.size(), otherPhones.size()); for(int i=0; i < phones.size(); i++) { QtContacts::QContactDetail phone = phones[i]; bool found = false; for(int x=0; x < otherPhones.size(); x++) { QtContacts::QContactDetail otherPhone = otherPhones[x]; if (phone.value(QtContacts::QContactPhoneNumber::FieldNumber) == otherPhone.value(QtContacts::QContactPhoneNumber::FieldNumber)) { found = true; QList phoneTypes = phone.value(QtContacts::QContactPhoneNumber::FieldSubTypes).value< QList >(); QList otherPhoneTypes = otherPhone.value(QtContacts::QContactPhoneNumber::FieldSubTypes).value< QList >(); QCOMPARE(phoneTypes, otherPhoneTypes); QCOMPARE(phone.value(QtContacts::QContactPhoneNumber::FieldContext), otherPhone.value(QtContacts::QContactPhoneNumber::FieldContext)); break; } } QVERIFY2(found, "Phone number is not equal"); } // email same as phone number QList emails = contact.details(QtContacts::QContactDetail::TypeEmailAddress); QList otherEmails = other.details(QtContacts::QContactDetail::TypeEmailAddress); QCOMPARE(emails.size(), otherEmails.size()); for(int i=0; i < emails.size(); i++) { QtContacts::QContactDetail email = emails[i]; bool found = false; for(int x=0; x < otherEmails.size(); x++) { QtContacts::QContactDetail otherEmail = otherEmails[x]; if (email.value(QtContacts::QContactEmailAddress::FieldEmailAddress) == otherEmail.value(QtContacts::QContactEmailAddress::FieldEmailAddress)) { found = true; QCOMPARE(email.value(QtContacts::QContactEmailAddress::FieldContext), otherEmail.value(QtContacts::QContactEmailAddress::FieldContext)); break; } } QVERIFY2(found, "Email is not equal"); } } /* * Use this function to compare vcards because the order of the attributes in the returned vcard * can be different for each vcard. Example: * "TEL;PID=1.1;TYPE=ISDN:33331410\r\n" or "TEL;TYPE=ISDN;PID=1.1:33331410\r\n" */ void compareVCards(const QString &vcard, const QString &other) { QStringList vcardLines = vcard.split("\n", QString::SkipEmptyParts); QStringList otherLines = other.split("\n", QString::SkipEmptyParts); QCOMPARE(vcardLines.size(), otherLines.size()); for(int i=0; i < vcardLines.size(); i++) { QString value = vcardLines[i].split(":").last(); QString otherValue = otherLines.first().split(":").last(); // compare values. After ":" QCOMPARE(value, otherValue); QString attribute = vcardLines[i].split(":").first(); QString attributeOther = otherLines.first().split(":").first(); // compare attributes. Before ":" QStringList attributeFields = attribute.split(";"); QStringList attributeOtherFields = attributeOther.split(";"); Q_FOREACH(const QString &attr, attributeFields) { attributeOtherFields.removeOne(attr); } QVERIFY2(attributeOtherFields.size() == 0, QString("Vcard attribute is not equal (%1) != (%2)").arg(vcardLines[i]).arg(otherLines.first()).toUtf8()); otherLines.removeFirst(); } } private Q_SLOTS: void init() { m_vcards << QStringLiteral("BEGIN:VCARD\r\n" "VERSION:3.0\r\n" "N:Sauro;Dino;da Silva;;\r\n" "EMAIL:dino@familiadinosauro.com.br\r\n" "TEL;PID=1.1;TYPE=ISDN:33331410\r\n" "TEL;PID=1.2;TYPE=CELL:8888888\r\n" "END:VCARD\r\n"); m_vcards << QStringLiteral("BEGIN:VCARD\r\n" "VERSION:3.0\r\n" "N:Sauro;Baby;da Silva;;\r\n" "EMAIL:baby@familiadinosauro.com.br\r\n" "TEL;PID=1.1;TYPE=ISDN:1111111\r\n" "TEL;PID=1.2;TYPE=CELL:2222222\r\n" "END:VCARD\r\n"); QContact contactDino; QContactName name; name.setFirstName("Dino"); name.setMiddleName("da Silva"); name.setLastName("Sauro"); contactDino.saveDetail(&name); QContactEmailAddress email; email.setEmailAddress("dino@familiadinosauro.com.br"); contactDino.saveDetail(&email); QContactPhoneNumber phoneLandLine; phoneLandLine.setSubTypes(QList() << QContactPhoneNumber::SubTypeLandline); phoneLandLine.setNumber("33331410"); phoneLandLine.setDetailUri("1.1"); contactDino.saveDetail(&phoneLandLine); QContactPhoneNumber phoneMobile; phoneMobile.setSubTypes(QList() << QContactPhoneNumber::SubTypeMobile); phoneMobile.setNumber("8888888"); phoneMobile.setDetailUri("1.2"); contactDino.saveDetail(&phoneMobile); QContact contactBaby; name.setFirstName("Baby"); name.setMiddleName("da Silva"); name.setLastName("Sauro"); contactBaby.saveDetail(&name); email.setEmailAddress("baby@familiadinosauro.com.br"); contactBaby.saveDetail(&email); phoneLandLine.setSubTypes(QList() << QContactPhoneNumber::SubTypeLandline); phoneLandLine.setNumber("1111111"); phoneLandLine.setDetailUri("1.1"); contactBaby.saveDetail(&phoneLandLine); phoneMobile.setSubTypes(QList() << QContactPhoneNumber::SubTypeMobile); phoneMobile.setNumber("2222222"); phoneMobile.setDetailUri("1.2"); contactBaby.saveDetail(&phoneMobile); m_contacts << contactDino << contactBaby; } void cleanup() { m_vcards.clear(); m_contacts.clear(); } /* * Test parse from vcard to contact using the async function */ void testVCardToContactAsync() { VCardParser parser; qRegisterMetaType< QList >(); QSignalSpy vcardToContactSignal(&parser, SIGNAL(contactsParsed(QList))); parser.vcardToContact(m_vcards); QTRY_COMPARE(vcardToContactSignal.count(), 1); QList arguments = vcardToContactSignal.takeFirst(); QCOMPARE(arguments.size(), 1); QList contacts = qvariant_cast >(arguments.at(0)); QCOMPARE(contacts.size(), 2); compareContact(contacts[0], m_contacts[0]); compareContact(contacts[1], m_contacts[1]); } /* * Test parse from vcard to contact using the sync function */ void testVCardToContactSync() { QList contacts = VCardParser::vcardToContactSync(m_vcards); QCOMPARE(contacts.size(), 2); compareContact(contacts[0], m_contacts[0]); compareContact(contacts[1], m_contacts[1]); } /* * Test parse a single vcard to contact using the sync function */ void testSingleVCardToContactSync() { QContact contact = VCardParser::vcardToContact(m_vcards[0]); compareContact(contact, m_contacts[0]); } /* * Test parse a invalid vcard */ void testInvalidVCard() { QString vcard("BEGIN:VCARD\r\nEND::VCARD\r\n"); QContact contact = VCardParser::vcardToContact(vcard); QVERIFY(contact.isEmpty()); } /* * Test parse contacts to vcard using the async function */ void testContactToVCardAsync() { VCardParser parser; QSignalSpy contactToVCardSignal(&parser, SIGNAL(vcardParsed(QStringList))); parser.contactToVcard(m_contacts); // Check if the vcardParsed signal was fired QTRY_COMPARE(contactToVCardSignal.count(), 1); // Check if the signal was fired with two vcards QList arguments = contactToVCardSignal.takeFirst(); QCOMPARE(arguments.size(), 1); QStringList vcardsResults = qvariant_cast(arguments.at(0)); QCOMPARE(vcardsResults.size(), 2); // Check if the vcard in the signals was correct parsed compareVCards(vcardsResults[0], m_vcards[0]); compareVCards(vcardsResults[1], m_vcards[1]); } /* * Test parse contacts to vcard using the sync function */ void testContactToVCardSync() { QStringList vcards = VCardParser::contactToVcardSync(m_contacts); QCOMPARE(vcards.size(), 2); // Check if the returned vcards are correct compareVCards(vcards[0], m_vcards[0]); compareVCards(vcards[1], m_vcards[1]); } /* * Test parse a single contact to vcard using the sync function */ void testSingContactToVCardSync() { QString vcard = VCardParser::contactToVcard(m_contacts[0]); // Check if the returned vcard is correct compareVCards(vcard, m_vcards[0]); } /* * Test parse a vcard with sync target into a Contact */ void testVCardWithSyncTargetToContact() { QString vcard = QStringLiteral("BEGIN:VCARD\r\n" "VERSION:3.0\r\n" "CLIENTPIDMAP;PID=1.ADDRESSBOOKID0:ADDRESSBOOKNAME0\r\n" "CLIENTPIDMAP;PID=2.ADDRESSBOOKID1:ADDRESSBOOKNAME1\r\n" "N:Sauro;Dino;da Silva;;\r\n" "EMAILPID=1.1;:dino@familiadinosauro.com.br\r\n" "TEL;PID=1.1;TYPE=ISDN:33331410\r\n" "TEL;PID=1.2;TYPE=CELL:8888888\r\n" "END:VCARD\r\n"); QContact contact = VCardParser::vcardToContact(vcard); QList targets = contact.details(); QCOMPARE(targets.size(), 2); QContactSyncTarget target0; QContactSyncTarget target1; // put the target in order if (targets[0].detailUri().startsWith("1.")) { target0 = targets[0]; target1 = targets[1]; } else { target0 = targets[1]; target1 = targets[2]; } QCOMPARE(target0.detailUri(), QString("1.ADDRESSBOOKID0")); QCOMPARE(target0.syncTarget(), QString("ADDRESSBOOKNAME0")); QCOMPARE(target1.detailUri(), QString("2.ADDRESSBOOKID1")); QCOMPARE(target1.syncTarget(), QString("ADDRESSBOOKNAME1")); } /* * Test parse a Contact with sync target into a vcard */ void testContactWithSyncTargetToVCard() { QContact c = m_contacts[0]; QContactSyncTarget target; target.setDetailUri("1.ADDRESSBOOKID0"); target.setSyncTarget("ADDRESSBOOKNAME0"); c.saveDetail(&target); QContactSyncTarget target1; target1.setDetailUri("2.ADDRESSBOOKID1"); target1.setSyncTarget("ADDRESSBOOKNAME1"); c.saveDetail(&target1); QString vcard = VCardParser::contactToVcard(c); QVERIFY(vcard.contains("CLIENTPIDMAP;PID=1.ADDRESSBOOKID0:ADDRESSBOOKNAME0")); QVERIFY(vcard.contains("CLIENTPIDMAP;PID=2.ADDRESSBOOKID1:ADDRESSBOOKNAME1")); } }; QTEST_MAIN(VCardParseTest) #include "vcardparser-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/contactmap-test.cpp0000644000015301777760000001102112321057324027112 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "config.h" #include "dummy-backend.h" #include "scoped-loop.h" #include "lib/contacts-map.h" #include "lib/qindividual.h" #include #include #include #include #include #include class ContactMapTest : public QObject { Q_OBJECT private: DummyBackendProxy *m_dummy; galera::ContactsMap m_map; QList m_individuals; int randomIndex() const { return qrand() % m_map.size(); } FolksIndividual *randomIndividual() const { return m_individuals[randomIndex()]; } void createContactWithSuffix(const QString &suffix) { QtContacts::QContact contact; QtContacts::QContactName name; name.setFirstName(QString("Fulano_%1").arg(suffix)); name.setMiddleName("de"); name.setLastName("Tal"); contact.saveDetail(&name); QtContacts::QContactEmailAddress email; email.setEmailAddress(QString("fulano_%1@ubuntu.com").arg(suffix)); contact.saveDetail(&email); QtContacts::QContactPhoneNumber phone; phone.setNumber("33331410"); contact.saveDetail(&phone); m_dummy->createContact(contact); } private Q_SLOTS: void initTestCase() { m_dummy = new DummyBackendProxy(); m_dummy->start(); QTRY_VERIFY(m_dummy->isReady()); createContactWithSuffix("1"); createContactWithSuffix("2"); createContactWithSuffix("3"); Q_FOREACH(galera::QIndividual *i, m_dummy->individuals()) { m_map.insert(new galera::ContactEntry(new galera::QIndividual(i->individual(), m_dummy->aggregator()))); m_individuals << i->individual(); } } void cleanupTestCase() { m_dummy->shutdown(); delete m_dummy; m_map.clear(); } void testLookupByFolksIndividual() { QVERIFY(m_map.size() > 0); FolksIndividual *fIndividual = randomIndividual(); QVERIFY(m_map.contains(fIndividual)); galera::ContactEntry *entry = m_map.value(fIndividual); QVERIFY(entry->individual()->individual() == fIndividual); } void testLookupByFolksIndividualId() { FolksIndividual *fIndividual = randomIndividual(); QString id = QString::fromUtf8(folks_individual_get_id(fIndividual)); galera::ContactEntry *entry = m_map.value(id); QVERIFY(entry->individual()->individual() == fIndividual); } void testValues() { QList entries = m_map.values(); QCOMPARE(entries.size(), m_map.size()); QCOMPARE(m_individuals.size(), m_map.size()); Q_FOREACH(FolksIndividual *individual, m_individuals) { QVERIFY(m_map.contains(individual)); } } void testTakeIndividual() { FolksIndividual *individual = folks_individual_new(0); QVERIFY(m_map.take(individual) == 0); QVERIFY(!m_map.contains(individual)); g_object_unref(individual); individual = randomIndividual(); galera::ContactEntry *entry = m_map.take(individual); QVERIFY(entry->individual()->individual() == individual); //put it back m_map.insert(entry); } void testLookupByVcard() { FolksIndividual *individual = randomIndividual(); QString id = QString::fromUtf8(folks_individual_get_id(individual)); QString vcard = QString("BEGIN:VCARD\r\n" "VERSION:3.0\r\n" "UID:%1\r\n" "N:Gump;Forrest\r\n" "FN:Forrest Gump\r\n" "REV:2008-04-24T19:52:43Z\r\n").arg(id); galera::ContactEntry *entry = m_map.valueFromVCard(vcard); QVERIFY(entry); QVERIFY(entry->individual()->individual() == individual); } }; QTEST_MAIN(ContactMapTest) #include "contactmap-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/qcontacts-test.cpp0000644000015301777760000001525412321057324026774 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "base-client-test.h" #include "common/source.h" #include "common/dbus-service-defs.h" #include "common/vcard-parser.h" #include #include #include #include #include #include "config.h" using namespace QtContacts; class QContactsTest : public BaseClientTest { Q_OBJECT private: QContactManager *m_manager; QContact testContact() { // create a contact QContact contact; QContactName name; name.setFirstName("Fulano"); name.setMiddleName("de"); name.setLastName("Tal"); contact.saveDetail(&name); QContactEmailAddress email; email.setEmailAddress("fulano@email.com"); contact.saveDetail(&email); return contact; } private Q_SLOTS: void initTestCase() { BaseClientTest::initTestCase(); QCoreApplication::setLibraryPaths(QStringList() << QT_PLUGINS_BINARY_DIR); } void init() { BaseClientTest::init(); m_manager = new QContactManager("galera"); } void cleanup() { delete m_manager; BaseClientTest::cleanup(); } void testAvailableManager() { QVERIFY(QContactManager::availableManagers().contains("galera")); } /* * Test create a new contact */ void testCreateContact() { // filter all contacts QContactFilter filter; // check result, must be empty QList contacts = m_manager->contacts(filter); QCOMPARE(contacts.size(), 0); // create a contact QContact contact = testContact(); QSignalSpy spyContactAdded(m_manager, SIGNAL(contactsAdded(QList))); bool result = m_manager->saveContact(&contact); QCOMPARE(result, true); QTRY_COMPARE(spyContactAdded.count(), 1); // query for new contacts contacts = m_manager->contacts(filter); QCOMPARE(contacts.size(), 1); QContact createdContact = contacts[0]; // id QVERIFY(!createdContact.id().isNull()); // email QContactEmailAddress email = contact.detail(); QContactEmailAddress createdEmail = createdContact.detail(); QCOMPARE(createdEmail.emailAddress(), email.emailAddress()); // name QContactName name = contact.detail(); QContactName createdName = createdContact.detail(); QCOMPARE(createdName.firstName(), name.firstName()); QCOMPARE(createdName.middleName(), name.middleName()); QCOMPARE(createdName.lastName(), name.lastName()); QContactSyncTarget target = contact.detail(); QCOMPARE(target.syncTarget(), QString("Dummy personas")); } #if 0 /* * Test create a new contact */ void testUpdateContact() { // filter all contacts QContactFilter filter; // create a contact QContact contact = testContact(); QSignalSpy spyContactAdded(m_manager, SIGNAL(contactsAdded(QList))); bool result = m_manager->saveContact(&contact); QCOMPARE(result, true); QTRY_COMPARE(spyContactAdded.count(), 1); QContactName name = contact.detail(); name.setMiddleName("da"); name.setLastName("Silva"); contact.saveDetail(&name); QSignalSpy spyContactChanged(m_manager, SIGNAL(contactsChanged(QList))); result = m_manager->saveContact(&contact); QCOMPARE(result, true); QTRY_COMPARE(spyContactChanged.count(), 1); // query for the contacts QList contacts = m_manager->contacts(filter); QCOMPARE(contacts.size(), 1); QContact updatedContact = contacts[0]; // name QContactName updatedName = updatedContact.detail(); QCOMPARE(updatedName.firstName(), name.firstName()); QCOMPARE(updatedName.middleName(), name.middleName()); QCOMPARE(updatedName.lastName(), name.lastName()); } /* * Test create a contact source using the contact group */ void testCreateGroup() { QContactManager manager("galera"); // create a contact QContact contact; contact.setType(QContactType::TypeGroup); QContactDisplayLabel label; label.setLabel("test group"); contact.saveDetail(&label); bool result = manager.saveContact(&contact); QCOMPARE(result, true); // query for new contacts QContactDetailFilter filter; filter.setDetailType(QContactDetail::TypeType, QContactType::FieldType); filter.setValue(QContactType::TypeGroup); QList contacts = manager.contacts(filter); // will be two sources since we have the main source already created QCOMPARE(contacts.size(), 2); QContact createdContact = contacts[0]; // id QVERIFY(!createdContact.id().isNull()); // label QContactDisplayLabel createdlabel = createdContact.detail(); QCOMPARE(createdlabel.label(), label.label()); } /* * Test query a contact source using the contact group */ void testQueryGroups() { QContactManager manager("galera"); // filter all contact groups/addressbook QContactDetailFilter filter; filter.setDetailType(QContactDetail::TypeType, QContactType::FieldType); filter.setValue(QContactType::TypeGroup); // check result QList contacts = manager.contacts(filter); QCOMPARE(contacts.size(), 1); QCOMPARE(contacts[0].id().toString(), QStringLiteral("qtcontacts:galera::dummy-store")); QCOMPARE(contacts[0].type(), QContactType::TypeGroup); QContactDisplayLabel label = contacts[0].detail(QContactDisplayLabel::Type); QCOMPARE(label.label(), QStringLiteral("Dummy personas")); } #endif }; QTEST_MAIN(QContactsTest) #include "qcontacts-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/addressbook-server.cpp0000644000015301777760000000225612321057324027622 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "lib/addressbook.h" #include "dummy-backend.h" #include int main(int argc, char** argv) { galera::AddressBook::init(); QCoreApplication app(argc, argv); // dummy DummyBackendProxy dummy; dummy.start(true); // addressbook galera::AddressBook book; book.connect(&dummy, SIGNAL(ready()), SLOT(start())); book.connect(&dummy, SIGNAL(stopped()), SLOT(shutdown())); app.connect(&book, SIGNAL(stopped()), SLOT(quit())); return app.exec(); } address-book-service-0.1.1+14.04.20140408.3/tests/unittest/service-life-cycle-test.cpp0000644000015301777760000000335412321057324030445 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "base-client-test.h" #include "common/dbus-service-defs.h" #include #include #include #include class ServiceLifeCycleTest : public BaseClientTest { Q_OBJECT private Q_SLOTS: void testServiceReady() { QTRY_COMPARE(m_serverIface->property("isReady").toBool(), true); QTRY_COMPARE(m_dummyIface->property("isReady").toBool(), true); } void testCallServiceFunction() { QDBusReply result = m_serverIface->call("ping"); QCOMPARE(result.value(), true); result = m_dummyIface->call("ping"); QCOMPARE(result.value(), true); } void testServiceShutdown() { m_dummyIface->call("quit"); // wait service quits QTest::qSleep(100); QDBusReply result = m_serverIface->call("ping"); QVERIFY(result.error().isValid()); result = m_dummyIface->call("ping"); QVERIFY(result.error().isValid()); } }; QTEST_MAIN(ServiceLifeCycleTest) #include "service-life-cycle-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/fetch-hint-test.cpp0000644000015301777760000000473412321057324027027 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 #include #include #include #include "common/fetch-hint.h" using namespace QtContacts; using namespace galera; class FetchHintTest : public QObject { Q_OBJECT private Q_SLOTS: void testSimpleFields() { const QString strHint = QString("FIELDS:N,TEL"); FetchHint hint(strHint); QVERIFY(!hint.isEmpty()); QCOMPARE(hint.fields(), QStringList() << "N" << "TEL"); QContactFetchHint cHint; cHint.setDetailTypesHint(QList() << QContactDetail::TypeName << QContactDetail::TypePhoneNumber); QVERIFY(cHint.detailTypesHint() == hint.toContactFetchHint().detailTypesHint()); FetchHint hint2(cHint); QCOMPARE(hint2.toString(), strHint); } void testInvalidHint() { const QString strHint = QString("FIELDSS:N,TEL"); FetchHint hint(strHint); QVERIFY(hint.isEmpty()); } void testInvalidFieldName() { const QString strHint = QString("FIELDS:N,NONE,TEL,INVALID"); FetchHint hint(strHint); QVERIFY(!hint.isEmpty()); QCOMPARE(hint.fields(), QStringList() << "N" << "TEL"); } void testParseFieldNames() { QList fields = FetchHint::parseFieldNames(QStringList() << "ADR" << "BDAY" << "N" << "TEL"); QList expectedFields; expectedFields << QContactDetail::TypeAddress << QContactDetail::TypeBirthday << QContactDetail::TypeName << QContactDetail::TypePhoneNumber; QCOMPARE(fields, expectedFields); } }; QTEST_MAIN(FetchHintTest) #include "fetch-hint-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/clause-test.cpp0000644000015301777760000000472612321057324026253 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 #include #include #include #include "common/filter.h" using namespace QtContacts; using namespace galera; class ClauseParseTest : public QObject { Q_OBJECT private Q_SLOTS: void testParseClause() { // Create manager to allow us to creact contact id QContactManager manager("memory"); QContactId id5 = QContactId::fromString("qtcontacts:memory::5"); QContactId id2 = QContactId::fromString("qtcontacts:memory::2"); QContactGuid guid5; guid5.setGuid("5"); QContactGuid guid2; guid2.setGuid("2"); // guid is necessary because our server uses that for compare ids // check Filter source code for more details QContact contact5; contact5.setId(id5); contact5.appendDetail(guid5); QContact contact2; contact2.setId(id2); contact2.appendDetail(guid2); QContactIdFilter originalFilter = QContactIdFilter(); originalFilter.setIds(QList() << QContactId::fromString("qtcontacts:memory::1") << QContactId::fromString("qtcontacts:memory::2") << QContactId::fromString("qtcontacts:memory::3")); QString filterString = Filter(originalFilter).toString(); Filter filterFromString = Filter(filterString); QCOMPARE(filterFromString.test(contact5), false); QCOMPARE(filterFromString.test(contact2), true); QCOMPARE(filterFromString.test(contact5), QContactManagerEngine::testFilter(originalFilter, contact5)); QCOMPARE(filterFromString.test(contact2), QContactManagerEngine::testFilter(originalFilter, contact2)); } }; QTEST_MAIN(ClauseParseTest) #include "clause-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/scoped-loop.cpp0000644000015301777760000000204312321057324026234 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "scoped-loop.h" ScopedEventLoop::ScopedEventLoop(QEventLoop **proxy) { reset(proxy); } ScopedEventLoop::~ScopedEventLoop() { *m_proxy = 0; } void ScopedEventLoop::reset(QEventLoop **proxy) { *proxy = &m_eventLoop; m_proxy = proxy; } void ScopedEventLoop::exec() { if (*m_proxy) { m_eventLoop.exec(); *m_proxy = 0; } } address-book-service-0.1.1+14.04.20140408.3/tests/unittest/base-client-test.h0000644000015301777760000000210612321057324026620 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __BASE_DUMMY_TEST_H__ #define __BASE_DUMMY_TEST_H__ #include #include #include class BaseClientTest : public QObject { Q_OBJECT protected: QDBusInterface *m_serverIface; QDBusInterface *m_dummyIface; protected Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); }; #endif address-book-service-0.1.1+14.04.20140408.3/tests/unittest/readonly-prop-test.cpp0000644000015301777760000000534512321057324027570 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "base-client-test.h" #include "common/source.h" #include "common/dbus-service-defs.h" #include "common/vcard-parser.h" #include #include #include #include #include class ReadOnlyPropTest : public BaseClientTest { Q_OBJECT private: QString m_basicVcard; QString m_resultBasicVcard; private Q_SLOTS: void initTestCase() { BaseClientTest::initTestCase(); m_basicVcard = QStringLiteral("BEGIN:VCARD\n" "VERSION:3.0\n" "N:Tal;Fulano_;de;;\n" "EMAIL:fulano_@ubuntu.com\n" "TEL;PID=1.1;TYPE=ISDN:33331410\n" "TEL;PID=1.2;TYPE=CELL:8888888\n" "URL:www.canonical.com\n" "END:VCARD"); } void testCreateContactAndReturnReadOlyFileds() { // call create contact QDBusReply reply = m_serverIface->call("createContact", m_basicVcard, "dummy-store"); // check if the returned id is valid QString newContactId = reply.value(); QVERIFY(!newContactId.isEmpty()); // check if the cotact was created with URL as read-only field // URL is not a writable property on our dummy backend QDBusReply reply2 = m_dummyIface->call("listContacts"); QCOMPARE(reply2.value().count(), 1); QList contactsCreated = galera::VCardParser::vcardToContactSync(reply2.value()); QCOMPARE(contactsCreated.count(), 1); Q_FOREACH(QContactDetail det, contactsCreated[0].details()) { if (det.type() == QContactDetail::TypeUrl) { QVERIFY(det.accessConstraints().testFlag(QContactDetail::ReadOnly)); } else { QVERIFY(!det.accessConstraints().testFlag(QContactDetail::ReadOnly)); } } } }; QTEST_MAIN(ReadOnlyPropTest) #include "readonly-prop-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/scoped-loop.h0000644000015301777760000000174412321057324025710 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __SCOPED_LOOP_H__ #define __SCOPED_LOOP_H__ #include class ScopedEventLoop { public: ScopedEventLoop(QEventLoop **proxy); ~ScopedEventLoop(); void reset(QEventLoop **proxy); void exec(); private: QEventLoop m_eventLoop; QEventLoop **m_proxy; }; #endif address-book-service-0.1.1+14.04.20140408.3/tests/unittest/dummy-backend.cpp0000644000015301777760000003556212321057334026545 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "config.h" #include "dummy-backend.h" #include "scoped-loop.h" #include "lib/qindividual.h" #include "common/vcard-parser.h" #include #include DummyBackendProxy::DummyBackendProxy() : m_adaptor(0), m_backend(0), m_primaryPersonaStore(0), m_backendStore(0), m_aggregator(0), m_isReady(false), m_individualsChangedDetailedId(0) { } DummyBackendProxy::~DummyBackendProxy() { shutdown(); } void DummyBackendProxy::start(bool useDBus) { m_useDBus = useDBus; initEnviroment(); initFolks(); } void DummyBackendProxy::shutdown() { m_isReady = false; if (m_adaptor) { QDBusConnection connection = QDBusConnection::sessionBus(); connection.unregisterObject(DUMMY_OBJECT_PATH); connection.unregisterService(DUMMY_SERVICE_NAME); delete m_adaptor; m_adaptor = 0; Q_EMIT stopped(); } Q_FOREACH(galera::QIndividual *i, m_contacts.values()) { delete i; } m_contacts.clear(); if (m_aggregator) { g_signal_handler_disconnect(m_aggregator, m_individualsChangedDetailedId); g_object_unref(m_aggregator); m_aggregator = 0; } if (m_primaryPersonaStore) { g_object_unref(m_primaryPersonaStore); m_primaryPersonaStore = 0; } if (m_backend) { g_object_unref(m_backend); m_backend = 0; } if (m_backendStore) { g_object_unref(m_backendStore); m_backendStore = 0; } } QList DummyBackendProxy::contacts() const { QList contacts; Q_FOREACH(galera::QIndividual *i, m_contacts.values()) { contacts << i->contact(); } return contacts; } QList DummyBackendProxy::individuals() const { return m_contacts.values(); } FolksIndividualAggregator *DummyBackendProxy::aggregator() const { return m_aggregator; } QStringList DummyBackendProxy::listContacts() const { return galera::VCardParser::contactToVcardSync(contacts()); } void DummyBackendProxy::reset() { if (m_contacts.count()) { GeeMap *map = folks_persona_store_get_personas((FolksPersonaStore*)m_primaryPersonaStore); GeeCollection *personas = gee_map_get_values(map); folks_dummy_persona_store_unregister_personas(m_primaryPersonaStore, (GeeSet*)personas); g_object_unref(personas); m_contacts.clear(); } // remove any extra collection/persona store GeeHashSet *extraStores = gee_hash_set_new(FOLKS_TYPE_PERSONA_STORE, (GBoxedCopyFunc) g_object_ref, g_object_unref, NULL, NULL, NULL, NULL, NULL, NULL); GeeMap *currentStores = folks_backend_get_persona_stores(FOLKS_BACKEND(m_backend)); GeeSet *keys = gee_map_get_keys(currentStores); GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(keys)); while(gee_iterator_next(iter)) { const gchar *key = (const gchar*) gee_iterator_get(iter); if (strcmp(key, "dummy-store") != 0) { FolksPersonaStore *store = FOLKS_PERSONA_STORE(gee_map_get(currentStores, key)); gee_abstract_collection_add(GEE_ABSTRACT_COLLECTION(extraStores), store); g_object_unref(store); } } if (gee_collection_get_size(GEE_COLLECTION(extraStores)) > 0) { folks_dummy_backend_unregister_persona_stores(m_backend, GEE_SET(extraStores)); } g_object_unref(extraStores); g_object_unref(keys); g_object_unref(iter); } void DummyBackendProxy::initFolks() { m_backendStore = folks_backend_store_dup(); folks_backend_store_load_backends(m_backendStore, (GAsyncReadyCallback) DummyBackendProxy::backendStoreLoaded, this); } bool DummyBackendProxy::isReady() const { return m_isReady; } void DummyBackendProxy::prepareAggregator() { m_aggregator = folks_individual_aggregator_dup(); m_individualsChangedDetailedId = g_signal_connect(m_aggregator, "individuals-changed-detailed", (GCallback) DummyBackendProxy::individualsChangedCb, this); folks_individual_aggregator_prepare(m_aggregator, (GAsyncReadyCallback) DummyBackendProxy::individualAggregatorPrepared, this); } QString DummyBackendProxy::createContact(const QtContacts::QContact &qcontact) { ScopedEventLoop loop(&m_eventLoop); GHashTable *details = galera::QIndividual::parseDetails(qcontact); Q_ASSERT(details); folks_individual_aggregator_add_persona_from_details(m_aggregator, NULL, //parent FOLKS_PERSONA_STORE(m_primaryPersonaStore), details, (GAsyncReadyCallback) DummyBackendProxy::individualAggregatorAddedPersona, this); loop.exec(); //g_object_unref(details); return QString(); } void DummyBackendProxy::contactUpdated(const QString &contactId, const QString &errorMsg) { m_contactUpdated = true; } QString DummyBackendProxy::updateContact(const QString &contactId, const QtContacts::QContact &qcontact) { galera::QIndividual *i = m_contacts.value(contactId); Q_ASSERT(i); ScopedEventLoop loop(&m_eventLoop); m_contactUpdated = false; i->update(qcontact, this, SLOT(contactUpdated(QString,QString))); loop.exec(); return i->id(); } void DummyBackendProxy::configurePrimaryStore() { static const char* writableProperties[] = { folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_FULL_NAME), folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_ALIAS), folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_NICKNAME), folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_STRUCTURED_NAME), folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_IS_FAVOURITE), folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_EMAIL_ADDRESSES), folks_persona_store_detail_key(FOLKS_PERSONA_DETAIL_PHONE_NUMBERS), 0 }; m_primaryPersonaStore = folks_dummy_persona_store_new("dummy-store", "Dummy personas", const_cast(writableProperties), 7); folks_dummy_persona_store_set_persona_type(m_primaryPersonaStore, FOLKS_DUMMY_TYPE_FULL_PERSONA); folks_dummy_persona_store_update_trust_level(m_primaryPersonaStore, FOLKS_PERSONA_STORE_TRUST_FULL); GeeHashSet *personaStores = gee_hash_set_new(FOLKS_TYPE_PERSONA_STORE, (GBoxedCopyFunc) g_object_ref, g_object_unref, NULL, NULL, NULL, NULL, NULL, NULL); gee_abstract_collection_add(GEE_ABSTRACT_COLLECTION(personaStores), m_primaryPersonaStore); folks_dummy_backend_register_persona_stores(m_backend, GEE_SET(personaStores), true); folks_dummy_persona_store_reach_quiescence(m_primaryPersonaStore); g_object_unref(personaStores); prepareAggregator(); } void DummyBackendProxy::backendEnabled(FolksBackendStore *backendStore, GAsyncResult *res, DummyBackendProxy *self) { folks_backend_store_enable_backend_finish(backendStore, res); self->m_eventLoop->quit(); self->m_eventLoop = 0; } void DummyBackendProxy::backendStoreLoaded(FolksBackendStore *backendStore, GAsyncResult *res, DummyBackendProxy *self) { GError *error = 0; folks_backend_store_load_backends_finish(backendStore, res, &error); checkError(error); self->m_backend = FOLKS_DUMMY_BACKEND(folks_backend_store_dup_backend_by_name(self->m_backendStore, "dummy")); Q_ASSERT(self->m_backend != 0); self->configurePrimaryStore(); } void DummyBackendProxy::checkError(GError *error) { if (error) { qWarning() << error->message; g_error_free(error); } Q_ASSERT(error == 0); } void DummyBackendProxy::mkpath(const QString &path) const { QDir dir; if (!dir.mkpath(path)) { qWarning() << "Fail to create path" << path; } Q_ASSERT(dir.mkpath(path)); } void DummyBackendProxy::initEnviroment() { Q_ASSERT(m_tmpDir.isValid()); QString tmpFullPath = QString("%1").arg(m_tmpDir.path()); qputenv("FOLKS_BACKENDS_ALLOWED", "dummy"); qputenv("FOLKS_PRIMARY_STORE", "dummy"); mkpath(tmpFullPath); qDebug() << "setting up in transient directory:" << tmpFullPath; // home qputenv("HOME", tmpFullPath.toUtf8().data()); // cache QString cacheDir = QString("%1/.cache/").arg(tmpFullPath); mkpath(cacheDir); qputenv("XDG_CACHE_HOME", cacheDir.toUtf8().data()); // config QString configDir = QString("%1/.config").arg(tmpFullPath); mkpath(configDir); qputenv("XDG_CONFIG_HOME", configDir.toUtf8().data()); // data QString dataDir = QString("%1/.local/share").arg(tmpFullPath); mkpath(dataDir); qputenv("XDG_DATA_HOME", dataDir.toUtf8().data()); mkpath(QString("%1/folks").arg(dataDir)); // runtime QString runtimeDir = QString("%1/run").arg(tmpFullPath); mkpath(runtimeDir); qputenv("XDG_RUNTIME_DIR", runtimeDir.toUtf8().data()); qputenv("XDG_DESKTOP_DIR", ""); qputenv("XDG_DOCUMENTS_DIR", ""); qputenv("XDG_DOWNLOAD_DIR", ""); qputenv("XDG_MUSIC_DIR", ""); qputenv("XDG_PICTURES_DIR", ""); qputenv("XDG_PUBLICSHARE_DIR", ""); qputenv("XDG_TEMPLATES_DIR", ""); qputenv("XDG_VIDEOS_DIR", ""); } bool DummyBackendProxy::registerObject() { QDBusConnection connection = QDBusConnection::sessionBus(); if (!connection.registerService(DUMMY_SERVICE_NAME)) { qWarning() << "Could not register service!" << DUMMY_SERVICE_NAME; return false; } m_adaptor = new DummyBackendAdaptor(connection, this); if (!connection.registerObject(DUMMY_OBJECT_PATH, this)) { qWarning() << "Could not register object!" << DUMMY_OBJECT_PATH; delete m_adaptor; m_adaptor = 0; } else { qDebug() << "Object registered:" << QString(DUMMY_OBJECT_PATH); } return (m_adaptor != 0); } void DummyBackendProxy::individualAggregatorPrepared(FolksIndividualAggregator *fia, GAsyncResult *res, DummyBackendProxy *self) { GError *error = 0; folks_individual_aggregator_prepare_finish(fia, res, &error); checkError(error); if (self->m_useDBus) { self->registerObject(); } self->m_isReady = true; Q_EMIT self->ready(); } void DummyBackendProxy::individualAggregatorAddedPersona(FolksIndividualAggregator *fia, GAsyncResult *res, DummyBackendProxy *self) { GError *error = 0; folks_individual_aggregator_add_persona_from_details_finish(fia, res, &error); checkError(error); self->m_eventLoop->quit(); self->m_eventLoop = 0; } void DummyBackendProxy::individualsChangedCb(FolksIndividualAggregator *individualAggregator, GeeMultiMap *changes, DummyBackendProxy *self) { Q_UNUSED(individualAggregator); GeeIterator *iter; GeeSet *removed = gee_multi_map_get_keys(changes); GeeCollection *added = gee_multi_map_get_values(changes); QStringList addedIds; iter = gee_iterable_iterator(GEE_ITERABLE(added)); while(gee_iterator_next(iter)) { FolksIndividual *individual = FOLKS_INDIVIDUAL(gee_iterator_get(iter)); if (individual) { galera::QIndividual *idv = new galera::QIndividual(individual, self->m_aggregator); self->m_contacts.insert(idv->id(), idv); addedIds << idv->id(); g_object_unref(individual); } } g_object_unref (iter); iter = gee_iterable_iterator(GEE_ITERABLE(removed)); while(gee_iterator_next(iter)) { FolksIndividual *individual = FOLKS_INDIVIDUAL(gee_iterator_get(iter)); if (individual) { QString id = QString::fromUtf8(folks_individual_get_id(individual)); if (!addedIds.contains(id) && self->m_contacts.contains(id)) { delete self->m_contacts.take(id); } g_object_unref(individual); } } g_object_unref (iter); g_object_unref(added); g_object_unref(removed); } DummyBackendAdaptor::DummyBackendAdaptor(const QDBusConnection &connection, DummyBackendProxy *parent) : QDBusAbstractAdaptor(parent), m_connection(connection), m_proxy(parent) { if (m_proxy->isReady()) { Q_EMIT ready(); } connect(m_proxy, SIGNAL(ready()), this, SIGNAL(ready())); } DummyBackendAdaptor::~DummyBackendAdaptor() { } bool DummyBackendAdaptor::isReady() { return m_proxy->isReady(); } bool DummyBackendAdaptor::ping() { return true; } void DummyBackendAdaptor::quit() { QMetaObject::invokeMethod(m_proxy, "shutdown", Qt::QueuedConnection); } void DummyBackendAdaptor::reset() { m_proxy->reset(); } QStringList DummyBackendAdaptor::listContacts() { return m_proxy->listContacts(); } QString DummyBackendAdaptor::createContact(const QString &vcard) { QtContacts::QContact contact = galera::VCardParser::vcardToContact(vcard); return m_proxy->createContact(contact); } QString DummyBackendAdaptor::updateContact(const QString &contactId, const QString &vcard) { QtContacts::QContact contact = galera::VCardParser::vcardToContact(vcard); return m_proxy->updateContact(contactId, contact); } void DummyBackendAdaptor::enableAutoLink(bool flag) { galera::QIndividual::enableAutoLink(flag); } address-book-service-0.1.1+14.04.20140408.3/tests/unittest/sort-clause-test.cpp0000644000015301777760000000754312321057324027240 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 #include #include #include #include "common/sort-clause.h" using namespace QtContacts; using namespace galera; class SortClauseTest : public QObject { Q_OBJECT private Q_SLOTS: void testSingleClause() { const QString strClause = QString("FIRST_NAME ASC"); SortClause clause(strClause); QList cClauseList; QContactSortOrder cClause; cClause.setCaseSensitivity(Qt::CaseInsensitive); cClause.setDetailType(QContactDetail::TypeName, QContactName::FieldFirstName); cClauseList << cClause; QVERIFY(clause.toContactSortOrder() == cClauseList); SortClause clause2(cClauseList); QCOMPARE(clause2.toString(), strClause); } void testComplexClause() { const QString strClause = QString("FIRST_NAME ASC, ORG_DEPARTMENT, ADDR_STREET DESC, URL"); const QString strClauseFull = QString("FIRST_NAME ASC, ORG_DEPARTMENT ASC, ADDR_STREET DESC, URL ASC"); SortClause clause(strClause); QList cClauseList; QContactSortOrder sortFirstName; sortFirstName.setDetailType(QContactDetail::TypeName, QContactName::FieldFirstName); sortFirstName.setDirection(Qt::AscendingOrder); sortFirstName.setCaseSensitivity(Qt::CaseInsensitive); cClauseList << sortFirstName; QContactSortOrder sortDepartment; sortDepartment.setDetailType(QContactDetail::TypeOrganization, QContactOrganization::FieldDepartment); sortDepartment.setDirection(Qt::AscendingOrder); sortDepartment.setCaseSensitivity(Qt::CaseInsensitive); cClauseList << sortDepartment; QContactSortOrder sortStreet; sortStreet.setDetailType(QContactDetail::TypeAddress, QContactAddress::FieldStreet); sortStreet.setDirection(Qt::DescendingOrder); sortStreet.setCaseSensitivity(Qt::CaseInsensitive); cClauseList << sortStreet; QContactSortOrder sortUrl; sortUrl.setDetailType(QContactDetail::TypeUrl, QContactUrl::FieldUrl); sortUrl.setDirection(Qt::AscendingOrder); sortUrl.setCaseSensitivity(Qt::CaseInsensitive); cClauseList << sortUrl; QVERIFY(clause.toContactSortOrder() == cClauseList); SortClause clause2(cClauseList); QCOMPARE(clause2.toString(), strClauseFull); } // should ignore the first field void testInvalidFieldNameClause() { SortClause clause("FIRSTNAME ASC, URL"); QCOMPARE(clause.toString(), QString("URL ASC")); QList cClauseList; QContactSortOrder sortUrl; sortUrl.setDetailType(QContactDetail::TypeUrl, QContactUrl::FieldUrl); sortUrl.setDirection(Qt::AscendingOrder); sortUrl.setCaseSensitivity(Qt::CaseInsensitive); cClauseList << sortUrl; QVERIFY(clause.toContactSortOrder() == cClauseList); } void testInvalidSintaxClause() { SortClause clause("FIRST_NAME ASC URL"); QCOMPARE(clause.toString(), QString("")); QCOMPARE(clause.toContactSortOrder().size(), 0); } }; QTEST_MAIN(SortClauseTest) #include "sort-clause-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/CMakeLists.txt0000644000015301777760000000614012321057324026046 0ustar pbusernogroup00000000000000macro(declare_test TESTNAME RUN_SERVER) add_executable(${TESTNAME} ${ARGN} ${TESTNAME}.cpp ) qt5_use_modules(${TESTNAME} Core Contacts Versit Test DBus) if(TEST_XML_OUTPUT) set(TEST_ARGS -p -xunitxml -p -o -p test_${testname}.xml) else() set(TEST_ARGS "") endif() target_link_libraries(${TESTNAME} address-book-service-lib folks-dummy ${CONTACTS_SERVICE_LIB} ${GLIB_LIBRARIES} ${GIO_LIBRARIES} ${FOLKS_LIBRARIES} ) if(${RUN_SERVER} STREQUAL "True") add_test(${TESTNAME} ${DBUS_RUNNER} --keep-env --task ${CMAKE_CURRENT_BINARY_DIR}/address-book-server-test --task ${CMAKE_CURRENT_BINARY_DIR}/${TESTNAME} ${TEST_ARGS} --wait-for=com.canonical.pim) else() add_test(${TESTNAME} ${TESTNAME}) endif() set(TEST_ENVIRONMENT "QT_QPA_PLATFORM=minimal\;FOLKS_BACKEND_PATH=${folks-dummy-backend_BINARY_DIR}/dummy.so\;FOLKS_BACKENDS_ALLOWED=dummy") set_tests_properties(${TESTNAME} PROPERTIES ENVIRONMENT ${TEST_ENVIRONMENT} TIMEOUT ${CTEST_TESTING_TIMEOUT}) endmacro() include_directories( ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${folks-dummy-lib_BINARY_DIR} ${GLIB_INCLUDE_DIRS} ${GIO_INCLUDE_DIRS} ${FOLKS_INCLUDE_DIRS} ${FOLKS_DUMMY_INCLUDE_DIRS} ) add_definitions(-DTEST_SUITE) if(NOT CTEST_TESTING_TIMEOUT) set(CTEST_TESTING_TIMEOUT 60) endif() declare_test(clause-test False) declare_test(sort-clause-test False) declare_test(fetch-hint-test False) declare_test(vcardparser-test False) set(DUMMY_BACKEND_SRC scoped-loop.h scoped-loop.cpp dummy-backend.cpp dummy-backend.h) declare_test(contactmap-test False ${DUMMY_BACKEND_SRC}) if(DBUS_RUNNER) set(BASE_CLIENT_TEST_SRC dummy-backend-defs.h base-client-test.h base-client-test.cpp) declare_test(addressbook-test True ${BASE_CLIENT_TEST_SRC}) declare_test(service-life-cycle-test True ${BASE_CLIENT_TEST_SRC}) declare_test(readonly-prop-test True ${BASE_CLIENT_TEST_SRC}) declare_test(contact-link-test True ${BASE_CLIENT_TEST_SRC}) declare_test(qcontacts-test True ${BASE_CLIENT_TEST_SRC}) elseif() message(STATUS "DBus test runner not found. Some tests will be disabled") endif() # server code add_executable(address-book-server-test scoped-loop.h scoped-loop.cpp dummy-backend.h dummy-backend.cpp addressbook-server.cpp ) qt5_use_modules(address-book-server-test Core Contacts Versit DBus) target_link_libraries(address-book-server-test address-book-service-lib folks-dummy ${CONTACTS_SERVICE_LIB} ${GLIB_LIBRARIES} ${GIO_LIBRARIES} ${FOLKS_LIBRARIES} ) address-book-service-0.1.1+14.04.20140408.3/tests/unittest/addressbook-test.cpp0000644000015301777760000003203312321057324027267 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "base-client-test.h" #include "common/source.h" #include "common/dbus-service-defs.h" #include "common/vcard-parser.h" #include #include #include #include #include class AddressBookTest : public BaseClientTest { Q_OBJECT private: QString m_basicVcard; QString m_resultBasicVcard; QtContacts::QContact basicContactWithId(const QString &id) { QString newVcard = m_resultBasicVcard.arg(id); return galera::VCardParser::vcardToContact(newVcard); } void compareContact(const QtContacts::QContact &contact, const QtContacts::QContact &other) { // id QCOMPARE(contact.id(), other.id()); // name QCOMPARE(contact.detail(QtContacts::QContactDetail::TypeName), other.detail(QtContacts::QContactDetail::TypeName)); // phone - this is necessary because: // 1 ) the QContactDetail::FieldDetailUri can change based on the detail order // 2 ) the phone number can be returned in different order QList phones = contact.details(QtContacts::QContactDetail::TypePhoneNumber); QList otherPhones = other.details(QtContacts::QContactDetail::TypePhoneNumber); QCOMPARE(phones.size(), otherPhones.size()); for(int i=0; i < phones.size(); i++) { QtContacts::QContactDetail phone = phones[i]; bool found = false; for(int x=0; x < otherPhones.size(); x++) { QtContacts::QContactDetail otherPhone = otherPhones[x]; if (phone.value(QtContacts::QContactPhoneNumber::FieldNumber) == otherPhone.value(QtContacts::QContactPhoneNumber::FieldNumber)) { found = true; QList phoneTypes = phone.value(QtContacts::QContactPhoneNumber::FieldSubTypes).value< QList >(); QList otherPhoneTypes = otherPhone.value(QtContacts::QContactPhoneNumber::FieldSubTypes).value< QList >(); QCOMPARE(phoneTypes, otherPhoneTypes); QCOMPARE(phone.value(QtContacts::QContactPhoneNumber::FieldContext), otherPhone.value(QtContacts::QContactPhoneNumber::FieldContext)); break; } } QVERIFY2(found, "Phone number is not equal"); } // email same as phone number QList emails = contact.details(QtContacts::QContactDetail::TypeEmailAddress); QList otherEmails = other.details(QtContacts::QContactDetail::TypeEmailAddress); QCOMPARE(emails.size(), otherEmails.size()); for(int i=0; i < emails.size(); i++) { QtContacts::QContactDetail email = emails[i]; bool found = false; for(int x=0; x < otherEmails.size(); x++) { QtContacts::QContactDetail otherEmail = otherEmails[x]; if (email.value(QtContacts::QContactEmailAddress::FieldEmailAddress) == otherEmail.value(QtContacts::QContactEmailAddress::FieldEmailAddress)) { found = true; QCOMPARE(email.value(QtContacts::QContactEmailAddress::FieldContext), otherEmail.value(QtContacts::QContactEmailAddress::FieldContext)); break; } } QVERIFY2(found, "Email is not equal"); } } private Q_SLOTS: void initTestCase() { BaseClientTest::initTestCase(); m_basicVcard = QStringLiteral("BEGIN:VCARD\n" "VERSION:3.0\n" "N:Tal;Fulano_;de;;\n" "EMAIL:fulano_@ubuntu.com\n" "TEL;PID=1.1;TYPE=ISDN:33331410\n" "TEL;PID=1.2;TYPE=CELL:8888888\n" "END:VCARD"); m_resultBasicVcard = QStringLiteral("BEGIN:VCARD\r\n" "VERSION:3.0\r\n" "UID:%1\r\n" "CLIENTPIDMAP:1;dummy:dummy-store:%2\r\n" "N;PID=1.1:Tal;Fulano_;de;;\r\n" "FN;PID=1.1:Fulano_ Tal\r\n" "X-QTPROJECT-FAVORITE;PID=1.1:false;0\r\n" "EMAIL;PID=1.1:fulano_@ubuntu.com\r\n" "TEL;PID=1.1;TYPE=ISDN:33331410\r\n" "TEL;PID=1.2;TYPE=CELL:8888888\r\n" "END:VCARD\r\n"); } void testSortFields() { QStringList defaultSortFields; defaultSortFields << "ADDR_COUNTRY" << "ADDR_LOCALITY" << "ADDR_POSTCODE" << "ADDR_POST_OFFICE_BOX" << "ADDR_REGION" << "ADDR_STREET" << "BIRTHDAY" << "EMAIL" << "FIRST_NAME" << "FULL_NAME" << "IM_PROTOCOL" << "IM_URI" << "LAST_NAME" << "MIDLE_NAME" << "NAME_PREFIX" << "NAME_SUFFIX" << "NICKNAME" << "ORG_DEPARTMENT" << "ORG_LOCATION" << "ORG_NAME" << "ORG_ROLE" << "ORG_TITLE" << "PHONE" << "PHOTO" << "URL"; QDBusReply reply = m_serverIface->call("sortFields"); QCOMPARE(reply.value(), defaultSortFields); } void testSource() { QDBusReply reply = m_serverIface->call("source"); QVERIFY(reply.isValid()); QCOMPARE(reply.value().id(), QStringLiteral("dummy-store")); } void testAvailableSources() { QDBusReply > reply = m_serverIface->call("availableSources"); galera::SourceList list = reply.value(); QCOMPARE(list.count(), 1); galera::Source src = list[0]; QCOMPARE(src.id(), QStringLiteral("dummy-store")); QCOMPARE(src.displayLabel(), QStringLiteral("Dummy personas")); QCOMPARE(src.isReadOnly(), false); } void testCreateContact() { // spy 'contactsAdded' signal QSignalSpy addedContactSpy(m_serverIface, SIGNAL(contactsAdded(QStringList))); // call create contact QDBusReply reply = m_serverIface->call("createContact", m_basicVcard, "dummy-store"); // check if the returned contact is valid QString vcard = reply.value(); QVERIFY(!vcard.isEmpty()); // check if the cotact was created with the correct fields QtContacts::QContact newContact = galera::VCardParser::vcardToContact(vcard); QDBusReply reply2 = m_dummyIface->call("listContacts"); QCOMPARE(reply2.value().count(), 1); QList contactsCreated = galera::VCardParser::vcardToContactSync(reply2.value()); QCOMPARE(contactsCreated.count(), 1); compareContact(contactsCreated[0], newContact); // check if the signal "contactAdded" was fired QTRY_COMPARE(addedContactSpy.count(), 1); QList args = addedContactSpy.takeFirst(); QCOMPARE(args.count(), 1); QStringList ids = args[0].toStringList(); QCOMPARE(ids[0], newContact.detail().guid()); } void testDuplicateContact() { // spy 'contactsAdded' signal QSignalSpy addedContactSpy(m_serverIface, SIGNAL(contactsAdded(QStringList))); // call create contact first QDBusReply reply = m_serverIface->call("createContact", m_basicVcard, "dummy-store"); // wait for folks to emit the signal QTRY_COMPARE(addedContactSpy.count(), 1); // user returned id to fill the new vcard QString newVcard = reply.value(); // try create a contact with the same id QDBusReply reply2 = m_serverIface->call("createContact", newVcard, "dummy-store"); // contactsAdded should be fired only once QTRY_COMPARE(addedContactSpy.count(), 1); // result should be null QVERIFY(reply2.value().isEmpty()); } void testCreateInvalidContact() { // spy 'contactsAdded' signal QSignalSpy addedContactSpy(m_serverIface, SIGNAL(contactsAdded(QStringList))); // call create contact with a invalid vcard string QDBusReply reply = m_serverIface->call("createContact", "INVALID VCARD", "dummy-store"); // wait for folks to emit the signal QTest::qWait(500); QVERIFY(reply.value().isEmpty()); QCOMPARE(addedContactSpy.count(), 0); } void testRemoveContact() { // create a basic contact QSignalSpy addedContactSpy(m_serverIface, SIGNAL(contactsAdded(QStringList))); QDBusReply replyAdd = m_serverIface->call("createContact", m_basicVcard, "dummy-store"); QString vcard = replyAdd.value(); // wait for added signal QTRY_COMPARE(addedContactSpy.count(), 1); // spy 'contactsRemoved' signal QSignalSpy removedContactSpy(m_serverIface, SIGNAL(contactsRemoved(QStringList))); // try remove the contact created QContact newContact = galera::VCardParser::vcardToContact(vcard); QString newContactId = newContact.detail().guid(); QDBusReply replyRemove = m_serverIface->call("removeContacts", QStringList() << newContactId); QCOMPARE(replyRemove.value(), 1); // check if the 'contactsRemoved' signal was fired with the correct args QTRY_COMPARE(removedContactSpy.count(), 1); QList args = removedContactSpy.takeFirst(); QCOMPARE(args.count(), 1); QStringList ids = args[0].toStringList(); QCOMPARE(ids[0], newContactId); // check if the contact was removed from the backend QDBusReply replyList = m_dummyIface->call("listContacts"); QCOMPARE(replyList.value().count(), 0); } void testUpdateContact() { // create a basic contact QDBusReply replyAdd = m_serverIface->call("createContact", m_basicVcard, "dummy-store"); QString vcard = replyAdd.value(); QContact newContact = galera::VCardParser::vcardToContact(vcard); QString newContactId = newContact.detail().guid(); // update the contact phone number vcard = vcard.replace("8888888", "0000000"); QtContacts::QContact contactUpdated = galera::VCardParser::vcardToContact(vcard); // spy 'contactsUpdated' signal QSignalSpy updateContactSpy(m_serverIface, SIGNAL(contactsUpdated(QStringList))); QDBusReply replyUpdate = m_serverIface->call("updateContacts", QStringList() << vcard); QStringList result = replyUpdate.value(); QCOMPARE(result.size(), 1); // check if contact returned by update function contains the new data QList contacts = galera::VCardParser::vcardToContactSync(result); QtContacts::QContact contactUpdatedResult = contacts[0]; compareContact(contactUpdatedResult, contactUpdated); // check if the 'contactsUpdated' signal was fired with the correct args QTRY_COMPARE(updateContactSpy.count(), 1); QList args = updateContactSpy.takeFirst(); QCOMPARE(args.count(), 1); QStringList ids = args[0].toStringList(); QCOMPARE(ids[0], newContactId); // check if the contact was updated into the backend QDBusReply replyList = m_dummyIface->call("listContacts"); result = replyList.value(); QCOMPARE(result.count(), 1); contacts = galera::VCardParser::vcardToContactSync(result); contactUpdatedResult = contacts[0]; compareContact(contactUpdatedResult, contactUpdated); } }; QTEST_MAIN(AddressBookTest) #include "addressbook-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/base-client-test.cpp0000644000015301777760000000401212321057324027151 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "config.h" #include "base-client-test.h" #include "dummy-backend-defs.h" #include "common/dbus-service-defs.h" #include "common/source.h" #include "lib/qindividual.h" #include #include void BaseClientTest::initTestCase() { galera::Source::registerMetaType(); m_serverIface = new QDBusInterface(CPIM_SERVICE_NAME, CPIM_ADDRESSBOOK_OBJECT_PATH, CPIM_ADDRESSBOOK_IFACE_NAME); QVERIFY(!m_serverIface->lastError().isValid()); // wait for service to be ready QTRY_COMPARE_WITH_TIMEOUT(m_serverIface->property("isReady").toBool(), true, 10000); m_dummyIface = new QDBusInterface(DUMMY_SERVICE_NAME, DUMMY_OBJECT_PATH, DUMMY_IFACE_NAME); QVERIFY(!m_dummyIface->lastError().isValid()); // wait for service to be ready QTRY_COMPARE_WITH_TIMEOUT(m_dummyIface->property("isReady").toBool(), true, 10000); } void BaseClientTest::init() { } void BaseClientTest::cleanup() { m_dummyIface->call("reset"); QDBusReply reply = m_dummyIface->call("listContacts"); QCOMPARE(reply.value().count(), 0); } void BaseClientTest::cleanupTestCase() { m_dummyIface->call("quit"); delete m_dummyIface; delete m_serverIface; } address-book-service-0.1.1+14.04.20140408.3/tests/unittest/contact-link-test.cpp0000644000015301777760000000616612321057324027365 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "base-client-test.h" #include "lib/qindividual.h" #include "common/source.h" #include "common/dbus-service-defs.h" #include "common/vcard-parser.h" #include #include #include #include #include class ContactLinkTest : public BaseClientTest { Q_OBJECT private: QString m_vcard; private Q_SLOTS: void initTestCase() { BaseClientTest::initTestCase(); m_vcard = QStringLiteral("BEGIN:VCARD\n" "VERSION:3.0\n" "N:tal;fulano_;de;;\n" "EMAIL:email@ubuntu.com\n" "TEL;PID=1.1;TYPE=ISDN:33331410\n" "END:VCARD"); } void testCreateContactWithSameEmail() { // call create contact QDBusReply reply = m_serverIface->call("createContact", m_vcard, "dummy-store"); // check if the returned id is valid QString contactAId = reply.value(); QVERIFY(!contactAId.isEmpty()); QString vcardB = m_vcard.replace("fulano", "contact"); reply = m_serverIface->call("createContact", vcardB, "dummy-store"); // check if the returned id is valid QString contactBId = reply.value(); QVERIFY(!contactBId.isEmpty()); QVERIFY(contactAId != contactBId); } void testAppendOtherContactEmail() { // call create contact QDBusReply reply = m_serverIface->call("createContact", m_vcard, "dummy-store"); // check if the returned id is valid QString contactAId = reply.value(); QVERIFY(!contactAId.isEmpty()); // add a contact with diff email QString vcardB = m_vcard.replace("fulano", "contact").replace("email","email2"); reply = m_serverIface->call("createContact", vcardB, "dummy-store"); // check if the returned id is valid QString contactBId = reply.value(); QVERIFY(!contactBId.isEmpty()); // udate contactB with same email as contactA vcardB = m_vcard.replace("fulano", "contact"); reply = m_serverIface->call("createContact", vcardB, "dummy-store"); // check if the returned id is valid contactBId = reply.value(); QVERIFY(!contactBId.isEmpty()); // check if id still different QVERIFY(contactAId != contactBId); } }; QTEST_MAIN(ContactLinkTest) #include "contact-link-test.moc" address-book-service-0.1.1+14.04.20140408.3/tests/unittest/dummy-backend-defs.h0000644000015301777760000000170512321057324027120 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __DUMMY_BACKEND_DEFS_H__ #define __DUMMY_BACKEND_DEFS_H__ #define DUMMY_SERVICE_NAME "com.canonical.test.folks" #define DUMMY_IFACE_NAME "com.canonical.test.folks.Dummy" #define DUMMY_OBJECT_PATH "/com/canonical/test/folks/Dummy" #endif address-book-service-0.1.1+14.04.20140408.3/data/0000755000015301777760000000000012321057642021200 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/data/CMakeLists.txt0000644000015301777760000000050012321057324023730 0ustar pbusernogroup00000000000000configure_file("${CMAKE_CURRENT_SOURCE_DIR}/com.canonical.pim.service.in" "${CMAKE_CURRENT_BINARY_DIR}/com.canonical.pim.service" IMMEDIATE @ONLY ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/com.canonical.pim.service DESTINATION ${CMAKE_INSTALL_FULL_DATAROOTDIR}/dbus-1/services/ ) address-book-service-0.1.1+14.04.20140408.3/data/com.canonical.pim.service.in0000644000015301777760000000014112321057324026450 0ustar pbusernogroup00000000000000[D-BUS Service] Name=com.canonical.pim Exec=@CMAKE_INSTALL_FULL_LIBEXECDIR@/address-book-service address-book-service-0.1.1+14.04.20140408.3/config.h.in0000644000015301777760000000016712321057334022314 0ustar pbusernogroup00000000000000#ifndef __GALERA_CONFIG_H__ #define __GALERA_CONFIG_H__ #define QT_PLUGINS_BINARY_DIR "@CMAKE_BINARY_DIR@" #endif address-book-service-0.1.1+14.04.20140408.3/lib/0000755000015301777760000000000012321057642021035 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/lib/gee-utils.h0000644000015301777760000000734512321057324023112 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_GEE_UTILS_H__ #define __GALERA_GEE_UTILS_H__ #include #include #include #include static guint _folks_abstract_field_details_hash_data_func (gconstpointer v, gpointer self) { const FolksAbstractFieldDetails *constDetails = static_cast(v); return folks_abstract_field_details_hash_static (const_cast(constDetails)); } static int _folks_abstract_field_details_equal_data_func (gconstpointer a, gconstpointer b, gpointer self) { const FolksAbstractFieldDetails *constDetailsA = static_cast(a); const FolksAbstractFieldDetails *constDetailsB = static_cast(b); return folks_abstract_field_details_equal_static (const_cast(constDetailsA), const_cast(constDetailsB)); } #define SET_AFD_NEW() \ GEE_SET(gee_hash_set_new(FOLKS_TYPE_ABSTRACT_FIELD_DETAILS, \ (GBoxedCopyFunc) g_object_ref, g_object_unref, \ _folks_abstract_field_details_hash_data_func, \ NULL, \ NULL, \ _folks_abstract_field_details_equal_data_func, \ NULL, \ NULL)) #define SET_PERSONA_NEW() \ GEE_SET(gee_hash_set_new(FOLKS_TYPE_PERSONA, \ (GBoxedCopyFunc) g_object_ref, g_object_unref, \ NULL, \ NULL, \ NULL, \ NULL, \ NULL, \ NULL)) #define GEE_MULTI_MAP_AFD_NEW(FOLKS_TYPE) \ GEE_MULTI_MAP(gee_hash_multi_map_new(G_TYPE_STRING,\ (GBoxedCopyFunc) g_strdup, g_free, \ FOLKS_TYPE, \ (GBoxedCopyFunc)g_object_ref, g_object_unref, \ NULL, \ NULL, \ NULL, \ NULL, \ NULL, \ NULL, \ _folks_abstract_field_details_hash_data_func, \ NULL, \ NULL, \ _folks_abstract_field_details_equal_data_func, \ NULL, \ NULL)) class GeeUtils { public: static GValue* gValueSliceNew(GType type); static void gValueSliceFree(GValue *value); static void personaDetailsInsert(GHashTable *details, FolksPersonaDetail key, gpointer value); static GValue* asvSetStrNew(QMultiMap providerUidMap); }; // class #endif address-book-service-0.1.1+14.04.20140408.3/lib/view.cpp0000644000015301777760000001675412321057324022525 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "view.h" #include "view-adaptor.h" #include "contacts-map.h" #include "qindividual.h" #include "common/vcard-parser.h" #include "common/filter.h" #include "common/fetch-hint.h" #include "common/dbus-service-defs.h" #include #include #include #include using namespace QtContacts; using namespace QtVersit; namespace galera { class ContactLessThan { public: ContactLessThan(const SortClause &sortClause) : m_sortClause(sortClause) { } bool operator()(galera::ContactEntry *entryA, galera::ContactEntry *entryB) { return QContactManagerEngine::compareContact(entryA->individual()->contact(), entryB->individual()->contact(), m_sortClause.toContactSortOrder()) < 0; } private: SortClause m_sortClause; }; class FilterThread: public QThread { public: FilterThread(QString filter, QString sort, ContactsMap *allContacts) : m_filter(filter), m_sortClause(sort), m_allContacts(allContacts), m_stopped(false) { } QList result() const { if (isRunning()) { return QList(); } else { return m_contacts; } } bool appendContact(ContactEntry *entry) { if (checkContact(entry)) { //TODO: append sorted m_contacts << entry; return true; } return false; } bool removeContact(ContactEntry *entry) { return m_contacts.removeAll(entry); } void chageSort(SortClause clause) { m_sortClause = clause; ContactLessThan lessThan(m_sortClause); qSort(m_contacts.begin(), m_contacts.end(), lessThan); } void stop() { m_stoppedLock.lockForWrite(); m_stopped = true; m_stoppedLock.unlock(); } protected: void run() { m_allContacts->lock(); // filter contacts if necessary if (m_filter.isValid()) { Q_FOREACH(ContactEntry *entry, m_allContacts->values()) { m_stoppedLock.lockForRead(); if (m_stopped) { m_stoppedLock.unlock(); m_allContacts->unlock(); return; } m_stoppedLock.unlock(); if (checkContact(entry)) { m_contacts << entry; } } } else { m_contacts = m_allContacts->values(); } chageSort(m_sortClause); m_allContacts->unlock(); } private: Filter m_filter; SortClause m_sortClause; ContactsMap *m_allContacts; QList m_contacts; bool m_stopped; QReadWriteLock m_stoppedLock; bool checkContact(ContactEntry *entry) { return m_filter.test(entry->individual()->contact()); } }; View::View(const QString &clause, const QString &sort, const QStringList &sources, ContactsMap *allContacts, QObject *parent) : QObject(parent), m_sources(sources), m_filterThread(new FilterThread(clause, sort, allContacts)), m_adaptor(0) { m_filterThread->start(); connect(m_filterThread, SIGNAL(finished()), SIGNAL(countChanged())); } View::~View() { close(); } void View::close() { if (m_adaptor) { Q_EMIT m_adaptor->contactsRemoved(0, m_filterThread->result().count()); Q_EMIT closed(); QDBusConnection conn = QDBusConnection::sessionBus(); unregisterObject(conn); m_adaptor->deleteLater(); m_adaptor = 0; } if (m_filterThread) { if (m_filterThread->isRunning()) { m_filterThread->stop(); m_filterThread->wait(); } delete m_filterThread; m_filterThread = 0; } } QString View::contactDetails(const QStringList &fields, const QString &id) { Q_ASSERT(FALSE); return QString(); } QStringList View::contactsDetails(const QStringList &fields, int startIndex, int pageSize, const QDBusMessage &message) { while(!m_filterThread->wait(300)) { QCoreApplication::processEvents(); } QList entries = m_filterThread->result(); if (startIndex < 0) { startIndex = 0; } if ((pageSize < 0) || ((startIndex + pageSize) >= entries.count())) { pageSize = entries.count() - startIndex; } QList contacts; for(int i = startIndex, iMax = (startIndex + pageSize); i < iMax; i++) { contacts << entries[i]->individual()->copy(FetchHint::parseFieldNames(fields)); } VCardParser *parser = new VCardParser(this); parser->setProperty("DATA", QVariant::fromValue(message)); connect(parser, &VCardParser::vcardParsed, this, &View::onVCardParsed); parser->contactToVcard(contacts); return QStringList(); } void View::onVCardParsed(const QStringList &vcards) { QObject *sender = QObject::sender(); QDBusMessage reply = sender->property("DATA").value().createReply(vcards); QDBusConnection::sessionBus().send(reply); sender->deleteLater(); } int View::count() { m_filterThread->wait(); return m_filterThread->result().count(); } void View::sort(const QString &field) { m_filterThread->chageSort(SortClause(field)); } QString View::objectPath() { return CPIM_ADDRESSBOOK_VIEW_OBJECT_PATH; } QString View::dynamicObjectPath() const { return objectPath() + "/" + QString::number((long)this); } bool View::registerObject(QDBusConnection &connection) { if (!m_adaptor) { m_adaptor = new ViewAdaptor(connection, this); if (!connection.registerObject(dynamicObjectPath(), this)) { qWarning() << "Could not register object!" << objectPath(); delete m_adaptor; m_adaptor = 0; } else { qDebug() << "Object registered:" << objectPath(); connect(this, SIGNAL(countChanged(int)), m_adaptor, SIGNAL(countChanged(int))); } } return (m_adaptor != 0); } void View::unregisterObject(QDBusConnection &connection) { if (m_adaptor) { qDebug() << "Object UN-registered:" << objectPath(); connection.unregisterObject(dynamicObjectPath()); } } bool View::appendContact(ContactEntry *entry) { if (m_filterThread->appendContact(entry)) { Q_EMIT countChanged(m_filterThread->result().count()); return true; } return false; } bool View::removeContact(ContactEntry *entry) { if (m_filterThread->removeContact(entry)) { Q_EMIT countChanged(m_filterThread->result().count()); return true; } return false; } QObject *View::adaptor() const { return m_adaptor; } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/view.h0000644000015301777760000000416512321057324022163 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_VIEW_H__ #define __GALERA_VIEW_H__ #include #include #include #include #include #include namespace galera { class ContactEntry; class ViewAdaptor; class ContactsMap; class FilterThread; class SortContact; class View : public QObject { Q_OBJECT Q_PROPERTY(int count READ count NOTIFY countChanged) public: View(const QString &clause, const QString &sort, const QStringList &sources, ContactsMap *allContacts, QObject *parent); ~View(); static QString objectPath(); QString dynamicObjectPath() const; QObject *adaptor() const; bool registerObject(QDBusConnection &connection); void unregisterObject(QDBusConnection &connection); // contacts bool appendContact(ContactEntry *entry); bool removeContact(ContactEntry *entry); // Adaptor QString contactDetails(const QStringList &fields, const QString &id); int count(); void sort(const QString &field); void close(); public Q_SLOTS: QStringList contactsDetails(const QStringList &fields, int startIndex, int pageSize, const QDBusMessage &message); private Q_SLOTS: void onVCardParsed(const QStringList &vcards); Q_SIGNALS: void closed(); void countChanged(int count=0); private: QStringList m_sources; FilterThread *m_filterThread; ViewAdaptor *m_adaptor; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/contacts-map.cpp0000644000015301777760000000632312321057324024133 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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-map.h" #include "qindividual.h" #include namespace galera { //ContactInfo ContactEntry::ContactEntry(QIndividual *individual) : m_individual(individual) { Q_ASSERT(individual); } ContactEntry::~ContactEntry() { delete m_individual; } QIndividual *ContactEntry::individual() const { return m_individual; } //ContactMap ContactsMap::ContactsMap() { } ContactsMap::~ContactsMap() { clear(); } ContactEntry *ContactsMap::value(const QString &id) const { return m_idToEntry[id]; } ContactEntry *ContactsMap::take(FolksIndividual *individual) { QString contactId = QString::fromUtf8(folks_individual_get_id(individual)); return take(contactId); } ContactEntry *ContactsMap::take(const QString &id) { QMutexLocker locker(&m_mutex); return m_idToEntry.take(id); } void ContactsMap::remove(const QString &id) { QMutexLocker locker(&m_mutex); ContactEntry *entry = m_idToEntry.value(id,0); if (entry) { m_idToEntry.remove(id); delete entry; } } void ContactsMap::insert(ContactEntry *entry) { QMutexLocker locker(&m_mutex); FolksIndividual *fIndividual = entry->individual()->individual(); if (fIndividual) { m_idToEntry.insert(folks_individual_get_id(fIndividual), entry); } } int ContactsMap::size() const { return m_idToEntry.size(); } void ContactsMap::clear() { QMutexLocker locker(&m_mutex); QList entries = m_idToEntry.values(); m_idToEntry.clear(); qDeleteAll(entries); } void ContactsMap::lock() { m_mutex.lock(); } void ContactsMap::unlock() { m_mutex.unlock(); } QList ContactsMap::values() const { return m_idToEntry.values(); } ContactEntry *ContactsMap::valueFromVCard(const QString &vcard) const { //GET UID int startIndex = vcard.indexOf("UID:"); if (startIndex) { startIndex += 4; // "UID:" int endIndex = vcard.indexOf("\r\n", startIndex); QString id = vcard.mid(startIndex, endIndex - startIndex); return m_idToEntry[id]; } return 0; } bool ContactsMap::contains(FolksIndividual *individual) const { QString contactId = QString::fromUtf8(folks_individual_get_id(individual)); return contains(contactId); } bool ContactsMap::contains(const QString &id) const { return m_idToEntry.contains(id); } ContactEntry *ContactsMap::value(FolksIndividual *individual) const { QString contactId = QString::fromUtf8(folks_individual_get_id(individual)); return m_idToEntry.value(contactId, 0); } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/contacts-utils.h0000644000015301777760000000253212321057324024161 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_CONTACTS_UTILS_H__ #define __GALERA_CONTACTS_UTILS_H__ #include #include #include namespace galera { class ContactsUtils { public: static QByteArray serializeIndividual(FolksIndividual *individual); private: static QList parsePersona(int index, FolksPersona *persona); static QtVersit::QVersitProperty createProperty(int sourceIndex, int index, const QString &name, const QString &value); }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/update-contact-request.h0000644000015301777760000001000512321057334025601 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_UPDATE_CONTACT_REQUEST_H__ #define __GALERA_UPDATE_CONTACT_REQUEST_H__ #include #include #include #include #include #include #include namespace galera { class QIndividual; class UpdateContactRequest : public QObject { Q_OBJECT public: UpdateContactRequest(QtContacts::QContact newContact, QIndividual *parent, QObject *listener, const char *slot); ~UpdateContactRequest(); void start(); void wait(); void deatach(); void notifyError(const QString &errorMessage); Q_SIGNALS: void done(const QString &errorMessage); private: QIndividual *m_parent; QObject *m_object; FolksPersona *m_currentPersona; QEventLoop *m_eventLoop; QList m_personas; QtContacts::QContact m_originalContact; QtContacts::QContact m_newContact; int m_currentDetailType; QMetaMethod m_slot; int m_currentPersonaIndex; void invokeSlot(const QString &errorMessage = QString()); static bool isEqual(QList listA, const QtContacts::QContactDetail &prefA, QList listB, const QtContacts::QContactDetail &prefB); static bool isEqual(QList listA, QList listB); static bool isEqual(const QtContacts::QContactDetail &detailA, const QtContacts::QContactDetail &detailB); static bool checkPersona(QtContacts::QContactDetail &det, int persona); static QList detailsFromPersona(const QtContacts::QContact &contact, QtContacts::QContactDetail::DetailType type, int persona, bool includeEmptyPersona, QtContacts::QContactDetail *pref); QList originalDetailsFromPersona(QtContacts::QContactDetail::DetailType type, int persona, QtContacts::QContactDetail *pref) const; QList detailsFromPersona(QtContacts::QContactDetail::DetailType type, int persona, QtContacts::QContactDetail *pref) const; void updatePersona(); void updateAddress(); void updateAvatar(); void updateBirthday(); void updateFullName(); void updateEmail(); void updateName(); void updateNickname(); void updateNote(); void updateOnlineAccount(); void updateOrganization(); void updatePhone(); void updateUrl(); void updateFavorite(); QString callDetailChangeFinish(QtContacts::QContactDetail::DetailType detailType, FolksPersona *persona, GAsyncResult *result); static void updateDetailsDone(GObject *detail, GAsyncResult *result, gpointer userdata); }; } #endif address-book-service-0.1.1+14.04.20140408.3/lib/view-adaptor.h0000644000015301777760000000616012321057324023610 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_VIEW_ADAPTOR_H__ #define __GALERA_VIEW_ADAPTOR_H__ #include #include #include #include #include "common/dbus-service-defs.h" namespace galera { class View; class ViewAdaptor: public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", CPIM_ADDRESSBOOK_VIEW_IFACE_NAME) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") Q_PROPERTY(int count READ count NOTIFY countChanged) public: ViewAdaptor(const QDBusConnection &connection, View *parent); virtual ~ViewAdaptor(); public Q_SLOTS: QString contactDetails(const QStringList &fields, const QString &id); QStringList contactsDetails(const QStringList &fields, int startIndex, int pageSize, const QDBusMessage &message); int count(); void sort(const QString &field); void close(); Q_SIGNALS: void contactsAdded(int pos, int lenght); void contactsRemoved(int pos, int lenght); void contactsUpdated(int pos, int lenght); void countChanged(int count); private: View *m_view; QDBusConnection m_connection; }; } // namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/addressbook-adaptor.cpp0000644000015301777760000001017112321057324025466 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "addressbook-adaptor.h" #include "addressbook.h" #include "view.h" namespace galera { AddressBookAdaptor::AddressBookAdaptor(const QDBusConnection &connection, AddressBook *parent) : QDBusAbstractAdaptor(parent), m_addressBook(parent), m_connection(connection) { setAutoRelaySignals(true); } AddressBookAdaptor::~AddressBookAdaptor() { // destructor } SourceList AddressBookAdaptor::availableSources(const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_addressBook, "availableSources", Qt::QueuedConnection, Q_ARG(const QDBusMessage&, message)); return SourceList(); } Source AddressBookAdaptor::source(const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_addressBook, "source", Qt::QueuedConnection, Q_ARG(const QDBusMessage&, message)); return Source(); } Source AddressBookAdaptor::createSource(const QString &sourceName, const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_addressBook, "createSource", Qt::QueuedConnection, Q_ARG(const QString&, sourceName), Q_ARG(const QDBusMessage&, message)); return Source(); } QString AddressBookAdaptor::createContact(const QString &contact, const QString &source, const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_addressBook, "createContact", Qt::QueuedConnection, Q_ARG(const QString&, contact), Q_ARG(const QString&, source), Q_ARG(const QDBusMessage&, message)); return QString(); } QDBusObjectPath AddressBookAdaptor::query(const QString &clause, const QString &sort, const QStringList &sources) { View *v = m_addressBook->query(clause, sort, sources); v->registerObject(m_connection); return QDBusObjectPath(v->dynamicObjectPath()); } int AddressBookAdaptor::removeContacts(const QStringList &contactIds, const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_addressBook, "removeContacts", Qt::QueuedConnection, Q_ARG(const QStringList&, contactIds), Q_ARG(const QDBusMessage&, message)); return 0; } QStringList AddressBookAdaptor::sortFields() { return m_addressBook->sortFields(); } QString AddressBookAdaptor::linkContacts(const QStringList &contactsIds) { return m_addressBook->linkContacts(contactsIds); } bool AddressBookAdaptor::unlinkContacts(const QString &parentId, const QStringList &contactsIds) { return m_addressBook->unlinkContacts(parentId, contactsIds); } QStringList AddressBookAdaptor::updateContacts(const QStringList &contacts, const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_addressBook, "updateContacts", Qt::QueuedConnection, Q_ARG(const QStringList&, contacts), Q_ARG(const QDBusMessage&, message)); return QStringList(); } bool AddressBookAdaptor::isReady() { return m_addressBook->isReady(); } bool AddressBookAdaptor::ping() { return true; } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/dirtycontact-notify.cpp0000644000015301777760000000554412321057324025563 0ustar pbusernogroup00000000000000/* * Copyright 2014 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ //this timeout represents how long the server will wait for changes on the contact before notify the client #define NOTIFY_CONTACTS_TIMEOUT 500 #include "dirtycontact-notify.h" #include "addressbook-adaptor.h" namespace galera { DirtyContactsNotify::DirtyContactsNotify(AddressBookAdaptor *adaptor, QObject *parent) : QObject(parent), m_adaptor(adaptor) { m_timer.setInterval(NOTIFY_CONTACTS_TIMEOUT); m_timer.setSingleShot(true); connect(&m_timer, SIGNAL(timeout()), SLOT(emitSignals())); } void DirtyContactsNotify::insertAddedContacts(QSet ids) { if (!m_adaptor->isReady()) { return; } // if the contact was removed before ignore the removal signal, and send a update signal QSet addedIds = ids; Q_FOREACH(QString added, ids) { if (m_contactsRemoved.contains(added)) { m_contactsRemoved.remove(added); addedIds.remove(added); m_contactsChanged.insert(added); } } m_contactsAdded += addedIds; m_timer.start(); } void DirtyContactsNotify::insertRemovedContacts(QSet ids) { if (!m_adaptor->isReady()) { return; } // if the contact was added before ignore the added and removed signal QSet removedIds = ids; Q_FOREACH(QString removed, ids) { if (m_contactsAdded.contains(removed)) { m_contactsAdded.remove(removed); removedIds.remove(removed); } } m_contactsRemoved += removedIds; m_timer.start(); } void DirtyContactsNotify::insertChangedContacts(QSet ids) { if (!m_adaptor->isReady()) { return; } m_contactsChanged += ids; m_timer.start(); } void DirtyContactsNotify::emitSignals() { if (!m_contactsRemoved.isEmpty()) { Q_EMIT m_adaptor->contactsRemoved(m_contactsRemoved.toList()); m_contactsRemoved.clear(); } if (!m_contactsAdded.isEmpty()) { Q_EMIT m_adaptor->contactsAdded(m_contactsAdded.toList()); m_contactsAdded.clear(); } if (!m_contactsChanged.isEmpty()) { Q_EMIT m_adaptor->contactsUpdated(m_contactsChanged.toList()); m_contactsChanged.clear(); } } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/dirtycontact-notify.h0000644000015301777760000000350112321057324025217 0ustar pbusernogroup00000000000000/* * Copyright 2014 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_DIRTYCONTACT_NOTIFY_H__ #define __GALERA_DIRTYCONTACT_NOTIFY_H__ #include #include #include #include namespace galera { class AddressBookAdaptor; // this is a helper class uses a timer with a small timeout to notify the client about // any contact change notification. This class should be used instead of emit the signal directly // this will avoid notify about the contact update several times when updating different fields simultaneously // With that we can reduce the dbus traffic and skip some client calls to query about the new contact info. class DirtyContactsNotify : public QObject { Q_OBJECT public: DirtyContactsNotify(AddressBookAdaptor *adaptor, QObject *parent=0); void insertChangedContacts(QSet ids); void insertRemovedContacts(QSet ids); void insertAddedContacts(QSet ids); private Q_SLOTS: void emitSignals(); private: AddressBookAdaptor *m_adaptor; QTimer m_timer; QSet m_contactsChanged; QSet m_contactsAdded; QSet m_contactsRemoved; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/addressbook-adaptor.h0000644000015301777760000001216512321057324025140 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_ADDRESSBOOK_ADAPTOR_H__ #define __GALERA_ADDRESSBOOK_ADAPTOR_H__ #include #include #include #include #include #include "common/source.h" #include "common/dbus-service-defs.h" namespace galera { class AddressBook; class AddressBookAdaptor: public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", CPIM_ADDRESSBOOK_IFACE_NAME) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") Q_PROPERTY(bool isReady READ isReady NOTIFY ready) public: AddressBookAdaptor(const QDBusConnection &connection, AddressBook *parent); virtual ~AddressBookAdaptor(); public Q_SLOTS: SourceList availableSources(const QDBusMessage &message); Source source(const QDBusMessage &message); Source createSource(const QString &sourceName, const QDBusMessage &message); QStringList sortFields(); QDBusObjectPath query(const QString &clause, const QString &sort, const QStringList &sources); int removeContacts(const QStringList &contactIds, const QDBusMessage &message); QString createContact(const QString &contact, const QString &source, const QDBusMessage &message); QStringList updateContacts(const QStringList &contacts, const QDBusMessage &message); QString linkContacts(const QStringList &contacts); bool unlinkContacts(const QString &parentId, const QStringList &contactsIds); bool isReady(); bool ping(); Q_SIGNALS: void contactsAdded(const QStringList &ids); void contactsRemoved(const QStringList &ids); void contactsUpdated(const QStringList &ids); void asyncOperationResult(QMap errors); void ready(); private: AddressBook *m_addressBook; QDBusConnection m_connection; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/qindividual.cpp0000644000015301777760000015257012321057334024062 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "qindividual.h" #include "detail-context-parser.h" #include "gee-utils.h" #include "update-contact-request.h" #include "common/vcard-parser.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace QtVersit; using namespace QtContacts; namespace { static void gValueGeeSetAddStringFieldDetails(GValue *value, GType g_type, const char* v_string, const QtContacts::QContactDetail &detail, bool ispreferred) { GeeCollection *collection = (GeeCollection*) g_value_get_object(value); if(collection == NULL) { collection = GEE_COLLECTION(SET_AFD_NEW()); g_value_take_object(value, collection); } FolksAbstractFieldDetails *fieldDetails = NULL; if(FALSE) { } else if(g_type == FOLKS_TYPE_EMAIL_FIELD_DETAILS) { fieldDetails = FOLKS_ABSTRACT_FIELD_DETAILS ( folks_email_field_details_new(v_string, NULL)); } else if(g_type == FOLKS_TYPE_IM_FIELD_DETAILS) { fieldDetails = FOLKS_ABSTRACT_FIELD_DETAILS ( folks_im_field_details_new(v_string, NULL)); } else if(g_type == FOLKS_TYPE_NOTE_FIELD_DETAILS) { fieldDetails = FOLKS_ABSTRACT_FIELD_DETAILS ( folks_note_field_details_new(v_string, NULL, NULL)); } else if(g_type == FOLKS_TYPE_PHONE_FIELD_DETAILS) { fieldDetails = FOLKS_ABSTRACT_FIELD_DETAILS ( folks_phone_field_details_new(v_string, NULL)); } else if(g_type == FOLKS_TYPE_URL_FIELD_DETAILS) { fieldDetails = FOLKS_ABSTRACT_FIELD_DETAILS ( folks_url_field_details_new(v_string, NULL)); } else if(g_type == FOLKS_TYPE_WEB_SERVICE_FIELD_DETAILS) { fieldDetails = FOLKS_ABSTRACT_FIELD_DETAILS ( folks_web_service_field_details_new(v_string, NULL)); } if (fieldDetails == NULL) { qWarning() << "Invalid fieldDetails type" << g_type; } else { galera::DetailContextParser::parseContext(fieldDetails, detail, ispreferred); gee_collection_add(collection, fieldDetails); g_object_unref(fieldDetails); } } #define PERSONA_DETAILS_INSERT_STRING_FIELD_DETAILS(\ details, cDetails, key, value, q_type, g_type, member, prefDetail) \ { \ if(cDetails.size() > 0) { \ value = GeeUtils::gValueSliceNew(G_TYPE_OBJECT); \ Q_FOREACH(const q_type& detail, cDetails) { \ if(!detail.isEmpty()) { \ gValueGeeSetAddStringFieldDetails(value, (g_type), \ detail.member().toUtf8().data(), \ detail, \ detail == prefDetail); \ } \ } \ GeeUtils::personaDetailsInsert((details), (key), (value)); \ } \ } } namespace galera { bool QIndividual::m_autoLink = false; QIndividual::QIndividual(FolksIndividual *individual, FolksIndividualAggregator *aggregator) : m_individual(0), m_aggregator(aggregator), m_contact(0), m_currentUpdate(0) { setIndividual(individual); } void QIndividual::notifyUpdate() { for(int i=0; i < m_listeners.size(); i++) { QPair listener = m_listeners[i]; listener.second.invoke(listener.first, Q_ARG(QIndividual*, this)); } } QIndividual::~QIndividual() { if (m_currentUpdate) { m_currentUpdate->disconnect(m_updateConnection); // this will leave the update object to destroy itself // this is necessary because the individual can be destroyed during a update // Eg. If the individual get linked m_currentUpdate->deatach(); m_currentUpdate = 0; } clear(); } QString QIndividual::id() const { return m_id; } QtContacts::QContactDetail QIndividual::getUid() const { QContactGuid uid; const char* id = folks_individual_get_id(m_individual); Q_ASSERT(id); uid.setGuid(QString::fromUtf8(id)); return uid; } QList QIndividual::getSyncTargets() const { QList details; Q_FOREACH(const QString id, m_personas.keys()) { QContactSyncTarget target; FolksPersona *p = m_personas[id]; FolksPersonaStore *ps = folks_persona_get_store(p); QString displayName = folks_persona_store_get_display_name(ps); target.setDetailUri(QString(id).replace(":",".")); target.setSyncTarget(displayName); details << target; } return details; } void QIndividual::appendDetailsForPersona(QtContacts::QContact *contact, const QtContacts::QContactDetail &detail, bool readOnly) const { if (!detail.isEmpty()) { QtContacts::QContactDetail cpy(detail); QtContacts::QContactDetail::AccessConstraints access; if (readOnly || detail.accessConstraints().testFlag(QContactDetail::ReadOnly)) { access |= QContactDetail::ReadOnly; } if (detail.accessConstraints().testFlag(QContactDetail::Irremovable)) { access |= QContactDetail::Irremovable; } QContactManagerEngine::setDetailAccessConstraints(&cpy, access); contact->appendDetail(cpy); } } void QIndividual::appendDetailsForPersona(QtContacts::QContact *contact, QList details, const QString &preferredAction, const QtContacts::QContactDetail &preferred, bool readOnly) const { Q_FOREACH(const QContactDetail &detail, details) { appendDetailsForPersona(contact, detail, readOnly); if (!preferred.isEmpty()) { contact->setPreferredDetail(preferredAction, preferred); } } } QContactDetail QIndividual::getPersonaName(FolksPersona *persona, int index) const { if (!FOLKS_IS_NAME_DETAILS(persona)) { return QContactDetail(); } QContactName detail; FolksStructuredName *sn = folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(persona)); if (sn) { const char *name = folks_structured_name_get_given_name(sn); if (name && strlen(name)) { detail.setFirstName(QString::fromUtf8(name)); } name = folks_structured_name_get_additional_names(sn); if (name && strlen(name)) { detail.setMiddleName(QString::fromUtf8(name)); } name = folks_structured_name_get_family_name(sn); if (name && strlen(name)) { detail.setLastName(QString::fromUtf8(name)); } name = folks_structured_name_get_prefixes(sn); if (name && strlen(name)) { detail.setPrefix(QString::fromUtf8(name)); } name = folks_structured_name_get_suffixes(sn); if (name && strlen(name)) { detail.setSuffix(QString::fromUtf8(name)); } detail.setDetailUri(QString("%1.1").arg(index)); } return detail; } QtContacts::QContactDetail QIndividual::getPersonaFullName(FolksPersona *persona, int index) const { if (!FOLKS_IS_NAME_DETAILS(persona)) { return QContactDetail(); } QContactDisplayLabel detail; FolksStructuredName *sn = folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(persona)); QString displayName; if (sn) { const char *name = folks_structured_name_get_given_name(sn); if (name && strlen(name)) { displayName += QString::fromUtf8(name); } name = folks_structured_name_get_family_name(sn); if (name && strlen(name)) { if (!displayName.isEmpty()) { displayName += " "; } displayName += QString::fromUtf8(name); } } if (!displayName.isEmpty()) { detail.setLabel(displayName); detail.setDetailUri(QString("%1.1").arg(index)); } return detail; } QtContacts::QContactDetail QIndividual::getPersonaNickName(FolksPersona *persona, int index) const { if (!FOLKS_IS_NAME_DETAILS(persona)) { return QContactDetail(); } QContactNickname detail; const gchar* nickname = folks_name_details_get_nickname(FOLKS_NAME_DETAILS(persona)); if (nickname && strlen(nickname)) { detail.setNickname(QString::fromUtf8(nickname)); detail.setDetailUri(QString("%1.1").arg(index)); } return detail; } QtContacts::QContactDetail QIndividual::getPersonaBirthday(FolksPersona *persona, int index) const { if (!FOLKS_IS_BIRTHDAY_DETAILS(persona)) { return QContactDetail(); } QContactBirthday detail; GDateTime* datetime = folks_birthday_details_get_birthday(FOLKS_BIRTHDAY_DETAILS(persona)); if (datetime) { QDate date(g_date_time_get_year(datetime), g_date_time_get_month(datetime), g_date_time_get_day_of_month(datetime)); QTime time(g_date_time_get_hour(datetime), g_date_time_get_minute(datetime), g_date_time_get_second(datetime)); detail.setDateTime(QDateTime(date, time)); detail.setDetailUri(QString("%1.1").arg(index)); } return detail; } void QIndividual::folksIndividualChanged(FolksIndividual *individual, GParamSpec *pspec, QIndividual *self) { Q_UNUSED(individual); Q_UNUSED(pspec); // skip update contact during a contact update, the update will be done after if (self->m_contactLock.tryLock()) { // invalidate contact self->markAsDirty(); self->notifyUpdate(); self->m_contactLock.unlock(); } } QtContacts::QContactDetail QIndividual::getPersonaPhoto(FolksPersona *persona, int index) const { QContactAvatar avatar; if (!FOLKS_IS_AVATAR_DETAILS(persona)) { return avatar; } GLoadableIcon *avatarIcon = folks_avatar_details_get_avatar(FOLKS_AVATAR_DETAILS(persona)); if (avatarIcon) { QString url; if (G_IS_FILE_ICON(avatarIcon)) { GFile *avatarFile = g_file_icon_get_file(G_FILE_ICON(avatarIcon)); gchar *uri = g_file_get_uri(avatarFile); if (uri) { url = QString::fromUtf8(uri); g_free(uri); } } else { FolksAvatarCache *cache = folks_avatar_cache_dup(); const char *contactId = folks_individual_get_id(m_individual); gchar *uri = folks_avatar_cache_build_uri_for_avatar(cache, contactId); url = QString::fromUtf8(uri); if (!QFile::exists(url)) { folks_avatar_cache_store_avatar(cache, contactId, avatarIcon, QIndividual::avatarCacheStoreDone, strdup(uri)); } g_free(uri); g_object_unref(cache); } // Avoid to set a empty url if (url.isEmpty()) { return avatar; } avatar.setImageUrl(QUrl(url)); avatar.setDetailUri(QString("%1.1").arg(index)); } return avatar; } void QIndividual::avatarCacheStoreDone(GObject *source, GAsyncResult *result, gpointer data) { GError *error = 0; gchar *uri = folks_avatar_cache_store_avatar_finish(FOLKS_AVATAR_CACHE(source), result, &error); if (error) { qWarning() << "Fail to store avatar" << error->message; g_error_free(error); } if (g_str_equal(data, uri) != 0) { qWarning() << "Avatar name changed from" << (gchar*)data << "to" << uri; } g_free(data); } QList QIndividual::getPersonaRoles(FolksPersona *persona, QtContacts::QContactDetail *preferredRole, int index) const { if (!FOLKS_IS_ROLE_DETAILS(persona)) { return QList(); } QList details; GeeSet *roles = folks_role_details_get_roles(FOLKS_ROLE_DETAILS(persona)); if (!roles) { return details; } GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(roles)); int fieldIndex = 1; while(gee_iterator_next(iter)) { FolksAbstractFieldDetails *fd = FOLKS_ABSTRACT_FIELD_DETAILS(gee_iterator_get(iter)); FolksRole *role = FOLKS_ROLE(folks_abstract_field_details_get_value(fd)); QContactOrganization org; QString field; field = QString::fromUtf8(folks_role_get_organisation_name(role)); if (!field.isEmpty()) { org.setName(field); } field = QString::fromUtf8(folks_role_get_title(role)); if (!field.isEmpty()) { org.setTitle(field); } field = QString::fromUtf8(folks_role_get_role(role)); if (!field.isEmpty()) { org.setRole(field); } bool isPref = false; DetailContextParser::parseParameters(org, fd, &isPref); org.setDetailUri(QString("%1.%2").arg(index).arg(fieldIndex++)); if (isPref) { *preferredRole = org; } g_object_unref(fd); details << org; } g_object_unref(iter); return details; } QList QIndividual::getPersonaEmails(FolksPersona *persona, QtContacts::QContactDetail *preferredEmail, int index) const { if (!FOLKS_IS_EMAIL_DETAILS(persona)) { return QList(); } QList details; GeeSet *emails = folks_email_details_get_email_addresses(FOLKS_EMAIL_DETAILS(persona)); if (!emails) { return details; } GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(emails)); int fieldIndex = 1; while(gee_iterator_next(iter)) { FolksAbstractFieldDetails *fd = FOLKS_ABSTRACT_FIELD_DETAILS(gee_iterator_get(iter)); const gchar *email = (const gchar*) folks_abstract_field_details_get_value(fd); QContactEmailAddress addr; addr.setEmailAddress(QString::fromUtf8(email)); bool isPref = false; DetailContextParser::parseParameters(addr, fd, &isPref); addr.setDetailUri(QString("%1.%2").arg(index).arg(fieldIndex++)); if (isPref) { *preferredEmail = addr; } g_object_unref(fd); details << addr; } g_object_unref(iter); return details; } QList QIndividual::getPersonaPhones(FolksPersona *persona, QtContacts::QContactDetail *preferredPhone, int index) const { if (!FOLKS_IS_PHONE_DETAILS(persona)) { return QList(); } QList details; GeeSet *phones = folks_phone_details_get_phone_numbers(FOLKS_PHONE_DETAILS(persona)); if (!phones) { return details; } GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(phones)); int fieldIndex = 1; while(gee_iterator_next(iter)) { FolksAbstractFieldDetails *fd = FOLKS_ABSTRACT_FIELD_DETAILS(gee_iterator_get(iter)); const gchar *phone = (const char*) folks_abstract_field_details_get_value(fd); QContactPhoneNumber number; number.setNumber(QString::fromUtf8(phone)); bool isPref = false; DetailContextParser::parseParameters(number, fd, &isPref); number.setDetailUri(QString("%1.%2").arg(index).arg(fieldIndex++)); if (isPref) { *preferredPhone = number; } g_object_unref(fd); details << number; } g_object_unref(iter); return details; } QList QIndividual::getPersonaAddresses(FolksPersona *persona, QtContacts::QContactDetail *preferredAddress, int index) const { if (!FOLKS_IS_POSTAL_ADDRESS_DETAILS(persona)) { return QList(); } QList details; GeeSet *addresses = folks_postal_address_details_get_postal_addresses(FOLKS_POSTAL_ADDRESS_DETAILS(persona)); if (!addresses) { return details; } GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(addresses)); int fieldIndex = 1; while(gee_iterator_next(iter)) { FolksAbstractFieldDetails *fd = FOLKS_ABSTRACT_FIELD_DETAILS(gee_iterator_get(iter)); FolksPostalAddress *addr = FOLKS_POSTAL_ADDRESS(folks_abstract_field_details_get_value(fd)); QContactAddress address; const char *field = folks_postal_address_get_country(addr); if (field && strlen(field)) { address.setCountry(QString::fromUtf8(field)); } field = folks_postal_address_get_locality(addr); if (field && strlen(field)) { address.setLocality(QString::fromUtf8(field)); } field = folks_postal_address_get_po_box(addr); if (field && strlen(field)) { address.setPostOfficeBox(QString::fromUtf8(field)); } field = folks_postal_address_get_postal_code(addr); if (field && strlen(field)) { address.setPostcode(QString::fromUtf8(field)); } field = folks_postal_address_get_region(addr); if (field && strlen(field)) { address.setRegion(QString::fromUtf8(field)); } field = folks_postal_address_get_street(addr); if (field && strlen(field)) { address.setStreet(QString::fromUtf8(field)); } bool isPref = false; DetailContextParser::parseParameters(address, fd, &isPref); address.setDetailUri(QString("%1.%2").arg(index).arg(fieldIndex++)); if (isPref) { *preferredAddress = address; } g_object_unref(fd); details << address; } g_object_unref(iter); return details; } QList QIndividual::getPersonaIms(FolksPersona *persona, QtContacts::QContactDetail *preferredIm, int index) const { if (!FOLKS_IS_IM_DETAILS(persona)) { return QList(); } QList details; GeeMultiMap *ims = folks_im_details_get_im_addresses(FOLKS_IM_DETAILS(persona)); if (!ims) { return details; } GeeSet *keys = gee_multi_map_get_keys(ims); GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(keys)); int fieldIndex = 1; while(gee_iterator_next(iter)) { const gchar *key = (const gchar*) gee_iterator_get(iter); GeeCollection *values = gee_multi_map_get(ims, key); GeeIterator *iterValues = gee_iterable_iterator(GEE_ITERABLE(values)); while(gee_iterator_next(iterValues)) { FolksAbstractFieldDetails *fd = FOLKS_ABSTRACT_FIELD_DETAILS(gee_iterator_get(iterValues)); const char *uri = (const char*) folks_abstract_field_details_get_value(fd); GeeCollection *parameters = folks_abstract_field_details_get_parameter_values(fd, "X-FOLKS-FIELD"); if (parameters) { continue; } QContactOnlineAccount account; account.setAccountUri(QString::fromUtf8(uri)); int protocolId = DetailContextParser::accountProtocolFromString(QString::fromUtf8(key)); account.setProtocol(static_cast(protocolId)); bool isPref = false; DetailContextParser::parseParameters(account, fd, &isPref); account.setDetailUri(QString("%1.%2").arg(index).arg(fieldIndex++)); if (isPref) { *preferredIm = account; } g_object_unref(fd); details << account; } g_object_unref(iterValues); } g_object_unref(iter); return details; } QList QIndividual::getPersonaUrls(FolksPersona *persona, QtContacts::QContactDetail *preferredUrl, int index) const { if (!FOLKS_IS_URL_DETAILS(persona)) { return QList(); } QList details; GeeSet *urls = folks_url_details_get_urls(FOLKS_URL_DETAILS(persona)); if (!urls) { return details; } GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(urls)); int fieldIndex = 1; while(gee_iterator_next(iter)) { FolksAbstractFieldDetails *fd = FOLKS_ABSTRACT_FIELD_DETAILS(gee_iterator_get(iter)); const char *url = (const char*) folks_abstract_field_details_get_value(fd); QContactUrl detail; detail.setUrl(QString::fromUtf8(url)); bool isPref = false; DetailContextParser::parseParameters(detail, fd, &isPref); detail.setDetailUri(QString("%1.%2").arg(index).arg(fieldIndex++)); if (isPref) { *preferredUrl = detail; } g_object_unref(fd); details << detail; } g_object_unref(iter); return details; } QtContacts::QContactDetail QIndividual::getPersonaFavorite(FolksPersona *persona, int index) const { if (!FOLKS_IS_FAVOURITE_DETAILS(persona)) { return QtContacts::QContactDetail(); } QContactFavorite detail; detail.setFavorite(folks_favourite_details_get_is_favourite(FOLKS_FAVOURITE_DETAILS(persona))); detail.setDetailUri(QString("%1.%2").arg(index).arg(1)); return detail; } QtContacts::QContact QIndividual::copy(QList fields) { QList details; QContact result; if (fields.isEmpty()) { result = contact(); } else { QContact fullContact = contact(); // this will remove the contact details but will keep the other metadata like preferred fields result = fullContact; result.clearDetails(); // mandatory details << fullContact.detail(); Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } // sync targets Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } if (fields.contains(QContactDetail::TypeName)) { details << fullContact.detail(); } if (fields.contains(QContactDetail::TypeDisplayLabel)) { details << fullContact.detail(); } if (fields.contains(QContactDetail::TypeNickname)) { details << fullContact.detail(); } if (fields.contains(QContactDetail::TypeBirthday)) { details << fullContact.detail(); } if (fields.contains(QContactDetail::TypeAvatar)) { details << fullContact.detail(); } if (fields.contains(QContactDetail::TypeOrganization)) { Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } } if (fields.contains(QContactDetail::TypeEmailAddress)) { Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } } if (fields.contains(QContactDetail::TypePhoneNumber)) { Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } } if (fields.contains(QContactDetail::TypeAddress)) { Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } } if (fields.contains(QContactDetail::TypeUrl)) { Q_FOREACH(QContactDetail det, fullContact.details()) { details << det; } } Q_FOREACH(QContactDetail det, details) { result.appendDetail(det); } } return result; } QtContacts::QContact &QIndividual::contact() { if (!m_contact && m_individual) { QMutexLocker locker(&m_contactLock); updatePersonas(); // avoid change on m_contact pointer until the contact is fully loaded QContact contact; updateContact(&contact); m_contact = new QContact(contact); } return *m_contact; } void QIndividual::updatePersonas() { Q_FOREACH(FolksPersona *p, m_personas.values()) { g_object_unref(p); } GeeSet *personas = folks_individual_get_personas(m_individual); if (!personas) { Q_ASSERT(false); return; } GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(personas)); while(gee_iterator_next(iter)) { FolksPersona *persona = FOLKS_PERSONA(gee_iterator_get(iter)); m_personas.insert(QString::fromUtf8(folks_persona_get_iid(persona)), persona); } g_object_unref(iter); } void QIndividual::updateContact(QContact *contact) const { if (!m_individual) { return; } contact->appendDetail(getUid()); Q_FOREACH(QContactDetail detail, getSyncTargets()) { contact->appendDetail(detail); } int personaIndex = 1; Q_FOREACH(FolksPersona *persona, m_personas.values()) { Q_ASSERT(FOLKS_IS_PERSONA(persona)); int wsize = 0; gchar **wproperties = folks_persona_get_writeable_properties(persona, &wsize); //"gender", "local-ids", "avatar", "postal-addresses", "urls", "phone-numbers", "structured-name", //"anti-links", "im-addresses", "is-favourite", "birthday", "notes", "roles", "email-addresses", //"web-service-addresses", "groups", "full-name" QStringList wPropList; for(int i=0; i < wsize; i++) { wPropList << wproperties[i]; } // vcard only support one of these details by contact if (personaIndex == 1) { appendDetailsForPersona(contact, getPersonaName(persona, personaIndex), !wPropList.contains("structured-name")); appendDetailsForPersona(contact, getPersonaFullName(persona, personaIndex), !wPropList.contains("full-name")); appendDetailsForPersona(contact, getPersonaNickName(persona, personaIndex), !wPropList.contains("structured-name")); appendDetailsForPersona(contact, getPersonaBirthday(persona, personaIndex), !wPropList.contains("birthday")); appendDetailsForPersona(contact, getPersonaPhoto(persona, personaIndex), !wPropList.contains("avatar")); appendDetailsForPersona(contact, getPersonaFavorite(persona, personaIndex), !wPropList.contains("is-favourite")); } QList details; QContactDetail prefDetail; details = getPersonaRoles(persona, &prefDetail, personaIndex); appendDetailsForPersona(contact, details, VCardParser::PreferredActionNames[QContactOrganization::Type], prefDetail, !wPropList.contains("roles")); details = getPersonaEmails(persona, &prefDetail, personaIndex); appendDetailsForPersona(contact, details, VCardParser::PreferredActionNames[QContactEmailAddress::Type], prefDetail, !wPropList.contains("email-addresses")); details = getPersonaPhones(persona, &prefDetail, personaIndex); appendDetailsForPersona(contact, details, VCardParser::PreferredActionNames[QContactPhoneNumber::Type], prefDetail, !wPropList.contains("phone-numbers")); details = getPersonaAddresses(persona, &prefDetail, personaIndex); appendDetailsForPersona(contact, details, VCardParser::PreferredActionNames[QContactAddress::Type], prefDetail, !wPropList.contains("postal-addresses")); details = getPersonaIms(persona, &prefDetail, personaIndex); appendDetailsForPersona(contact, details, VCardParser::PreferredActionNames[QContactOnlineAccount::Type], prefDetail, !wPropList.contains("im-addresses")); details = getPersonaUrls(persona, &prefDetail, personaIndex); appendDetailsForPersona(contact, details, VCardParser::PreferredActionNames[QContactUrl::Type], prefDetail, !wPropList.contains("urls")); personaIndex++; } } bool QIndividual::update(const QtContacts::QContact &newContact, QObject *object, const char *slot) { QContact &originalContact = contact(); if (newContact != originalContact) { m_currentUpdate = new UpdateContactRequest(newContact, this, object, slot); if (!m_contactLock.tryLock(5000)) { qWarning() << "Fail to lock contact to update"; m_currentUpdate->notifyError("Fail to update contact"); m_currentUpdate->deleteLater(); m_currentUpdate = 0; return false; } m_updateConnection = QObject::connect(m_currentUpdate, &UpdateContactRequest::done, [this] (const QString &errorMessage) { if (errorMessage.isEmpty()) { markAsDirty(); } m_currentUpdate->deleteLater(); m_currentUpdate = 0; m_contactLock.unlock(); }); m_currentUpdate->start(); return true; } else { qDebug() << "Contact is equal"; return false; } } bool QIndividual::update(const QString &vcard, QObject *object, const char *slot) { QContact contact = VCardParser::vcardToContact(vcard); return update(contact, object, slot); } FolksIndividual *QIndividual::individual() const { return m_individual; } QList QIndividual::personas() const { return m_personas.values(); } void QIndividual::clearPersonas() { Q_FOREACH(FolksPersona *p, m_personas.values()) { g_object_unref(p); } m_personas.clear(); } void QIndividual::clear() { clearPersonas(); if (m_individual) { // disconnect any previous handler Q_FOREACH(int handlerId, m_notifyConnections) { g_signal_handler_disconnect(m_individual, handlerId); } m_notifyConnections.clear(); g_object_unref(m_individual); m_individual = 0; } if (m_contact) { delete m_contact; m_contact = 0; } } void QIndividual::addListener(QObject *object, const char *slot) { int slotIndex = object->metaObject()->indexOfSlot(++slot); if (slotIndex == -1) { qWarning() << "Invalid slot:" << slot << "for object" << object; } else { m_listeners << qMakePair(object, object->metaObject()->method(slotIndex)); } } bool QIndividual::isValid() const { return (m_individual != 0); } void QIndividual::flush() { // flush the folks persona store folks_persona_store_flush(folks_individual_aggregator_get_primary_store(m_aggregator), 0, 0); // cause the contact info to be reload markAsDirty(); } void QIndividual::setIndividual(FolksIndividual *individual) { static QList individualProperties; if (m_individual != individual) { clear(); if (individual) { QString newId = QString::fromUtf8(folks_individual_get_id(individual)); if (!m_id.isEmpty()) { // we can only update to individual with the same id Q_ASSERT(newId == m_id); } else { m_id = newId; } } m_individual = individual; if (m_individual) { g_object_ref(m_individual); if (individualProperties.isEmpty()) { individualProperties << "alias" << "avatar" << "birthday" << "calendar-event-id" << "call-interaction-count" << "client-types" << "email-addresses" << "full-name" << "gender" << "groups" << "id" << "im-addresses" << "im-interaction-count" << "is-favourite" << "is-user" << "last-call-interaction-datetime" << "last-im-interaction-datetime" << "local-ids" << "location" << "nickname" << "notes" << "personas" << "phone-numbers" << "postal-addresses" << "presence-message" << "presence-status" << "presence-type" << "roles" << "structured-name" << "trust-level" << "urls" << "web-service-addresses"; } Q_FOREACH(const QByteArray &property, individualProperties) { uint signalHandler = g_signal_connect(G_OBJECT(m_individual), QByteArray("notify::") + property, (GCallback) QIndividual::folksIndividualChanged, const_cast(this)); m_notifyConnections << signalHandler; } } } } GHashTable *QIndividual::parseAddressDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { if(cDetails.size() == 0) { return details; } GValue *value = GeeUtils::gValueSliceNew(G_TYPE_OBJECT); Q_FOREACH(const QContactDetail& detail, cDetails) { if(!detail.isEmpty()) { QContactAddress address = static_cast(detail); FolksPostalAddress *postalAddress = folks_postal_address_new(address.postOfficeBox().toUtf8().data(), NULL, // extension address.street().toUtf8().data(), address.locality().toUtf8().data(), address.region().toUtf8().data(), address.postcode().toUtf8().data(), address.country().toUtf8().data(), NULL, // address format NULL); //UID GeeCollection *collection = (GeeCollection*) g_value_get_object(value); if(collection == NULL) { collection = GEE_COLLECTION(SET_AFD_NEW()); g_value_take_object(value, collection); } if (!folks_postal_address_is_empty(postalAddress)) { FolksPostalAddressFieldDetails *pafd = folks_postal_address_field_details_new(postalAddress, NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(pafd), address, detail == prefDetail); gee_collection_add(collection, pafd); g_object_unref(pafd); } g_object_unref(postalAddress); } GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_POSTAL_ADDRESSES, value); } return details; } GHashTable *QIndividual::parsePhotoDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactAvatar avatar = static_cast(detail); if(!avatar.isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(G_TYPE_FILE_ICON); QUrl avatarUri = avatar.imageUrl(); if(!avatarUri.isEmpty()) { QString formattedUri = avatarUri.toString(QUrl::RemoveUserInfo); if(!formattedUri.isEmpty()) { GFile *avatarFile = g_file_new_for_uri(formattedUri.toUtf8().data()); GFileIcon *avatarFileIcon = G_FILE_ICON(g_file_icon_new(avatarFile)); g_value_take_object(value, avatarFileIcon); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_AVATAR, value); g_clear_object((GObject**) &avatarFile); } } else { g_object_unref(value); } } } return details; } GHashTable *QIndividual::parseBirthdayDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactBirthday birthday = static_cast(detail); if(!birthday.isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(G_TYPE_DATE_TIME); GDateTime *dateTime = g_date_time_new_from_unix_utc(birthday.dateTime().toMSecsSinceEpoch() / 1000); g_value_set_boxed(value, dateTime); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_BIRTHDAY, value); g_date_time_unref(dateTime); } } return details; } GHashTable *QIndividual::parseEmailDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { if(cDetails.size() == 0) { return details; } GValue *value; PERSONA_DETAILS_INSERT_STRING_FIELD_DETAILS(details, cDetails, FOLKS_PERSONA_DETAIL_EMAIL_ADDRESSES, value, QContactEmailAddress, FOLKS_TYPE_EMAIL_FIELD_DETAILS, emailAddress, prefDetail); return details; } GHashTable *QIndividual::parseFavoriteDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactFavorite favorite = static_cast(detail); if(!favorite.isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(G_TYPE_BOOLEAN); g_value_set_boolean(value, favorite.isFavorite()); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_IS_FAVOURITE, value); } } return details; } GHashTable *QIndividual::parseGenderDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactGender gender = static_cast(detail); if(!gender.isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(FOLKS_TYPE_GENDER); FolksGender genderEnum = FOLKS_GENDER_UNSPECIFIED; if(gender.gender() == QContactGender::GenderMale) { genderEnum = FOLKS_GENDER_MALE; } else if(gender.gender() == QContactGender::GenderFemale) { genderEnum = FOLKS_GENDER_FEMALE; } g_value_set_enum(value, genderEnum); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_GENDER, value); } } return details; } GHashTable *QIndividual::parseNameDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactName name = static_cast(detail); if(!name.isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(FOLKS_TYPE_STRUCTURED_NAME); FolksStructuredName *sn = folks_structured_name_new(name.lastName().toUtf8().data(), name.firstName().toUtf8().data(), name.middleName().toUtf8().data(), name.prefix().toUtf8().data(), name.suffix().toUtf8().data()); g_value_take_object(value, sn); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_STRUCTURED_NAME, value); } } return details; } GHashTable *QIndividual::parseFullNameDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactDisplayLabel displayLabel = static_cast(detail); if(!displayLabel.label().isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(G_TYPE_STRING); g_value_set_string(value, displayLabel.label().toUtf8().data()); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_FULL_NAME, value); // FIXME: check if those values should all be set to the same thing value = GeeUtils::gValueSliceNew(G_TYPE_STRING); g_value_set_string(value, displayLabel.label().toUtf8().data()); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_ALIAS, value); } } return details; } GHashTable *QIndividual::parseNicknameDetails(GHashTable *details, const QList &cDetails) { if(cDetails.size() == 0) { return details; } Q_FOREACH(const QContactDetail& detail, cDetails) { QContactNickname nickname = static_cast(detail); if(!nickname.nickname().isEmpty()) { GValue *value = GeeUtils::gValueSliceNew(G_TYPE_STRING); g_value_set_string(value, nickname.nickname().toUtf8().data()); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_NICKNAME, value); // FIXME: check if those values should all be set to the same thing value = GeeUtils::gValueSliceNew(G_TYPE_STRING); g_value_set_string(value, nickname.nickname().toUtf8().data()); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_ALIAS, value); } } return details; } GHashTable *QIndividual::parseNoteDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { if(cDetails.size() == 0) { return details; } GValue *value; PERSONA_DETAILS_INSERT_STRING_FIELD_DETAILS(details, cDetails, FOLKS_PERSONA_DETAIL_NOTES, value, QContactNote, FOLKS_TYPE_NOTE_FIELD_DETAILS, note, prefDetail); return details; } GHashTable *QIndividual::parseImDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { Q_UNUSED(prefDetail); if(cDetails.size() == 0) { return details; } QMultiMap providerUidMap; Q_FOREACH(const QContactDetail &detail, cDetails) { QContactOnlineAccount account = static_cast(detail); if (!account.isEmpty()) { providerUidMap.insert(DetailContextParser::accountProtocolName(account.protocol()), account.accountUri()); } } if(!providerUidMap.isEmpty()) { //TODO: add account type and subtype GValue *value = GeeUtils::asvSetStrNew(providerUidMap); GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_IM_ADDRESSES, value); } return details; } GHashTable *QIndividual::parseOrganizationDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { if(cDetails.size() == 0) { return details; } GValue *value = GeeUtils::gValueSliceNew(G_TYPE_OBJECT); Q_FOREACH(const QContactDetail& detail, cDetails) { QContactOrganization org = static_cast(detail); if(!org.isEmpty()) { FolksRole *role = folks_role_new(org.title().toUtf8().data(), org.name().toUtf8().data(), NULL); folks_role_set_role(role, org.role().toUtf8().data()); GeeCollection *collection = (GeeCollection*) g_value_get_object(value); if(collection == NULL) { collection = GEE_COLLECTION(SET_AFD_NEW()); g_value_take_object(value, collection); } FolksRoleFieldDetails *rfd = folks_role_field_details_new(role, NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(rfd), org, detail == prefDetail); gee_collection_add(collection, rfd); g_object_unref(rfd); g_object_unref(role); } } GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_ROLES, value); return details; } GHashTable *QIndividual::parsePhoneNumbersDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { if(cDetails.size() == 0) { return details; } GValue *value = GeeUtils::gValueSliceNew(G_TYPE_OBJECT); Q_FOREACH(const QContactDetail &detail, cDetails) { QContactPhoneNumber phone = static_cast(detail); if(!phone.isEmpty()) { gValueGeeSetAddStringFieldDetails(value, FOLKS_TYPE_PHONE_FIELD_DETAILS, phone.number().toUtf8().data(), phone, detail == prefDetail); } } GeeUtils::personaDetailsInsert(details, FOLKS_PERSONA_DETAIL_PHONE_NUMBERS, value); return details; } GHashTable *QIndividual::parseUrlDetails(GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail) { if(cDetails.size() == 0) { return details; } GValue *value; PERSONA_DETAILS_INSERT_STRING_FIELD_DETAILS(details, cDetails, FOLKS_PERSONA_DETAIL_URLS, value, QContactUrl, FOLKS_TYPE_URL_FIELD_DETAILS, url, prefDetail); return details; } GHashTable *QIndividual::parseDetails(const QtContacts::QContact &contact) { GHashTable *details = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, (GDestroyNotify) GeeUtils::gValueSliceFree); parsePhotoDetails(details, contact.details(QContactAvatar::Type)); parseBirthdayDetails(details, contact.details(QContactBirthday::Type)); parseFavoriteDetails(details, contact.details(QContactFavorite::Type)); parseGenderDetails(details, contact.details(QContactGender::Type)); parseNameDetails(details, contact.details(QContactName::Type)); parseFullNameDetails(details, contact.details(QContactDisplayLabel::Type)); parseNicknameDetails(details, contact.details(QContactNickname::Type)); parseAddressDetails(details, contact.details(QContactAddress::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactAddress::Type])); parseEmailDetails(details, contact.details(QContactEmailAddress::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactEmailAddress::Type])); parseNoteDetails(details, contact.details(QContactNote::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactNote::Type])); parseImDetails(details, contact.details(QContactOnlineAccount::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactOnlineAccount::Type])); parseOrganizationDetails(details, contact.details(QContactOrganization::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactOrganization::Type])); parsePhoneNumbersDetails(details, contact.details(QContactPhoneNumber::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactPhoneNumber::Type])); parseUrlDetails(details, contact.details(QContactUrl::Type), contact.preferredDetail(VCardParser::PreferredActionNames[QContactUrl::Type])); return details; } void QIndividual::markAsDirty() { delete m_contact; m_contact = 0; } void QIndividual::enableAutoLink(bool flag) { m_autoLink = flag; } bool QIndividual::autoLinkEnabled() { return m_autoLink; } FolksPersona* QIndividual::primaryPersona() { if (m_personas.size() > 0) { return m_personas.begin().value(); } else { return 0; } } QtContacts::QContactDetail QIndividual::detailFromUri(QtContacts::QContactDetail::DetailType type, const QString &uri) const { Q_FOREACH(QContactDetail detail, m_contact->details(type)) { if (detail.detailUri() == uri) { return detail; } } return QContactDetail(); } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/detail-context-parser.cpp0000644000015301777760000003404412321057324025761 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "detail-context-parser.h" #include "common/vcard-parser.h" #include #include using namespace QtContacts; namespace galera { void DetailContextParser::parseContext(FolksAbstractFieldDetails *fd, const QtContacts::QContactDetail &detail, bool isPreffered) { // clear the current values to prevent duplicate values folks_abstract_field_details_set_parameter(fd, "type", ""); Q_FOREACH(const QString ¶m, listContext(detail)) { folks_abstract_field_details_add_parameter(fd, "type", param.toUtf8().data()); } if (isPreffered) { folks_abstract_field_details_set_parameter(fd, VCardParser::PrefParamName.toLower().toUtf8().data(), "1"); } } QStringList DetailContextParser::parseContext(const QtContacts::QContactDetail &detail) { static QMap map; // populate the map once if (map.isEmpty()) { map[QContactDetail::ContextHome] = "home"; map[QContactDetail::ContextWork] = "work"; map[QContactDetail::ContextOther] = "other"; } QStringList strings; Q_FOREACH(int subType, detail.contexts()) { if (map.contains(subType)) { strings << map[subType]; } } return strings; } QStringList DetailContextParser::listContext(const QtContacts::QContactDetail &detail) { QStringList context = parseContext(detail); switch (detail.type()) { case QContactDetail::TypePhoneNumber: context << parsePhoneContext(detail); break; case QContactDetail::TypeAddress: context << parseAddressContext(detail); break; case QContactDetail::TypeOnlineAccount: context << parseOnlineAccountContext(detail); break; case QContactDetail::TypeUrl: case QContactDetail::TypeEmailAddress: case QContactDetail::TypeOrganization: default: break; } return context; } QStringList DetailContextParser::parsePhoneContext(const QtContacts::QContactDetail &detail) { static QMap map; // populate the map once if (map.isEmpty()) { map[QContactPhoneNumber::SubTypeLandline] = "landline"; map[QContactPhoneNumber::SubTypeMobile] = "mobile"; map[QContactPhoneNumber::SubTypeFax] = "fax"; map[QContactPhoneNumber::SubTypePager] = "pager"; map[QContactPhoneNumber::SubTypeVoice] = "voice"; map[QContactPhoneNumber::SubTypeModem] = "modem"; map[QContactPhoneNumber::SubTypeVideo] = "video"; map[QContactPhoneNumber::SubTypeCar] = "car"; map[QContactPhoneNumber::SubTypeBulletinBoardSystem] = "bulletinboard"; map[QContactPhoneNumber::SubTypeMessagingCapable] = "messaging"; map[QContactPhoneNumber::SubTypeAssistant] = "assistant"; map[QContactPhoneNumber::SubTypeDtmfMenu] = "dtmfmenu"; } QStringList strings; Q_FOREACH(int subType, static_cast(&detail)->subTypes()) { if (map.contains(subType)) { strings << map[subType]; } } return strings; } QStringList DetailContextParser::parseAddressContext(const QtContacts::QContactDetail &detail) { static QMap map; // populate the map once if (map.isEmpty()) { map[QContactAddress::SubTypeParcel] = "parcel"; map[QContactAddress::SubTypePostal] = "postal"; map[QContactAddress::SubTypeDomestic] = "domestic"; map[QContactAddress::SubTypeInternational] = "international"; } QStringList strings; Q_FOREACH(int subType, static_cast(&detail)->subTypes()) { if (map.contains(subType)) { strings << map[subType]; } } return strings; } QStringList DetailContextParser::parseOnlineAccountContext(const QtContacts::QContactDetail &im) { static QMap map; // populate the map once if (map.isEmpty()) { map[QContactOnlineAccount::SubTypeSip] = "sip"; map[QContactOnlineAccount::SubTypeSipVoip] = "sipvoip"; map[QContactOnlineAccount::SubTypeImpp] = "impp"; map[QContactOnlineAccount::SubTypeVideoShare] = "videoshare"; } QSet strings; const QContactOnlineAccount *acc = static_cast(&im); Q_FOREACH(int subType, acc->subTypes()) { if (map.contains(subType)) { strings << map[subType]; } } // Make compatible with contact importer if (acc->protocol() == QContactOnlineAccount::ProtocolJabber) { strings << map[QContactOnlineAccount::SubTypeImpp]; } else if (acc->protocol() == QContactOnlineAccount::ProtocolJabber) { strings << map[QContactOnlineAccount::SubTypeSip]; } return strings.toList(); } QString DetailContextParser::accountProtocolName(int protocol) { static QMap map; // populate the map once if (map.isEmpty()) { map[QContactOnlineAccount::ProtocolAim] = "aim"; map[QContactOnlineAccount::ProtocolIcq] = "icq"; map[QContactOnlineAccount::ProtocolIrc] = "irc"; map[QContactOnlineAccount::ProtocolJabber] = "jabber"; map[QContactOnlineAccount::ProtocolMsn] = "msn"; map[QContactOnlineAccount::ProtocolQq] = "qq"; map[QContactOnlineAccount::ProtocolSkype] = "skype"; map[QContactOnlineAccount::ProtocolYahoo] = "yahoo"; map[QContactOnlineAccount::ProtocolUnknown] = "unknown"; } if (map.contains(protocol)) { return map[protocol]; } else { qWarning() << "invalid IM protocol" << protocol; } return map[QContactOnlineAccount::ProtocolUnknown]; } QStringList DetailContextParser::listParameters(FolksAbstractFieldDetails *details) { static QStringList whiteList; if (whiteList.isEmpty()) { whiteList << "x-evolution-ui-slot" << "x-google-label"; } GeeMultiMap *map = folks_abstract_field_details_get_parameters(details); GeeSet *keys = gee_multi_map_get_keys(map); GeeIterator *siter = gee_iterable_iterator(GEE_ITERABLE(keys)); QStringList params; while (gee_iterator_next (siter)) { char *parameter = (char*) gee_iterator_get(siter); if (QString::fromUtf8(parameter).toUpper() == VCardParser::PrefParamName) { params << "pref"; continue; } else if (QString::fromUtf8(parameter) != "type") { if (!whiteList.contains(QString::fromUtf8(parameter))) { qDebug() << "not suported field details" << parameter; // FIXME: check what to do with other parameters } continue; } GeeCollection *args = folks_abstract_field_details_get_parameter_values(details, parameter); GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE (args)); while (gee_iterator_next (iter)) { char *type = (char*) gee_iterator_get(iter); QString context(QString::fromUtf8(type).toLower()); if (!params.contains(context)) { params << context; } g_free(type); } g_free(parameter); g_object_unref(iter); } g_object_unref(siter); return params; } void DetailContextParser::parseParameters(QtContacts::QContactDetail &detail, FolksAbstractFieldDetails *fd, bool *isPref) { QStringList params = listParameters(fd); if (isPref) { *isPref = params.contains(VCardParser::PrefParamName.toLower()); if (*isPref) { params.removeOne(VCardParser::PrefParamName.toLower()); } } QList context = contextsFromParameters(¶ms); if (!context.isEmpty()) { detail.setContexts(context); } switch (detail.type()) { case QContactDetail::TypePhoneNumber: parsePhoneParameters(detail, params); break; case QContactDetail::TypeAddress: parseAddressParameters(detail, params); break; case QContactDetail::TypeOnlineAccount: parseOnlineAccountParameters(detail, params); break; case QContactDetail::TypeUrl: case QContactDetail::TypeEmailAddress: case QContactDetail::TypeOrganization: default: break; } } QList DetailContextParser::contextsFromParameters(QStringList *parameters) { static QMap map; // populate the map once if (map.isEmpty()) { map["home"] = QContactDetail::ContextHome; map["work"] = QContactDetail::ContextWork; map["other"] = QContactDetail::ContextOther; } QList values; QStringList accepted; Q_FOREACH(const QString ¶m, *parameters) { if (map.contains(param.toLower())) { accepted << param; values << map[param.toLower()]; } } Q_FOREACH(const QString ¶m, accepted) { parameters->removeOne(param); } return values; } void DetailContextParser::parsePhoneParameters(QtContacts::QContactDetail &phone, const QStringList ¶ms) { // populate the map once static QMap mapTypes; if (mapTypes.isEmpty()) { mapTypes["landline"] = QContactPhoneNumber::SubTypeLandline; mapTypes["mobile"] = QContactPhoneNumber::SubTypeMobile; mapTypes["cell"] = QContactPhoneNumber::SubTypeMobile; mapTypes["fax"] = QContactPhoneNumber::SubTypeFax; mapTypes["pager"] = QContactPhoneNumber::SubTypePager; mapTypes["voice"] = QContactPhoneNumber::SubTypeVoice; mapTypes["modem"] = QContactPhoneNumber::SubTypeModem; mapTypes["video"] = QContactPhoneNumber::SubTypeVideo; mapTypes["car"] = QContactPhoneNumber::SubTypeCar; mapTypes["bulletinboard"] = QContactPhoneNumber::SubTypeBulletinBoardSystem; mapTypes["messaging"] = QContactPhoneNumber::SubTypeMessagingCapable; mapTypes["assistant"] = QContactPhoneNumber::SubTypeAssistant; mapTypes["dtmfmenu"] = QContactPhoneNumber::SubTypeDtmfMenu; } QList subTypes; Q_FOREACH(const QString ¶m, params) { if (mapTypes.contains(param.toLower())) { subTypes << mapTypes[param.toLower()]; } else if (!param.isEmpty()) { qWarning() << "Invalid phone parameter:" << param; } } if (!subTypes.isEmpty()) { static_cast(&phone)->setSubTypes(subTypes); } } void DetailContextParser::parseAddressParameters(QtContacts::QContactDetail &address, const QStringList ¶meters) { static QMap map; // populate the map once if (map.isEmpty()) { map["parcel"] = QContactAddress::SubTypeParcel; map["postal"] = QContactAddress::SubTypePostal; map["domestic"] = QContactAddress::SubTypeDomestic; map["international"] = QContactAddress::SubTypeInternational; } QList values; Q_FOREACH(const QString ¶m, parameters) { if (map.contains(param.toLower())) { values << map[param.toLower()]; } else { qWarning() << "invalid Address subtype" << param; } } if (!values.isEmpty()) { static_cast(&address)->setSubTypes(values); } } void DetailContextParser::parseOnlineAccountParameters(QtContacts::QContactDetail &im, const QStringList ¶meters) { static QMap map; // populate the map once if (map.isEmpty()) { map["sip"] = QContactOnlineAccount::SubTypeSip; map["sipvoip"] = QContactOnlineAccount::SubTypeSipVoip; map["impp"] = QContactOnlineAccount::SubTypeImpp; map["videoshare"] = QContactOnlineAccount::SubTypeVideoShare; } QSet values; Q_FOREACH(const QString ¶m, parameters) { if (map.contains(param.toLower())) { values << map[param.toLower()]; } else { qWarning() << "invalid IM subtype" << param; } } // Make compatible with contact importer QContactOnlineAccount *acc = static_cast(&im); if (acc->protocol() == QContactOnlineAccount::ProtocolJabber) { values << QContactOnlineAccount::SubTypeImpp; } else if (acc->protocol() == QContactOnlineAccount::ProtocolJabber) { values << QContactOnlineAccount::SubTypeSip; } if (!values.isEmpty()) { static_cast(&im)->setSubTypes(values.toList()); } } int DetailContextParser::accountProtocolFromString(const QString &protocol) { static QMap map; // populate the map once if (map.isEmpty()) { map["aim"] = QContactOnlineAccount::ProtocolAim; map["icq"] = QContactOnlineAccount::ProtocolIcq; map["irc"] = QContactOnlineAccount::ProtocolIrc; map["jabber"] = QContactOnlineAccount::ProtocolJabber; map["msn"] = QContactOnlineAccount::ProtocolMsn; map["qq"] = QContactOnlineAccount::ProtocolQq; map["skype"] = QContactOnlineAccount::ProtocolSkype; map["yahoo"] = QContactOnlineAccount::ProtocolYahoo; } if (map.contains(protocol.toLower())) { return map[protocol.toLower()]; } else { qWarning() << "invalid IM protocol" << protocol; } return QContactOnlineAccount::ProtocolUnknown; } } // namespace address-book-service-0.1.1+14.04.20140408.3/lib/qindividual.h0000644000015301777760000002150712321057334023522 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_QINDIVIDUAL_H__ #define __GALERA_QINDIVIDUAL_H__ #include #include #include #include #include #include #include #include namespace galera { typedef GHashTable* (*ParseDetailsFunc)(GHashTable*, const QList &); class UpdateContactRequest; class QIndividual { public: QIndividual(FolksIndividual *individual, FolksIndividualAggregator *aggregator); ~QIndividual(); QString id() const; QtContacts::QContact &contact(); QtContacts::QContact copy(QList fields); bool update(const QString &vcard, QObject *object, const char *slot); bool update(const QtContacts::QContact &contact, QObject *object, const char *slot); void setIndividual(FolksIndividual *individual); FolksIndividual *individual() const; QList personas() const; void addListener(QObject *object, const char *slot); bool isValid() const; void flush(); static GHashTable *parseDetails(const QtContacts::QContact &contact); // enable or disable auto-link static void enableAutoLink(bool flag); static bool autoLinkEnabled(); private: FolksIndividual *m_individual; FolksIndividualAggregator *m_aggregator; QtContacts::QContact *m_contact; UpdateContactRequest *m_currentUpdate; QList > m_listeners; QMap m_personas; QList m_notifyConnections; QString m_id; QMetaObject::Connection m_updateConnection; QMutex m_contactLock; static bool m_autoLink; QIndividual(); QIndividual(const QIndividual &); void notifyUpdate(); QMultiHash parseDetails(FolksAbstractFieldDetails *details) const; void markAsDirty(); void updateContact(QtContacts::QContact *contact) const; void updatePersonas(); void clearPersonas(); void clear(); FolksPersona *primaryPersona(); QtContacts::QContactDetail detailFromUri(QtContacts::QContactDetail::DetailType type, const QString &uri) const; void appendDetailsForPersona(QtContacts::QContact *contact, const QtContacts::QContactDetail &detail, bool readOnly) const; void appendDetailsForPersona(QtContacts::QContact *contact, QList details, const QString &preferredAction, const QtContacts::QContactDetail &preferred, bool readOnly) const; // QContact QtContacts::QContactDetail getUid() const; QList getSyncTargets() const; QtContacts::QContactDetail getPersonaName (FolksPersona *persona, int index) const; QtContacts::QContactDetail getPersonaFullName (FolksPersona *persona, int index) const; QtContacts::QContactDetail getPersonaNickName (FolksPersona *persona, int index) const; QtContacts::QContactDetail getPersonaBirthday (FolksPersona *persona, int index) const; QtContacts::QContactDetail getPersonaPhoto (FolksPersona *persona, int index) const; QtContacts::QContactDetail getPersonaFavorite (FolksPersona *persona, int index) const; QList getPersonaRoles (FolksPersona *persona, QtContacts::QContactDetail *preferredRole, int index) const; QList getPersonaEmails (FolksPersona *persona, QtContacts::QContactDetail *preferredEmail, int index) const; QList getPersonaPhones (FolksPersona *persona, QtContacts::QContactDetail *preferredPhone, int index) const; QList getPersonaAddresses(FolksPersona *persona, QtContacts::QContactDetail *preferredAddress, int index) const; QList getPersonaIms (FolksPersona *persona, QtContacts::QContactDetail *preferredIm, int index) const; QList getPersonaUrls (FolksPersona *persona, QtContacts::QContactDetail *preferredUrl, int index) const; static void avatarCacheStoreDone(GObject *source, GAsyncResult *result, gpointer data); // create void createPersonaFromDetails(QList detail, ParseDetailsFunc parseFunc, void *data) const; static void createPersonaForDetailDone(GObject *detail, GAsyncResult *result, gpointer userdata); // translate details static GHashTable *parseFullNameDetails (GHashTable *details, const QList &cDetails); static GHashTable *parseNicknameDetails (GHashTable *details, const QList &cDetails); static GHashTable *parseNameDetails (GHashTable *details, const QList &cDetails); static GHashTable *parseGenderDetails (GHashTable *details, const QList &cDetails); static GHashTable *parseFavoriteDetails (GHashTable *details, const QList &cDetails); static GHashTable *parsePhotoDetails (GHashTable *details, const QList &cDetails); static GHashTable *parseBirthdayDetails (GHashTable *details, const QList &cDetails); static GHashTable *parseAddressDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); static GHashTable *parsePhoneNumbersDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); static GHashTable *parseOrganizationDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); static GHashTable *parseImDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); static GHashTable *parseNoteDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); static GHashTable *parseEmailDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); static GHashTable *parseUrlDetails (GHashTable *details, const QList &cDetails, const QtContacts::QContactDetail &prefDetail); // property changed static void folksIndividualChanged (FolksIndividual *individual, GParamSpec *pspec, QIndividual *self); }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/addressbook.h0000644000015301777760000001232512321057334023507 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_ADDRESSBOOK_H__ #define __GALERA_ADDRESSBOOK_H__ #include "common/source.h" #include #include #include #include #include #include #include #include #include namespace galera { class View; class ContactsMap; class AddressBookAdaptor; class QIndividual; class DirtyContactsNotify; class AddressBook: public QObject { Q_OBJECT public: AddressBook(QObject *parent=0); virtual ~AddressBook(); static QString objectPath(); bool start(QDBusConnection connection); // Adaptor QString linkContacts(const QStringList &contacts); View *query(const QString &clause, const QString &sort, const QStringList &sources); QStringList sortFields(); bool unlinkContacts(const QString &parent, const QStringList &contacts); bool isReady() const; static int init(); Q_SIGNALS: void stopped(); public Q_SLOTS: bool start(); void shutdown(); SourceList availableSources(const QDBusMessage &message); Source source(const QDBusMessage &message); Source createSource(const QString &sourceId, const QDBusMessage &message); QString createContact(const QString &contact, const QString &source, const QDBusMessage &message); int removeContacts(const QStringList &contactIds, const QDBusMessage &message); QStringList updateContacts(const QStringList &contacts, const QDBusMessage &message); void updateContactsDone(const QString &contactId, const QString &error); private Q_SLOTS: void viewClosed(); void individualChanged(QIndividual *individual); // Unix signal handlers. void handleSigQuit(); private: FolksIndividualAggregator *m_individualAggregator; ContactsMap *m_contacts; QSet m_views; AddressBookAdaptor *m_adaptor; // timer to avoid send several updates at the same time DirtyContactsNotify *m_notifyContactUpdate; bool m_ready; int m_individualsChangedDetailedId; int m_notifyIsQuiescentHandlerId; QDBusConnection m_connection; // Update command QDBusMessage m_updateCommandReplyMessage; QStringList m_updateCommandResult; QStringList m_updatedIds; QStringList m_updateCommandPendingContacts; // Unix signals static int m_sigQuitFd[2]; QSocketNotifier *m_snQuit; // Disable copy contructor AddressBook(const AddressBook&); void getSource(const QDBusMessage &message, bool onlyTheDefault); void setupUnixSignals(); // Unix signal handlers. void prepareUnixSignals(); static void quitSignalHandler(int unused); void prepareFolks(); bool registerObject(QDBusConnection &connection); QString removeContact(FolksIndividual *individual); QString addContact(FolksIndividual *individual); FolksPersonaStore *getFolksStore(const QString &source); static void availableSourcesDoneListAllSources(FolksBackendStore *backendStore, GAsyncResult *res, QDBusMessage *msg); static void availableSourcesDoneListDefaultSource(FolksBackendStore *backendStore, GAsyncResult *res, QDBusMessage *msg); static SourceList availableSourcesDoneImpl(FolksBackendStore *backendStore, GAsyncResult *res); static void individualsChangedCb(FolksIndividualAggregator *individualAggregator, GeeMultiMap *changes, AddressBook *self); static void isQuiescentChanged(GObject *source, GParamSpec *param, AddressBook *self); static void prepareFolksDone(GObject *source, GAsyncResult *res, AddressBook *self); static void createContactDone(FolksIndividualAggregator *individualAggregator, GAsyncResult *res, void *data); static void removeContactDone(FolksIndividualAggregator *individualAggregator, GAsyncResult *result, void *data); static void createSourceDone(GObject *source, GAsyncResult *res, void *data); friend class DirtyContactsNotify; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/view-adaptor.cpp0000644000015301777760000000352212321057324024142 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "view-adaptor.h" #include "view.h" namespace galera { ViewAdaptor::ViewAdaptor(const QDBusConnection &connection, View *parent) : QDBusAbstractAdaptor(parent), m_view(parent), m_connection(connection) { setAutoRelaySignals(true); } ViewAdaptor::~ViewAdaptor() { } QString ViewAdaptor::contactDetails(const QStringList &fields, const QString &id) { return m_view->contactDetails(fields, id); } QStringList ViewAdaptor::contactsDetails(const QStringList &fields, int startIndex, int pageSize, const QDBusMessage &message) { message.setDelayedReply(true); QMetaObject::invokeMethod(m_view, "contactsDetails", Qt::QueuedConnection, Q_ARG(const QStringList&, fields), Q_ARG(int, startIndex), Q_ARG(int, pageSize), Q_ARG(const QDBusMessage&, message)); return QStringList(); } int ViewAdaptor::count() { return m_view->count(); } void ViewAdaptor::sort(const QString &field) { return m_view->sort(field); } void ViewAdaptor::close() { return m_view->close(); } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/gee-utils.cpp0000644000015301777760000000363512321057324023443 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "gee-utils.h" #include GValue* GeeUtils::gValueSliceNew(GType type) { GValue *retval = g_slice_new0(GValue); g_value_init(retval, type); return retval; } void GeeUtils::gValueSliceFree(GValue *value) { g_value_unset(value); g_slice_free(GValue, value); } void GeeUtils::personaDetailsInsert(GHashTable *details, FolksPersonaDetail key, gpointer value) { g_hash_table_insert(details, (gpointer) folks_persona_store_detail_key(key), value); } GValue* GeeUtils::asvSetStrNew(QMultiMap providerUidMap) { GeeMultiMap *hashSet = GEE_MULTI_MAP_AFD_NEW(FOLKS_TYPE_IM_FIELD_DETAILS); GValue *retval = gValueSliceNew (G_TYPE_OBJECT); g_value_take_object (retval, hashSet); QList keys = providerUidMap.keys(); Q_FOREACH(const QString& key, keys) { QList values = providerUidMap.values(key); Q_FOREACH(const QString& value, values) { FolksImFieldDetails *imfd; imfd = folks_im_field_details_new (value.toUtf8().data(), NULL); gee_multi_map_set(hashSet, key.toUtf8().data(), imfd); g_object_unref(imfd); } } return retval; } address-book-service-0.1.1+14.04.20140408.3/lib/detail-context-parser.h0000644000015301777760000000417712321057324025432 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_DETAIL_CONTEXT_PARSER_H__ #define __GALERA_DETAIL_CONTEXT_PARSER_H__ #include #include #include namespace galera { class DetailContextParser { public: static void parseContext(FolksAbstractFieldDetails *fd, const QtContacts::QContactDetail &detail, bool isPreffered); static QStringList parseContext(const QtContacts::QContactDetail &detail); static QStringList listContext(const QtContacts::QContactDetail &detail); static QStringList parsePhoneContext(const QtContacts::QContactDetail &detail); static QStringList parseAddressContext(const QtContacts::QContactDetail &detail); static QStringList parseOnlineAccountContext(const QtContacts::QContactDetail &im); static QString accountProtocolName(int protocol); static QStringList listParameters(FolksAbstractFieldDetails *details); static void parseParameters(QtContacts::QContactDetail &detail, FolksAbstractFieldDetails *fd, bool *isPref); static QList contextsFromParameters(QStringList *parameters); static void parsePhoneParameters(QtContacts::QContactDetail &phone, const QStringList ¶ms); static void parseAddressParameters(QtContacts::QContactDetail &address, const QStringList ¶meters); static int accountProtocolFromString(const QString &protocol); static void parseOnlineAccountParameters(QtContacts::QContactDetail &im, const QStringList ¶meters); }; } #endif address-book-service-0.1.1+14.04.20140408.3/lib/CMakeLists.txt0000644000015301777760000000213112321057324023567 0ustar pbusernogroup00000000000000project(address-book-service-lib) set(CONTACTS_SERVICE_LIB address-book-service-lib) set(CONTACTS_SERVICE_LIB_SRC addressbook.cpp addressbook-adaptor.cpp contacts-map.cpp detail-context-parser.cpp dirtycontact-notify.cpp gee-utils.cpp qindividual.cpp update-contact-request.cpp view.cpp view-adaptor.cpp ) set(CONTACTS_SERVICE_LIB_HEADERS addressbook.h addressbook-adaptor.h contacts-map.h detail-context-parser.h dirtycontact-notify.h gee-utils.h qindividual.h update-contact-request.h view.h view-adaptor.h ) add_library(${CONTACTS_SERVICE_LIB} STATIC ${CONTACTS_SERVICE_LIB_SRC} ${CONTACTS_SERVICE_LIB_HEADERS} ) target_link_libraries(${CONTACTS_SERVICE_LIB} galera-common ${GLIB_LIBRARIES} ${GIO_LIBRARIES} ${FOLKS_LIBRARIES} ${FOLKS_EDS_LIBRARIES} ) qt5_use_modules(${CONTACTS_SERVICE_LIB} Core Contacts DBus Versit) include_directories( ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${GLIB_INCLUDE_DIRS} ${GIO_INCLUDE_DIRS} ${FOLKS_INCLUDE_DIRS} ${FOLKS_EDS_INCLUDE_DIRS} ) address-book-service-0.1.1+14.04.20140408.3/lib/addressbook.cpp0000644000015301777760000006523212321057334024047 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "config.h" #include "addressbook.h" #include "addressbook-adaptor.h" #include "view.h" #include "contacts-map.h" #include "qindividual.h" #include "dirtycontact-notify.h" #include "common/vcard-parser.h" #include #include #include #include #include using namespace QtContacts; namespace { class CreateContactData { public: QDBusMessage m_message; galera::AddressBook *m_addressbook; }; class UpdateContactsData { public: QList m_contacts; QStringList m_request; int m_currentIndex; QStringList m_result; galera::AddressBook *m_addressbook; QDBusMessage m_message; }; class RemoveContactsData { public: QStringList m_request; galera::AddressBook *m_addressbook; QDBusMessage m_message; int m_sucessCount; }; class CreateSourceData { public: QString sourceName; galera::AddressBook *m_addressbook; QDBusMessage m_message; }; } namespace galera { int AddressBook::m_sigQuitFd[2] = {0, 0}; AddressBook::AddressBook(QObject *parent) : QObject(parent), m_individualAggregator(0), m_contacts(new ContactsMap), m_adaptor(0), m_notifyContactUpdate(0), m_ready(false), m_individualsChangedDetailedId(0), m_notifyIsQuiescentHandlerId(0), m_connection(QDBusConnection::sessionBus()) { prepareUnixSignals(); } AddressBook::~AddressBook() { shutdown(); // destructor if (m_notifyContactUpdate) { delete m_notifyContactUpdate; m_notifyContactUpdate = 0; } } QString AddressBook::objectPath() { return CPIM_ADDRESSBOOK_OBJECT_PATH; } bool AddressBook::registerObject(QDBusConnection &connection) { if (connection.interface()->isServiceRegistered(CPIM_SERVICE_NAME)) { qWarning() << "Galera pin service already registered"; return false; } else if (!connection.registerService(CPIM_SERVICE_NAME)) { qWarning() << "Could not register service!" << CPIM_SERVICE_NAME; return false; } if (!m_adaptor) { m_adaptor = new AddressBookAdaptor(connection, this); if (!connection.registerObject(galera::AddressBook::objectPath(), this)) { qWarning() << "Could not register object!" << objectPath(); delete m_adaptor; m_adaptor = 0; if (m_notifyContactUpdate) { delete m_notifyContactUpdate; m_notifyContactUpdate = 0; } } } if (m_adaptor) { m_notifyContactUpdate = new DirtyContactsNotify(m_adaptor); } return (m_adaptor != 0); } bool AddressBook::start(QDBusConnection connection) { if (registerObject(connection)) { m_connection = connection; prepareFolks(); return true; } return false; } bool AddressBook::start() { return start(QDBusConnection::sessionBus()); } void AddressBook::shutdown() { m_ready = false; Q_FOREACH(View* view, m_views) { view->close(); } m_views.clear(); if (m_contacts) { delete m_contacts; m_contacts = 0; } if (m_individualAggregator) { g_signal_handler_disconnect(m_individualAggregator, m_individualsChangedDetailedId); g_signal_handler_disconnect(m_individualAggregator, m_notifyIsQuiescentHandlerId); m_individualsChangedDetailedId = m_notifyIsQuiescentHandlerId = 0; g_clear_object(&m_individualAggregator); } if (m_adaptor) { if (m_connection.interface() && m_connection.interface()->isValid()) { m_connection.unregisterObject(objectPath()); if (m_connection.interface()->isServiceRegistered(CPIM_SERVICE_NAME)) { m_connection.unregisterService(CPIM_SERVICE_NAME); } } delete m_adaptor; m_adaptor = 0; Q_EMIT stopped(); } } void AddressBook::prepareFolks() { m_individualAggregator = folks_individual_aggregator_dup(); g_object_get(G_OBJECT(m_individualAggregator), "is-quiescent", &m_ready, NULL); if (m_ready) { AddressBook::isQuiescentChanged(G_OBJECT(m_individualAggregator), NULL, this); } m_notifyIsQuiescentHandlerId = g_signal_connect(m_individualAggregator, "notify::is-quiescent", (GCallback)AddressBook::isQuiescentChanged, this); m_individualsChangedDetailedId = g_signal_connect(m_individualAggregator, "individuals-changed-detailed", (GCallback) AddressBook::individualsChangedCb, this); folks_individual_aggregator_prepare(m_individualAggregator, (GAsyncReadyCallback) AddressBook::prepareFolksDone, this); } SourceList AddressBook::availableSources(const QDBusMessage &message) { getSource(message, false); return SourceList(); } Source AddressBook::source(const QDBusMessage &message) { getSource(message, true); return Source(); } Source AddressBook::createSource(const QString &sourceId, const QDBusMessage &message) { CreateSourceData *data = new CreateSourceData; data->m_addressbook = this; data->m_message = message; data->sourceName = sourceId; FolksPersonaStore *store = folks_individual_aggregator_get_primary_store(m_individualAggregator); QString personaStoreTypeId = QString::fromUtf8(folks_persona_store_get_type_id (store)); if ( personaStoreTypeId == "dummy") { FolksBackendStore *backendStore = folks_backend_store_dup(); FolksBackend *dummy = folks_backend_store_dup_backend_by_name(backendStore, "dummy"); GeeMap *stores = folks_backend_get_persona_stores(dummy); GeeSet *storesKeys = gee_map_get_keys(stores); GeeSet *storesIds = (GeeSet*) gee_hash_set_new(G_TYPE_STRING, (GBoxedCopyFunc) g_strdup, g_free, NULL, NULL, NULL, NULL, NULL, NULL); gee_collection_add_all(GEE_COLLECTION(storesIds), GEE_COLLECTION(storesKeys)); gee_collection_add(GEE_COLLECTION(storesIds), sourceId.toUtf8().constData()); folks_backend_set_persona_stores(dummy, storesIds); g_object_unref(storesIds); g_object_unref(backendStore); g_object_unref(dummy); Source src(sourceId, sourceId, false, false); QDBusMessage reply = message.createReply(QVariant::fromValue(src)); QDBusConnection::sessionBus().send(reply); } else if (personaStoreTypeId == "eds") { edsf_persona_store_create_address_book(sourceId.toUtf8().data(), (GAsyncReadyCallback) AddressBook::createSourceDone, data); } else { qWarning() << "Not supported, create sources on persona store with type id:" << personaStoreTypeId; } return Source(); } void AddressBook::createSourceDone(GObject *source, GAsyncResult *res, void *data) { CreateSourceData *cData = static_cast(data); GError *error = 0; Source src; edsf_persona_store_create_address_book_finish(res, &error); if (error) { qWarning() << "Fail to create source" << error->message; g_error_free(error); } else { src = Source(cData->sourceName, cData->sourceName, false, false); } QDBusMessage reply = cData->m_message.createReply(QVariant::fromValue(src)); QDBusConnection::sessionBus().send(reply); delete cData; } void AddressBook::getSource(const QDBusMessage &message, bool onlyTheDefault) { FolksBackendStore *backendStore = folks_backend_store_dup(); QDBusMessage *msg = new QDBusMessage(message); if (folks_backend_store_get_is_prepared(backendStore)) { if (onlyTheDefault) { availableSourcesDoneListDefaultSource(backendStore, 0, msg); } else { availableSourcesDoneListAllSources(backendStore, 0, msg); } } else { if (onlyTheDefault) { folks_backend_store_prepare(backendStore, (GAsyncReadyCallback) availableSourcesDoneListDefaultSource, msg); } else { folks_backend_store_prepare(backendStore, (GAsyncReadyCallback) availableSourcesDoneListAllSources, msg); } } g_object_unref(backendStore); } void AddressBook::availableSourcesDoneListAllSources(FolksBackendStore *backendStore, GAsyncResult *res, QDBusMessage *msg) { SourceList list = availableSourcesDoneImpl(backendStore, res); QDBusMessage reply = msg->createReply(QVariant::fromValue(list)); QDBusConnection::sessionBus().send(reply); delete msg; } void AddressBook::availableSourcesDoneListDefaultSource(FolksBackendStore *backendStore, GAsyncResult *res, QDBusMessage *msg) { Source defaultSource; SourceList list = availableSourcesDoneImpl(backendStore, res); if (list.count() > 0) { defaultSource = list[0]; } QDBusMessage reply = msg->createReply(QVariant::fromValue(defaultSource)); QDBusConnection::sessionBus().send(reply); delete msg; } SourceList AddressBook::availableSourcesDoneImpl(FolksBackendStore *backendStore, GAsyncResult *res) { if (res) { folks_backend_store_prepare_finish(backendStore, res); } static QStringList backendBlackList; // these backends are not fully supported yet if (backendBlackList.isEmpty()) { backendBlackList << "telepathy" << "bluez" << "ofono" << "key-file"; } GeeCollection *backends = folks_backend_store_list_backends(backendStore); SourceList result; GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(backends)); while(gee_iterator_next(iter)) { FolksBackend *backend = FOLKS_BACKEND(gee_iterator_get(iter)); QString backendName = QString::fromUtf8(folks_backend_get_name(backend)); if (backendBlackList.contains(backendName)) { continue; } GeeMap *stores = folks_backend_get_persona_stores(backend); GeeCollection *values = gee_map_get_values(stores); GeeIterator *backendIter = gee_iterable_iterator(GEE_ITERABLE(values)); while(gee_iterator_next(backendIter)) { FolksPersonaStore *store = FOLKS_PERSONA_STORE(gee_iterator_get(backendIter)); QString id = QString::fromUtf8(folks_persona_store_get_id(store)); QString displayName = QString::fromUtf8(folks_persona_store_get_display_name(store)); bool canWrite = folks_persona_store_get_can_add_personas(store) && folks_persona_store_get_can_remove_personas(store); bool isPrimary = folks_persona_store_get_is_primary_store(store); result << Source(id, displayName, !canWrite, isPrimary); g_object_unref(store); } g_object_unref(backendIter); g_object_unref(backend); g_object_unref(values); } g_object_unref(iter); return result; } QString AddressBook::createContact(const QString &contact, const QString &source, const QDBusMessage &message) { ContactEntry *entry = m_contacts->valueFromVCard(contact); if (entry) { qWarning() << "Contact exists"; } else { QContact qcontact = VCardParser::vcardToContact(contact); if (!qcontact.isEmpty()) { if (!qcontact.isEmpty()) { GHashTable *details = QIndividual::parseDetails(qcontact); CreateContactData *data = new CreateContactData; data->m_message = message; data->m_addressbook = this; FolksPersonaStore *store = getFolksStore(source); folks_individual_aggregator_add_persona_from_details(m_individualAggregator, NULL, //parent store, details, (GAsyncReadyCallback) createContactDone, (void*) data); g_hash_table_destroy(details); g_object_unref(store); return ""; } } } QDBusMessage reply = message.createReply(QString()); QDBusConnection::sessionBus().send(reply); return ""; } FolksPersonaStore * AddressBook::getFolksStore(const QString &source) { FolksPersonaStore *result = 0; if (!source.isEmpty()) { FolksBackendStore *backendStore = folks_backend_store_dup(); GeeCollection *backends = folks_backend_store_list_backends(backendStore); GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(backends)); while((result == 0) && gee_iterator_next(iter)) { FolksBackend *backend = FOLKS_BACKEND(gee_iterator_get(iter)); GeeMap *stores = folks_backend_get_persona_stores(backend); GeeCollection *values = gee_map_get_values(stores); GeeIterator *backendIter = gee_iterable_iterator(GEE_ITERABLE(values)); while(gee_iterator_next(backendIter)) { FolksPersonaStore *store = FOLKS_PERSONA_STORE(gee_iterator_get(backendIter)); QString id = QString::fromUtf8(folks_persona_store_get_id(store)); if (id == source) { result = store; break; } g_object_unref(store); } g_object_unref(backendIter); g_object_unref(backend); g_object_unref(values); } g_object_unref(iter); g_object_unref(backendStore); } if (!result) { result = folks_individual_aggregator_get_primary_store(m_individualAggregator); g_object_ref(result); } return result; } QString AddressBook::linkContacts(const QStringList &contacts) { //TODO return ""; } View *AddressBook::query(const QString &clause, const QString &sort, const QStringList &sources) { // wait for the service be ready for queries while(!m_ready) { QCoreApplication::processEvents(); } View *view = new View(clause, sort, sources, m_contacts, this); m_views << view; connect(view, SIGNAL(closed()), this, SLOT(viewClosed())); return view; } void AddressBook::viewClosed() { m_views.remove(qobject_cast(QObject::sender())); } void AddressBook::individualChanged(QIndividual *individual) { m_notifyContactUpdate->insertChangedContacts(QSet() << individual->id()); } int AddressBook::removeContacts(const QStringList &contactIds, const QDBusMessage &message) { RemoveContactsData *data = new RemoveContactsData; data->m_addressbook = this; data->m_message = message; data->m_request = contactIds; data->m_sucessCount = 0; removeContactDone(0, 0, data); return 0; } void AddressBook::removeContactDone(FolksIndividualAggregator *individualAggregator, GAsyncResult *result, void *data) { GError *error = 0; RemoveContactsData *removeData = static_cast(data); if (result) { folks_individual_aggregator_remove_individual_finish(individualAggregator, result, &error); if (error) { qWarning() << "Fail to remove contact:" << error->message; g_error_free(error); } else { removeData->m_sucessCount++; } } if (!removeData->m_request.isEmpty()) { QString contactId = removeData->m_request.takeFirst(); ContactEntry *entry = removeData->m_addressbook->m_contacts->value(contactId); if (entry) { folks_individual_aggregator_remove_individual(individualAggregator, entry->individual()->individual(), (GAsyncReadyCallback) removeContactDone, data); } else { removeContactDone(individualAggregator, 0, data); } } else { QDBusMessage reply = removeData->m_message.createReply(removeData->m_sucessCount); QDBusConnection::sessionBus().send(reply); delete removeData; } } QStringList AddressBook::sortFields() { return SortClause::supportedFields(); } bool AddressBook::unlinkContacts(const QString &parent, const QStringList &contacts) { //TODO return false; } bool AddressBook::isReady() const { return m_ready; } QStringList AddressBook::updateContacts(const QStringList &contacts, const QDBusMessage &message) { //TODO: support multiple update contacts calls Q_ASSERT(m_updateCommandPendingContacts.isEmpty()); m_updatedIds.clear(); m_updateCommandReplyMessage = message; m_updateCommandResult = contacts; m_updateCommandPendingContacts = contacts; updateContactsDone("", ""); return QStringList(); } void AddressBook::updateContactsDone(const QString &contactId, const QString &error) { qDebug() << Q_FUNC_INFO; int currentContactIndex = m_updateCommandResult.size() - m_updateCommandPendingContacts.size() - 1; if (!error.isEmpty()) { // update the result with the error m_updateCommandResult[currentContactIndex] = error; } else if (!contactId.isEmpty()){ // update the result with the new contact info ContactEntry *entry = m_contacts->value(contactId); Q_ASSERT(entry); m_updatedIds << contactId; QContact contact = entry->individual()->contact(); QString vcard = VCardParser::contactToVcard(contact); if (!vcard.isEmpty()) { m_updateCommandResult[currentContactIndex] = vcard; } else { m_updateCommandResult[currentContactIndex] = ""; } } if (!m_updateCommandPendingContacts.isEmpty()) { QContact newContact = VCardParser::vcardToContact(m_updateCommandPendingContacts.takeFirst()); ContactEntry *entry = m_contacts->value(newContact.detail().guid()); if (entry) { entry->individual()->update(newContact, this, SLOT(updateContactsDone(QString,QString))); } else { updateContactsDone("", "Contact not found!"); } } else { QDBusMessage reply = m_updateCommandReplyMessage.createReply(m_updateCommandResult); QDBusConnection::sessionBus().send(reply); // notify about the changes m_notifyContactUpdate->insertChangedContacts(m_updatedIds.toSet()); // clear command data m_updatedIds.clear(); m_updateCommandResult.clear(); m_updateCommandReplyMessage = QDBusMessage(); } } QString AddressBook::removeContact(FolksIndividual *individual) { QString contactId = QString::fromUtf8(folks_individual_get_id(individual)); ContactEntry *ci = m_contacts->take(contactId); if (ci) { delete ci; return contactId; } return QString(); } QString AddressBook::addContact(FolksIndividual *individual) { QString id = QString::fromUtf8(folks_individual_get_id(individual)); ContactEntry *entry = m_contacts->value(id); if (entry) { entry->individual()->setIndividual(individual); } else { QIndividual *i = new QIndividual(individual, m_individualAggregator); i->addListener(this, SLOT(individualChanged(QIndividual*))); m_contacts->insert(new ContactEntry(i)); //TODO: Notify view } return id; } void AddressBook::individualsChangedCb(FolksIndividualAggregator *individualAggregator, GeeMultiMap *changes, AddressBook *self) { qDebug() << Q_FUNC_INFO; Q_UNUSED(individualAggregator); QSet removedIds; QSet addedIds; QSet updatedIds; QSet ignoreIds; GeeSet *keys = gee_multi_map_get_keys(changes); GeeIterator *iter = gee_iterable_iterator(GEE_ITERABLE(keys)); while(gee_iterator_next(iter)) { FolksIndividual *individualKey = FOLKS_INDIVIDUAL(gee_iterator_get(iter)); GeeCollection *values = gee_multi_map_get(changes, individualKey); GeeIterator *iterV; iterV = gee_iterable_iterator(GEE_ITERABLE(values)); while(gee_iterator_next(iterV)) { FolksIndividual *individualValue = FOLKS_INDIVIDUAL(gee_iterator_get(iterV)); // contact added if (individualKey == 0) { addedIds << self->addContact(individualValue); } else if (individualValue != 0) { QString idValue = QString::fromUtf8(folks_individual_get_id(individualValue)); QString idKey = QString::fromUtf8(folks_individual_get_id(individualKey)); // after adding a anti link folks emit a signal with the same value in both key and value, // we can ignore this if (idValue == idKey) { // individual object has changed ignoreIds << self->addContact(individualValue); } else { if (self->m_contacts->value(idValue)) { updatedIds << self->addContact(individualValue); } else { addedIds << self->addContact(individualValue); } } } if (individualValue) { g_object_unref(individualValue); } } g_object_unref(iterV); g_object_unref(values); if (individualKey) { QString id = QString::fromUtf8(folks_individual_get_id(individualKey)); if (!ignoreIds.contains(id) && !addedIds.contains(id) && !updatedIds.contains(id)) { removedIds << self->removeContact(individualKey); } g_object_unref(individualKey); } } g_object_unref(keys); if (!removedIds.isEmpty()) { self->m_notifyContactUpdate->insertRemovedContacts(removedIds); } if (!addedIds.isEmpty()) { self->m_notifyContactUpdate->insertAddedContacts(addedIds); } if (!updatedIds.isEmpty()) { self->m_notifyContactUpdate->insertChangedContacts(updatedIds); } } void AddressBook::prepareFolksDone(GObject *source, GAsyncResult *res, AddressBook *self) { Q_UNUSED(source); Q_UNUSED(res); Q_UNUSED(self); } void AddressBook::createContactDone(FolksIndividualAggregator *individualAggregator, GAsyncResult *res, void *data) { CreateContactData *createData = static_cast(data); FolksPersona *persona; GError *error = NULL; QDBusMessage reply; persona = folks_individual_aggregator_add_persona_from_details_finish(individualAggregator, res, &error); if (error != NULL) { qWarning() << "Failed to create individual from contact:" << error->message; reply = createData->m_message.createErrorReply("Failed to create individual from contact", error->message); g_clear_error(&error); } else if (persona == NULL) { qWarning() << "Failed to create individual from contact: Persona already exists"; reply = createData->m_message.createErrorReply("Failed to create individual from contact", "Contact already exists"); } else { FolksIndividual *individual = folks_persona_get_individual(persona); ContactEntry *entry = createData->m_addressbook->m_contacts->value(QString::fromUtf8(folks_individual_get_id(individual))); if (entry) { QString vcard = VCardParser::contactToVcard(entry->individual()->contact()); reply = createData->m_message.createReply(vcard); } else { reply = createData->m_message.createErrorReply("Failed to retrieve the new contact", error->message); } } //TODO: use dbus connection QDBusConnection::sessionBus().send(reply); delete createData; } void AddressBook::isQuiescentChanged(GObject *source, GParamSpec *param, AddressBook *self) { Q_UNUSED(source); Q_UNUSED(param); g_object_get(source, "is-quiescent", &self->m_ready, NULL); if (self->m_ready && self->m_adaptor) { Q_EMIT self->m_adaptor->ready(); } } void AddressBook::quitSignalHandler(int) { char a = 1; ::write(m_sigQuitFd[0], &a, sizeof(a)); } int AddressBook::init() { struct sigaction quit = { { 0 } }; Source::registerMetaType(); quit.sa_handler = AddressBook::quitSignalHandler; sigemptyset(&quit.sa_mask); quit.sa_flags |= SA_RESTART; if (sigaction(SIGQUIT, &quit, 0) > 0) return 1; return 0; } void AddressBook::prepareUnixSignals() { if (::socketpair(AF_UNIX, SOCK_STREAM, 0, m_sigQuitFd)) { qFatal("Couldn't create HUP socketpair"); } m_snQuit = new QSocketNotifier(m_sigQuitFd[1], QSocketNotifier::Read, this); connect(m_snQuit, SIGNAL(activated(int)), this, SLOT(handleSigQuit())); } void AddressBook::handleSigQuit() { m_snQuit->setEnabled(false); char tmp; ::read(m_sigQuitFd[1], &tmp, sizeof(tmp)); shutdown(); m_snQuit->setEnabled(true); } } //namespace address-book-service-0.1.1+14.04.20140408.3/lib/update-contact-request.cpp0000644000015301777760000010561712321057334026152 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "update-contact-request.h" #include "qindividual.h" #include "detail-context-parser.h" #include "gee-utils.h" #include "common/vcard-parser.h" #include using namespace QtContacts; namespace galera { UpdateContactRequest::UpdateContactRequest(QtContacts::QContact newContact, QIndividual *parent, QObject *listener, const char *slot) : QObject(), m_parent(parent), m_object(listener), m_currentPersona(0), m_eventLoop(0), m_newContact(newContact), m_currentPersonaIndex(0) { int slotIndex = listener->metaObject()->indexOfSlot(++slot); if (slotIndex == -1) { qWarning() << "Invalid slot:" << slot << "for object" << listener; } else { m_slot = listener->metaObject()->method(slotIndex); } } UpdateContactRequest::~UpdateContactRequest() { // check if there is a operation running if (m_currentPersona != 0) { wait(); } } void UpdateContactRequest::invokeSlot(const QString &errorMessage) { Q_EMIT done(errorMessage); if (m_slot.isValid() && m_parent) { m_slot.invoke(m_object, Q_ARG(QString, m_parent->id()), Q_ARG(QString, errorMessage)); } else if (m_parent == 0) { // the object was detached we need to destroy it deleteLater(); } if (m_eventLoop) { m_eventLoop->quit(); } } void UpdateContactRequest::start() { m_currentDetailType = QContactDetail::TypeAddress; m_originalContact = m_parent->contact(); m_personas = m_parent->personas(); m_currentPersonaIndex = 0; updatePersona(); } void UpdateContactRequest::wait() { Q_ASSERT(m_eventLoop == 0); QEventLoop eventLoop; m_eventLoop = &eventLoop; eventLoop.exec(); m_eventLoop = 0; } void UpdateContactRequest::deatach() { m_parent = 0; } void UpdateContactRequest::notifyError(const QString &errorMessage) { invokeSlot(errorMessage); } bool UpdateContactRequest::isEqual(const QtContacts::QContactDetail &detailA, const QtContacts::QContactDetail &detailB) { if (detailA.type() != detailB.type()) { return false; } switch(detailA.type()) { case QContactDetail::TypeFavorite: return detailA.value(QContactFavorite::FieldFavorite) == detailB.value(QContactFavorite::FieldFavorite); default: return (detailA == detailB); } } bool UpdateContactRequest::isEqual(QList listA, QList listB) { if (listA.size() != listB.size()) { return false; } for(int i=0; i < listA.size(); i++) { if (!isEqual(listA[i], listB[i])) { return false; } } return true; } bool UpdateContactRequest::isEqual(QList listA, const QtContacts::QContactDetail &prefA, QList listB, const QtContacts::QContactDetail &prefB) { if (prefA != prefB) { return false; } return isEqual(listA, listB); } bool UpdateContactRequest::checkPersona(QtContacts::QContactDetail &det, int persona) { if (det.detailUri().isEmpty()) { return false; } QStringList ids = det.detailUri().split("."); Q_ASSERT(ids.count() == 2); return (ids[0].toInt() == persona); } QList UpdateContactRequest::detailsFromPersona(const QtContacts::QContact &contact, QtContacts::QContactDetail::DetailType type, int persona, bool includeEmptyPersona, QtContacts::QContactDetail *pref) { QList personaDetails; QContactDetail globalPref; if (pref && VCardParser::PreferredActionNames.contains(type)) { globalPref = contact.preferredDetail(VCardParser::PreferredActionNames[type]); } Q_FOREACH(QContactDetail det, contact.details(type)) { if ((includeEmptyPersona && det.detailUri().isEmpty()) || checkPersona(det, persona)) { if (!det.isEmpty()) { personaDetails << det; if (pref && det == globalPref) { *pref = det; } } } } return personaDetails; } QList UpdateContactRequest::originalDetailsFromPersona(QtContacts::QContactDetail::DetailType type, int persona, QtContacts::QContactDetail *pref) const { return detailsFromPersona(m_originalContact, type, persona, false, pref); } QList UpdateContactRequest::detailsFromPersona(QtContacts::QContactDetail::DetailType type, int persona, QtContacts::QContactDetail *pref) const { // only return new details for the first persona, this will avoid to create the details for all personas return detailsFromPersona(m_newContact, type, persona, (persona==1), pref); } void UpdateContactRequest::updateAddress() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeAddress, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypeAddress, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_POSTAL_ADDRESS_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "Adderess diff"; GeeSet *newSet = SET_AFD_NEW(); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactAddress addr = static_cast(newDetail); FolksPostalAddress *pa; QByteArray postOfficeBox = addr.postOfficeBox().toUtf8(); QByteArray street = addr.street().toUtf8(); QByteArray locality = addr.locality().toUtf8(); QByteArray region = addr.region().toUtf8(); QByteArray postcode = addr.postcode().toUtf8(); QByteArray country = addr.country().toUtf8(); pa = folks_postal_address_new(postOfficeBox.constData(), NULL, street.constData(), locality.constData(), region.constData(), postcode.constData(), country.constData(), NULL, NULL); FolksPostalAddressFieldDetails *field = folks_postal_address_field_details_new(pa, NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), newDetail, newDetail == prefDetail); gee_collection_add(GEE_COLLECTION(newSet), field); g_object_unref(field); g_object_unref(pa); } folks_postal_address_details_change_postal_addresses(FOLKS_POSTAL_ADDRESS_DETAILS(m_currentPersona), newSet, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(newSet); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateAvatar() { QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeAvatar, m_currentPersonaIndex, 0); QList newDetails = detailsFromPersona(QContactDetail::TypeAvatar, m_currentPersonaIndex, 0); if (m_currentPersona && FOLKS_IS_AVATAR_DETAILS(m_currentPersona) && !isEqual(originalDetails, newDetails)) { qDebug() << "avatar diff:" << "\n\t" << originalDetails.size() << (originalDetails.size() > 0 ? originalDetails[0] : QContactDetail()) << "\n" << "\n\t" << newDetails.size() << (newDetails.size() > 0 ? newDetails[0] : QContactDetail()); //Only supports one avatar QUrl avatarUri; QUrl oldAvatarUri; if (originalDetails.count()) { QContactAvatar avatar = static_cast(originalDetails[0]); oldAvatarUri = avatar.imageUrl(); } if (newDetails.count()) { QContactAvatar avatar = static_cast(newDetails[0]); avatarUri = avatar.imageUrl(); } if (avatarUri != oldAvatarUri) { GFileIcon *avatarFileIcon = NULL; if(!avatarUri.isEmpty()) { QString formattedUri = avatarUri.toString(QUrl::RemoveUserInfo); if(!formattedUri.isEmpty()) { QByteArray uriUtf8 = formattedUri.toUtf8(); GFile *avatarFile = g_file_new_for_uri(uriUtf8.constData()); avatarFileIcon = G_FILE_ICON(g_file_icon_new(avatarFile)); g_object_unref(avatarFile); } } folks_avatar_details_change_avatar(FOLKS_AVATAR_DETAILS(m_currentPersona), G_LOADABLE_ICON(avatarFileIcon), (GAsyncReadyCallback) updateDetailsDone, this); if (avatarFileIcon) { g_object_unref(avatarFileIcon); } } } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateBirthday() { QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeBirthday, m_currentPersonaIndex, 0); QList newDetails = detailsFromPersona(QContactDetail::TypeBirthday, m_currentPersonaIndex, 0); if (m_currentPersona && FOLKS_IS_BIRTHDAY_DETAILS(m_currentPersona) && !isEqual(originalDetails, newDetails)) { qDebug() << "birthday diff"; //Only supports one birthday QDateTime dateTimeBirthday; if (newDetails.count()) { QContactBirthday birthday = static_cast(newDetails[0]); if (!birthday.isEmpty()) { dateTimeBirthday = birthday.dateTime(); } } GDateTime *dateTime = NULL; if (dateTimeBirthday.isValid()) { dateTime = g_date_time_new_from_unix_utc(dateTimeBirthday.toMSecsSinceEpoch() / 1000); } folks_birthday_details_change_birthday(FOLKS_BIRTHDAY_DETAILS(m_currentPersona), dateTime, (GAsyncReadyCallback) updateDetailsDone, this); if (dateTime) { g_date_time_unref(dateTime); } } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateFullName() { QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeDisplayLabel, m_currentPersonaIndex, 0); QList newDetails = detailsFromPersona(QContactDetail::TypeDisplayLabel, m_currentPersonaIndex, 0); if (m_currentPersona && FOLKS_IS_NAME_DETAILS(m_currentPersona) && !isEqual(originalDetails, newDetails)) { qDebug() << "Full Name diff:" << "\n\t" << originalDetails.size() << (originalDetails.size() > 0 ? originalDetails[0] : QContactDetail()) << "\n" << "\n\t" << newDetails.size() << (newDetails.size() > 0 ? newDetails[0] : QContactDetail()); //Only supports one fullName QString fullName; if (newDetails.count()) { QContactDisplayLabel label = static_cast(newDetails[0]); fullName = label.label(); } QByteArray fullNameUtf8 = fullName.toUtf8(); folks_name_details_change_full_name(FOLKS_NAME_DETAILS(m_currentPersona), fullNameUtf8.constData(), (GAsyncReadyCallback) updateDetailsDone, this); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateEmail() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeEmailAddress, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypeEmailAddress, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_EMAIL_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "email diff"; GeeSet *newSet = SET_AFD_NEW(); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactEmailAddress email = static_cast(newDetail); FolksEmailFieldDetails *field; QByteArray emailAddress = email.emailAddress().toUtf8(); field = folks_email_field_details_new(emailAddress.constData(), NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), newDetail, newDetail == prefDetail); gee_collection_add(GEE_COLLECTION(newSet), field); g_object_unref(field); } folks_email_details_change_email_addresses(FOLKS_EMAIL_DETAILS(m_currentPersona), newSet, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(newSet); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateName() { QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeName, m_currentPersonaIndex, 0); QList newDetails = detailsFromPersona(QContactDetail::TypeName, m_currentPersonaIndex, 0); if (m_currentPersona && FOLKS_IS_NAME_DETAILS(m_currentPersona) && !isEqual(originalDetails, newDetails)) { qDebug() << "Name diff"; //Only supports one fullName FolksStructuredName *sn = 0; if (newDetails.count()) { QContactName name = static_cast(newDetails[0]); QByteArray lastName = name.lastName().toUtf8(); QByteArray firstName = name.firstName().toUtf8(); QByteArray middleName = name.middleName().toUtf8(); QByteArray prefix = name.prefix().toUtf8(); QByteArray suffix = name.suffix().toUtf8(); sn = folks_structured_name_new(lastName.constData(), firstName.constData(), middleName.constData(), prefix.constData(), suffix.constData()); } folks_name_details_change_structured_name(FOLKS_NAME_DETAILS(m_currentPersona), sn, (GAsyncReadyCallback) updateDetailsDone, this); if (sn) { g_object_unref(sn); } } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateNickname() { QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeNickname, m_currentPersonaIndex, 0); QList newDetails = detailsFromPersona(QContactDetail::TypeNickname, m_currentPersonaIndex, 0); if (m_currentPersona && FOLKS_IS_NAME_DETAILS(m_currentPersona) && !isEqual(originalDetails, newDetails)) { qDebug() << "Nickname diff"; //Only supports one fullName QString nicknameValue; if (newDetails.count()) { QContactNickname nickname = static_cast(newDetails[0]); nicknameValue = nickname.nickname(); } QByteArray nicknameValueUtf8 = nicknameValue.toUtf8(); folks_name_details_change_nickname(FOLKS_NAME_DETAILS(m_currentPersona), nicknameValueUtf8.constData(), (GAsyncReadyCallback) updateDetailsDone, this); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateNote() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeNote, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypeNote, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_EMAIL_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "notes diff"; GeeSet *newSet = SET_AFD_NEW(); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactNote note = static_cast(newDetail); FolksNoteFieldDetails *field; QByteArray noteUtf8 = note.note().toUtf8(); field = folks_note_field_details_new(noteUtf8.constData(), 0, 0); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), newDetail, newDetail == prefDetail); gee_collection_add(GEE_COLLECTION(newSet), field); g_object_unref(field); } folks_note_details_change_notes(FOLKS_NOTE_DETAILS(m_currentPersona), newSet, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(newSet); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateOnlineAccount() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeOnlineAccount, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypeOnlineAccount, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_IM_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "OnlineAccounts diff"; GeeMultiMap *imMap = GEE_MULTI_MAP_AFD_NEW(FOLKS_TYPE_IM_FIELD_DETAILS); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactOnlineAccount account = static_cast(newDetail); FolksImFieldDetails *field; if (account.protocol() != QContactOnlineAccount::ProtocolUnknown) { QByteArray accountUri = account.accountUri().toUtf8(); field = folks_im_field_details_new(accountUri.constData(), NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), account, account == prefDetail); QString protocolName(DetailContextParser::accountProtocolName(account.protocol())); QByteArray protocolNameUtf8 = protocolName.toUtf8(); gee_multi_map_set(imMap, protocolNameUtf8.constData(), field); g_object_unref(field); } } folks_im_details_change_im_addresses(FOLKS_IM_DETAILS(m_currentPersona), imMap, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(imMap); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateOrganization() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeOrganization, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypeOrganization, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_ROLE_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "Organization diff"; GeeSet *newSet = SET_AFD_NEW(); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactOrganization org = static_cast(newDetail); FolksRoleFieldDetails *field; FolksRole *roleValue; QByteArray title = org.title().isEmpty() ? "" : org.title().toUtf8(); QByteArray name = org.name().isEmpty() ? "" : org.name().toUtf8(); QByteArray roleName = org.role().isEmpty() ? "" : org.role().toUtf8(); roleValue = folks_role_new(title.constData(), name.constData(), ""); folks_role_set_role(roleValue, roleName.constData()); field = folks_role_field_details_new(roleValue, NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), newDetail, newDetail == prefDetail); gee_collection_add(GEE_COLLECTION(newSet), field); g_object_unref(field); g_object_unref(roleValue); } folks_role_details_change_roles(FOLKS_ROLE_DETAILS(m_currentPersona), newSet, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(newSet); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updatePhone() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypePhoneNumber, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypePhoneNumber, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_PHONE_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "Phone diff:" << "\n\t" << originalDetails.size() << (originalDetails.size() > 0 ? originalDetails[0] : QContactDetail()) << "\n" << "\n\t" << newDetails.size() << (newDetails.size() > 0 ? newDetails[0] : QContactDetail()); GeeSet *newSet = SET_AFD_NEW(); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactPhoneNumber phone = static_cast(newDetail); FolksPhoneFieldDetails *field; QByteArray phoneNumber = phone.number().toUtf8(); field = folks_phone_field_details_new(phoneNumber.constData(), NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), newDetail, newDetail == prefDetail); gee_collection_add(GEE_COLLECTION(newSet), field); g_object_unref(field); } folks_phone_details_change_phone_numbers(FOLKS_PHONE_DETAILS(m_currentPersona), newSet, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(newSet); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateUrl() { QContactDetail originalPref; QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeUrl, m_currentPersonaIndex, &originalPref); QContactDetail prefDetail; QList newDetails = detailsFromPersona(QContactDetail::TypeUrl, m_currentPersonaIndex, &prefDetail); if (m_currentPersona && FOLKS_IS_URL_DETAILS(m_currentPersona) && !isEqual(originalDetails, originalPref, newDetails, prefDetail)) { qDebug() << "Url diff"; GeeSet *newSet = SET_AFD_NEW(); Q_FOREACH(QContactDetail newDetail, newDetails) { QContactUrl url = static_cast(newDetail); FolksUrlFieldDetails *field; QByteArray urlValue = url.url().toUtf8(); field = folks_url_field_details_new(urlValue.constData(), NULL); DetailContextParser::parseContext(FOLKS_ABSTRACT_FIELD_DETAILS(field), newDetail, prefDetail == newDetail); gee_collection_add(GEE_COLLECTION(newSet), field); g_object_unref(field); } folks_url_details_change_urls(FOLKS_URL_DETAILS(m_currentPersona), newSet, (GAsyncReadyCallback) updateDetailsDone, this); g_object_unref(newSet); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updateFavorite() { QList originalDetails = originalDetailsFromPersona(QContactDetail::TypeFavorite, m_currentPersonaIndex, 0); QList newDetails = detailsFromPersona(QContactDetail::TypeFavorite, m_currentPersonaIndex, 0); if (m_currentPersona && FOLKS_IS_FAVOURITE_DETAILS(m_currentPersona) && !isEqual(originalDetails, newDetails)) { qDebug() << "Favorite diff:" << "\n\t" << originalDetails.size() << (originalDetails.size() > 0 ? originalDetails[0] : QContactDetail()) << "\n" << "\n\t" << newDetails.size() << (newDetails.size() > 0 ? newDetails[0] : QContactDetail()); //Only supports one fullName bool isFavorite = false; if (newDetails.count()) { QContactFavorite favorite = static_cast(newDetails[0]); isFavorite = favorite.isFavorite(); } folks_favourite_details_change_is_favourite(FOLKS_FAVOURITE_DETAILS(m_currentPersona), isFavorite, (GAsyncReadyCallback) updateDetailsDone, this); } else { updateDetailsDone(0, 0, this); } } void UpdateContactRequest::updatePersona() { if (m_personas.size() <= m_currentPersonaIndex) { m_currentPersona = 0; if (m_parent) { m_parent->flush(); } invokeSlot(); } else { m_currentPersona = m_personas[m_currentPersonaIndex]; g_object_ref(m_currentPersona); m_currentDetailType = QContactDetail::TypeUndefined; m_currentPersonaIndex++; updateDetailsDone(0, 0, this); } } QString UpdateContactRequest::callDetailChangeFinish(QtContacts::QContactDetail::DetailType detailType, FolksPersona *persona, GAsyncResult *result) { Q_ASSERT(persona); Q_ASSERT(result); GError *error = 0; switch(detailType) { case QContactDetail::TypeAddress: folks_postal_address_details_change_postal_addresses_finish(FOLKS_POSTAL_ADDRESS_DETAILS(persona), result, &error); break; case QContactDetail::TypeAvatar: folks_avatar_details_change_avatar_finish(FOLKS_AVATAR_DETAILS(persona), result, &error); break; case QContactDetail::TypeBirthday: folks_birthday_details_change_birthday_finish(FOLKS_BIRTHDAY_DETAILS(persona), result, &error); break; case QContactDetail::TypeDisplayLabel: folks_name_details_change_full_name_finish(FOLKS_NAME_DETAILS(persona), result, &error); break; case QContactDetail::TypeEmailAddress: folks_email_details_change_email_addresses_finish(FOLKS_EMAIL_DETAILS(persona), result, &error); break; case QContactDetail::TypeFavorite: folks_favourite_details_change_is_favourite_finish(FOLKS_FAVOURITE_DETAILS(persona), result, &error); break; case QContactDetail::TypeName: folks_name_details_change_structured_name_finish(FOLKS_NAME_DETAILS(persona), result, &error); break; case QContactDetail::TypeNickname: folks_name_details_change_nickname_finish(FOLKS_NAME_DETAILS(persona), result, &error); break; case QContactDetail::TypeNote: folks_note_details_change_notes_finish(FOLKS_NOTE_DETAILS(persona), result, &error); break; case QContactDetail::TypeOnlineAccount: folks_im_details_change_im_addresses_finish(FOLKS_IM_DETAILS(persona), result, &error); break; case QContactDetail::TypeOrganization: folks_role_details_change_roles_finish(FOLKS_ROLE_DETAILS(persona), result, &error); break; case QContactDetail::TypePhoneNumber: folks_phone_details_change_phone_numbers_finish(FOLKS_PHONE_DETAILS(persona), result, &error); break; case QContactDetail::TypeUrl: folks_url_details_change_urls_finish(FOLKS_URL_DETAILS(persona), result, &error); default: break; } QString errorMessage; if (error) { errorMessage = QString::fromUtf8(error->message); g_error_free(error); } return errorMessage; } void UpdateContactRequest::updateDetailsDone(GObject *detail, GAsyncResult *result, gpointer userdata) { UpdateContactRequest *self = static_cast(userdata); QString errorMessage; if (detail && result) { if (FOLKS_IS_PERSONA(detail)) { // This is a normal field update errorMessage = self->callDetailChangeFinish(static_cast(self->m_currentDetailType), FOLKS_PERSONA(detail), result); } if (!errorMessage.isEmpty()) { self->invokeSlot(errorMessage); return; } } self->m_currentDetailType += 1; switch(static_cast(self->m_currentDetailType)) { case QContactDetail::TypeAddress: self->updateAddress(); break; case QContactDetail::TypeAvatar: self->updateAvatar(); break; case QContactDetail::TypeBirthday: self->updateBirthday(); break; case QContactDetail::TypeDisplayLabel: self->updateFullName(); break; case QContactDetail::TypeEmailAddress: //WORKAROUND: Folks automatically add online accounts based on e-mail address // for example user@gmail.com will create a jabber account, and this causes some // confusions on the service during the update, because of that we first update // the online account and this will avoid problems with the automatic update ] // from folks self->updateOnlineAccount(); break; case QContactDetail::TypeFavorite: self->updateFavorite(); break; case QContactDetail::TypeName: self->updateName(); break; case QContactDetail::TypeNickname: self->updateNickname(); break; case QContactDetail::TypeNote: self->updateNote(); break; case QContactDetail::TypeOnlineAccount: //WORKAROUND: see TypeEmailAddress update clause self->updateEmail(); break; case QContactDetail::TypeOrganization: self->updateOrganization(); break; case QContactDetail::TypePhoneNumber: self->updatePhone(); break; case QContactDetail::TypeUrl: self->updateUrl(); break; case QContactDetail::TypeAnniversary: case QContactDetail::TypeFamily: case QContactDetail::TypeGender: case QContactDetail::TypeGeoLocation: case QContactDetail::TypeGlobalPresence: case QContactDetail::TypeHobby: case QContactDetail::TypeRingtone: case QContactDetail::TypeTag: case QContactDetail::TypeTimestamp: //TODO case QContactDetail::TypeGuid: case QContactDetail::TypeType: case QContactDetail::TypeExtendedDetail: updateDetailsDone(0, 0, self); break; case QContactDetail::TypeVersion: g_object_unref(self->m_currentPersona); self->m_currentPersona = 0; self->updatePersona(); break; default: qWarning() << "Update not implemented for" << self->m_currentDetailType; updateDetailsDone(0, 0, self); break; } } } // namespace address-book-service-0.1.1+14.04.20140408.3/lib/contacts-map.h0000644000015301777760000000360612321057324023601 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_CONTACTS_MAP_PRIV_H__ #define __GALERA_CONTACTS_MAP_PRIV_H__ #include #include #include #include #include #include namespace galera { class QIndividual; class ContactEntry { public: ContactEntry(QIndividual *individual); ~ContactEntry(); QIndividual *individual() const; private: ContactEntry(); ContactEntry(const ContactEntry &other); QIndividual *m_individual; }; class ContactsMap { public: ContactsMap(); ~ContactsMap(); ContactEntry *valueFromVCard(const QString &vcard) const; bool contains(FolksIndividual *individual) const; bool contains(const QString &id) const; ContactEntry *value(FolksIndividual *individual) const; ContactEntry *value(const QString &id) const; ContactEntry *take(FolksIndividual *individual); ContactEntry *take(const QString &id); void remove(const QString &id); void insert(ContactEntry *entry); int size() const; void clear(); void lock(); void unlock(); QList values() const; private: QHash m_idToEntry; QMutex m_mutex; }; } //namespace #endif address-book-service-0.1.1+14.04.20140408.3/lib/contacts-utils.cpp0000644000015301777760000000512712321057324024517 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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-utils.h" #include #include #include using namespace QtVersit; namespace galera { QVersitProperty ContactsUtils::createProperty(int sourceIndex, int index, const QString &name, const QString &value) { QVersitProperty prop; QMultiHash param; prop.setName(name); prop.setValue(value); param.insert("PID", QString("%1.%1").arg(sourceIndex).arg(index)); prop.setParameters(param); return prop; } QList ContactsUtils::parsePersona(int index, FolksPersona *persona) { QList result; QVersitProperty prop; prop.setName("CLIENTPIDMAP"); prop.setValue(QString("%1;%2").arg(index) .arg(folks_persona_get_uid(persona))); result << prop; prop.clear(); result << createProperty(index, 1, "N", folks_persona_(persona)); return result; } QByteArray ContactsUtils::serializeIndividual(FolksIndividual *individual) { QVersitProperty prop; QVersitDocument vcard(QVersitDocument::VCard30Type); //UID prop.setName("UID"); prop.setValue(folks_individual_get_id(individual)); vcard.addProperty(prop); GeeIterator *iter; GeeSet *personas = folks_individual_get_personas(individual); int index = 1; iter = gee_iterable_iterator(GEE_ITERABLE(personas)); QList personaProps; while(gee_iterator_next(iter)) { personaProps = parsePersona(index++, FOLKS_PERSONA(gee_iterator_get(iter))); Q_FOREACH(QVersitProperty p, personaProps) { vcard.addProperty(p); } } QByteArray result; QVersitWriter writer(&result); writer.startWriting(vcard); writer.waitForFinished(); return result; } } //namespace address-book-service-0.1.1+14.04.20140408.3/3rd_party/0000755000015301777760000000000012321057642022176 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/3rd_party/CMakeLists.txt0000644000015301777760000000003012321057324024724 0ustar pbusernogroup00000000000000add_subdirectory(folks) address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/0000755000015301777760000000000012321057642023314 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/CMakeLists.txt0000644000015301777760000000021612321057324026050 0ustar pbusernogroup00000000000000list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/vala) find_package(Vala "0.17.6" REQUIRED) include(UseVala) add_subdirectory(dummy) address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/0000755000015301777760000000000012321057642024447 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/backend/0000755000015301777760000000000012321057642026036 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/backend/CMakeLists.txt0000644000015301777760000000121312321057324030570 0ustar pbusernogroup00000000000000project(folks-dummy-backend) vala_precompile(DUMMY_VALA_C SOURCES dummy-backend-factory.vala PACKAGES posix folks gee-0.8 gio-2.0 gobject-2.0 CUSTOM_VAPIS ${folks-dummy-lib_BINARY_DIR}/folks-dummy.vapi ) add_definitions(-DBACKEND_NAME="dummy") include_directories( ${CMAKE_SOURCE_DIR} ${folks-dummy-lib_BINARY_DIR} ${GLIB_INCLUDE_DIRS} ${GIO_INCLUDE_DIRS} ${FOLKS_INCLUDE_DIRS} ) add_library(dummy MODULE ${DUMMY_VALA_C} ) set_target_properties(dummy PROPERTIES PREFIX "" ) target_link_libraries(dummy folks-dummy ${GLIB_LIBRARIES} ${GIO_LIBRARIES} ${FOLKS_LIBRARIES} ) address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/backend/dummy-backend-factory.vala0000644000015301777760000000315712321057324033073 0ustar pbusernogroup00000000000000/* * Copyright (C) 2009 Zeeshan Ali (Khattak) . * Copyright (C) 2009 Nokia Corporation. * Copyright (C) 2011, 2013 Collabora Ltd. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see . * * Authors: Zeeshan Ali (Khattak) * Travis Reitter * Marco Barisione * Raul Gutierrez Segales * * This file was originally part of Rygel. */ using Folks; /** * The dummy backend module entry point. * * @backend_store a store to add the dummy backends to * @since UNRELEASED */ public void module_init (BackendStore backend_store) { backend_store.add_backend (new FolksDummy.Backend ()); } /** * The dummy backend module exit point. * * @param backend_store the store to remove the backends from * @since UNRELEASED */ public void module_finalize (BackendStore backend_store) { /* FIXME: No backend_store.remove_backend() API exists. */ } address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/0000755000015301777760000000000012321057642025215 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/folks-dummy.pc.in0000644000015301777760000000061412321057324030413 0ustar pbusernogroup00000000000000prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ bindir=@bindir@ includedir=@includedir@ datarootdir=@datarootdir@ datadir=@datadir@ vapidir=@datadir@/vala/vapi Name: Folks dummy support library Description: Dummy support library for the Folks meta-contacts library Version: @VERSION@ Requires: folks glib-2.0 gobject-2.0 gee-0.8 Libs: -L${libdir} -lfolks-dummy Cflags: -I${includedir} address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/dummy-full-persona.vala0000644000015301777760000007753412321057324031637 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Philip Withnall * Copyright (C) 2013 Collabora Ltd. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see . * * Authors: * Philip Withnall * Travis Reitter * Marco Barisione * Raul Gutierrez Segales */ using Folks; using Gee; using GLib; /** * A persona subclass representing a single ‘full’ contact. * * This mocks up a ‘full’ persona which implements all the available property * interfaces provided by libfolks. This is in contrast with * {@link FolksDummy.Persona}, which provides a base class implementing none of * libfolks’ interfaces. * * The full dummy persona can be used to simulate a persona from most libfolks * backends, if writing a custom {@link FolksDummy.Persona} subclass is not an * option. * * There are two sides to this class’ interface: the normal methods required by * the libfolks ‘details’ interfaces, such as * {@link Folks.GenderDetails.change_gender}, * and the backend methods which should be called by test driver code to * simulate changes in the backing store providing this persona, such as * {@link FullPersona.update_gender}. For example, test driver code should call * {@link FullPersona.update_nickname} to simulate the user editing a contact’s * nickname in an online address book which is being exposed to libfolks. The * ``update_``, ``register_`` and ``unregister_`` prefixes are commonly used for * backend methods. * * The API in {@link FolksDummy} is unstable and may change wildly. It is * designed mostly for use by libfolks unit tests. * * @since UNRELEASED */ public class FolksDummy.FullPersona : FolksDummy.Persona, AntiLinkable, AvatarDetails, BirthdayDetails, EmailDetails, FavouriteDetails, GenderDetails, GroupDetails, ImDetails, LocalIdDetails, NameDetails, NoteDetails, PhoneDetails, RoleDetails, UrlDetails, PostalAddressDetails, WebServiceDetails { private const string[] _default_linkable_properties = { "im-addresses", "email-addresses", "local-ids", "web-service-addresses" }; /** * Create a new ‘full’ persona. * * Create a new persona for the {@link FolksDummy.PersonaStore} ``store``, * with the given construct-only properties. * * @param store the store which will contain the persona * @param contact_id a unique free-form string identifier for the persona * @param is_user ``true`` if the persona represents the user, ``false`` * otherwise * @param linkable_properties an array of names of the properties which should * be used for linking this persona to others * * @since UNRELEASED */ public FullPersona (PersonaStore store, string contact_id, bool is_user = false, string[] linkable_properties = {}) { base (store, contact_id, is_user, linkable_properties); } construct { this._local_ids_ro = this._local_ids.read_only_view; this._postal_addresses_ro = this._postal_addresses.read_only_view; this._email_addresses_ro = this._email_addresses.read_only_view; this._phone_numbers_ro = this._phone_numbers.read_only_view; this._notes_ro = this._notes.read_only_view; this._urls_ro = this._urls.read_only_view; this._groups_ro = this._groups.read_only_view; this._roles_ro = this._roles.read_only_view; this._anti_links_ro = this._anti_links.read_only_view; this.update_linkable_properties(FullPersona._default_linkable_properties); } private HashMultiMap _web_service_addresses = new HashMultiMap ( null, null, AbstractFieldDetails.hash_static, AbstractFieldDetails.equal_static); /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public MultiMap web_service_addresses { get { return this._web_service_addresses; } set { this.change_web_service_addresses.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_web_service_addresses ( MultiMap web_service_addresses) throws PropertyError { yield this.change_property ("web-service-addresses", () => { this.update_web_service_addresses (web_service_addresses); }); } private HashSet _local_ids = new HashSet (); private Set _local_ids_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set local_ids { get { if (this._local_ids.contains (this.iid) == false) { this._local_ids.add (this.iid); } return this._local_ids_ro; } set { this.change_local_ids.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_local_ids (Set local_ids) throws PropertyError { yield this.change_property ("local-ids", () => { this.update_local_ids (local_ids); }); } private HashSet _postal_addresses = new HashSet (); private Set _postal_addresses_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set postal_addresses { get { return this._postal_addresses_ro; } set { this.change_postal_addresses.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_postal_addresses ( Set postal_addresses) throws PropertyError { yield this.change_property ("postal-addresses", () => { this.update_postal_addresses (postal_addresses); }); } private HashSet _phone_numbers = new HashSet (); private Set _phone_numbers_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set phone_numbers { get { return this._phone_numbers_ro; } set { this.change_phone_numbers.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_phone_numbers ( Set phone_numbers) throws PropertyError { yield this.change_property ("phone-numbers", () => { this.update_phone_numbers (phone_numbers); }); } private HashSet? _email_addresses = new HashSet ( AbstractFieldDetails.hash_static, AbstractFieldDetails.equal_static); private Set _email_addresses_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set email_addresses { get { return this._email_addresses_ro; } set { this.change_email_addresses.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_email_addresses ( Set email_addresses) throws PropertyError { yield this.change_property ("email-addresses", () => { this.update_email_addresses (email_addresses); }); } private HashSet _notes = new HashSet (); private Set _notes_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set notes { get { return this._notes_ro; } set { this.change_notes.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_notes (Set notes) throws PropertyError { yield this.change_property ("notes", () => { this.update_notes (notes); }); } private LoadableIcon? _avatar = null; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public LoadableIcon? avatar { get { return this._avatar; } set { this.change_avatar.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_avatar (LoadableIcon? avatar) throws PropertyError { yield this.change_property ("avatar", () => { this.update_avatar (avatar); }); } private StructuredName? _structured_name = null; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public StructuredName? structured_name { get { return this._structured_name; } set { this.change_structured_name.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_structured_name (StructuredName? structured_name) throws PropertyError { yield this.change_property ("structured-name", () => { this.update_structured_name (structured_name); }); } private string _full_name = ""; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public string full_name { get { return this._full_name; } set { this.change_full_name.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_full_name (string full_name) throws PropertyError { yield this.change_property ("full-name", () => { this.update_full_name (full_name); }); } private string _nickname = ""; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public string nickname { get { return this._nickname; } set { this.change_nickname.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_nickname (string nickname) throws PropertyError { yield this.change_property ("nickname", () => { this.update_nickname (nickname); }); } private Gender _gender = Gender.UNSPECIFIED; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Gender gender { get { return this._gender; } set { this.change_gender.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_gender (Gender gender) throws PropertyError { yield this.change_property ("gender", () => { this.update_gender (gender); }); } private HashSet _urls = new HashSet (); private Set _urls_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set urls { get { return this._urls_ro; } set { this.change_urls.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_urls (Set urls) throws PropertyError { yield this.change_property ("urls", () => { this.update_urls (urls); }); } private HashMultiMap _im_addresses = new HashMultiMap (null, null, AbstractFieldDetails.hash_static, AbstractFieldDetails.equal_static); /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public MultiMap im_addresses { get { return this._im_addresses; } set { this.change_im_addresses.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_im_addresses ( MultiMap im_addresses) throws PropertyError { yield this.change_property ("im-addresses", () => { this.update_im_addresses (im_addresses); }); } private HashSet _groups = new HashSet (); private Set _groups_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set groups { get { return this._groups_ro; } set { this.change_groups.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_group (string group, bool is_member) throws GLib.Error { /* Nothing to do? */ if ((is_member == true && this._groups.contains (group) == true) || (is_member == false && this._groups.contains (group) == false)) { return; } /* Replace the current set of groups with a modified one. */ var new_groups = new HashSet (); foreach (var category_name in this._groups) { new_groups.add (category_name); } if (is_member == false) { new_groups.remove (group); } else { new_groups.add (group); } yield this.change_groups (new_groups); } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_groups (Set groups) throws PropertyError { yield this.change_property ("groups", () => { this.update_groups (groups); }); } private string? _calendar_event_id = null; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public string? calendar_event_id { get { return this._calendar_event_id; } set { this.change_calendar_event_id.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_calendar_event_id (string? calendar_event_id) throws PropertyError { yield this.change_property ("calendar-event-id", () => { this.update_calendar_event_id (calendar_event_id); }); } private DateTime? _birthday = null; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public DateTime? birthday { get { return this._birthday; } set { this.change_birthday.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_birthday (DateTime? bday) throws PropertyError { yield this.change_property ("birthday", () => { this.update_birthday (bday); }); } private HashSet _roles = new HashSet (); private Set _roles_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set roles { get { return this._roles_ro; } set { this.change_roles.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_roles (Set roles) throws PropertyError { yield this.change_property ("roles", () => { this.update_roles (roles); }); } private bool _is_favourite = false; /** * Whether this contact is a user-defined favourite. * * @since UNRELEASED */ [CCode (notify = false)] public bool is_favourite { get { return this._is_favourite; } set { this.change_is_favourite.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_is_favourite (bool is_favourite) throws PropertyError { yield this.change_property ("is-favourite", () => { this.update_is_favourite (is_favourite); }); } private HashSet _anti_links = new HashSet (); private Set _anti_links_ro; /** * {@inheritDoc} * * @since UNRELEASED */ [CCode (notify = false)] public Set anti_links { get { return this._anti_links_ro; } set { this.change_anti_links.begin (value); } } /** * {@inheritDoc} * * @since UNRELEASED */ public async void change_anti_links (Set anti_links) throws PropertyError { yield this.change_property ("anti-links", () => { this.update_anti_links (anti_links); }); } /* * All the functions below here are to be used by testing code rather than by * libfolks clients. They form the interface which would normally be between * the Persona and a web service or backing store of some kind. */ private HashSet _dup_to_hash_set (Set input_set) { var output_set = new HashSet (); output_set.add_all (input_set); return output_set; } private HashMultiMap _dup_to_hash_multi_map ( MultiMap input_multi_map) { var output_multi_map = new HashMultiMap (); var iter = input_multi_map.map_iterator (); while (iter.next () == true) output_multi_map.set (iter.get_key (), iter.get_value ()); return output_multi_map; } /** * Update persona's gender. * * This simulates a backing-store-side update of the persona's * {@link Folks.GenderDetails.gender} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param gender persona's new gender * @since UNRELEASED */ public void update_gender (Gender gender) { if (this._gender != gender) { this._gender = gender; this.notify_property ("gender"); } } /** * Update persona's birthday calendar event ID. * * This simulates a backing-store-side update of the persona's * {@link Folks.BirthdayDetails.calendar_event_id} property. It is intended to * be used for testing code which consumes this property. If the property * value changes, this results in a property change notification on the * persona. * * @param calendar_event_id persona's new birthday calendar event ID * @since UNRELEASED */ public void update_calendar_event_id (string? calendar_event_id) { if (calendar_event_id != this._calendar_event_id) { this._calendar_event_id = calendar_event_id; this.notify_property ("calendar-event-id"); } } /** * Update persona's birthday. * * This simulates a backing-store-side update of the persona's * {@link Folks.BirthdayDetails.birthday} property. It is intended to be used * for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param birthday persona's new birthday * @since UNRELEASED */ public void update_birthday (DateTime? birthday) { if ((this._birthday == null) != (birthday == null) || (this._birthday != null && birthday != null && !((!) this._birthday).equal ((!) birthday))) { this._birthday = birthday; this.notify_property ("birthday"); } } /** * Update persona's roles. * * This simulates a backing-store-side update of the persona's * {@link Folks.RoleDetails.roles} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param roles persona's new roles * @since UNRELEASED */ public void update_roles (Set roles) { if (!Folks.Internal.equal_sets (roles, this._roles)) { this._roles = this._dup_to_hash_set (roles); this._roles_ro = this._roles.read_only_view; this.notify_property ("roles"); } } /** * Update persona's groups. * * This simulates a backing-store-side update of the persona's * {@link Folks.GroupDetails.groups} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param groups persona's new groups * @since UNRELEASED */ public void update_groups (Set groups) { if (!Folks.Internal.equal_sets (groups, this._groups)) { this._groups = this._dup_to_hash_set (groups); this._groups_ro = this._groups.read_only_view; this.notify_property ("groups"); } } /** * Update persona's web service addresses. * * This simulates a backing-store-side update of the persona's * {@link Folks.WebServiceDetails.web_service_addresses} property. It is * intended to be used for testing code which consumes this property. If the * property value changes, this results in a property change notification on * the persona. * * @param web_service_addresses persona's new web service addresses * @since UNRELEASED */ public void update_web_service_addresses ( MultiMap web_service_addresses) { if (!Utils.multi_map_str_afd_equal (web_service_addresses, this._web_service_addresses)) { this._web_service_addresses = this._dup_to_hash_multi_map ( web_service_addresses); this.notify_property ("web-service-addresses"); } } /** * Update persona's e-mail addresses. * * This simulates a backing-store-side update of the persona's * {@link Folks.EmailDetails.email_addresses} property. It is intended to be * used for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param email_addresses persona's new e-mail addresses * @since UNRELEASED */ public void update_email_addresses (Set email_addresses) { if (!Folks.Internal.equal_sets (email_addresses, this._email_addresses)) { this._email_addresses = this._dup_to_hash_set (email_addresses); this._email_addresses_ro = this._email_addresses.read_only_view; this.notify_property ("email-addresses"); } } /** * Update persona's notes. * * This simulates a backing-store-side update of the persona's * {@link Folks.NoteDetails.notes} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param notes persona's new notes * @since UNRELEASED */ public void update_notes (Set notes) { if (!Folks.Internal.equal_sets (notes, this._notes)) { this._notes = this._dup_to_hash_set (notes); this._notes_ro = this._notes.read_only_view; this.notify_property ("notes"); } } /** * Update persona's full name. * * This simulates a backing-store-side update of the persona's * {@link Folks.NameDetails.full_name} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param full_name persona's new full name * @since UNRELEASED */ public void update_full_name (string full_name) { if (this._full_name != full_name) { this._full_name = full_name; this.notify_property ("full-name"); } } /** * Update persona's nickname. * * This simulates a backing-store-side update of the persona's * {@link Folks.NameDetails.nickname} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param nickname persona's new nickname * @since UNRELEASED */ public void update_nickname (string nickname) { if (this._nickname != nickname) { this._nickname = nickname; this.notify_property ("nickname"); } } /** * Update persona's structured name. * * This simulates a backing-store-side update of the persona's * {@link Folks.NameDetails.structured_name} property. It is intended to be * used for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param structured_name persona's new structured name * @since UNRELEASED */ public void update_structured_name (StructuredName? structured_name) { if (structured_name != null && !((!) structured_name).is_empty ()) { this._structured_name = (!) structured_name; this.notify_property ("structured-name"); } else if (this._structured_name != null) { this._structured_name = null; this.notify_property ("structured-name"); } } /** * Update persona's avatar. * * This simulates a backing-store-side update of the persona's * {@link Folks.AvatarDetails.avatar} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param avatar persona's new avatar * @since UNRELEASED */ public void update_avatar (LoadableIcon? avatar) { if ((this._avatar == null) != (avatar == null) || (this._avatar != null && avatar != null && !((!) this._avatar).equal ((!) avatar))) { this._avatar = avatar; this.notify_property ("avatar"); } } /** * Update persona's URIs. * * This simulates a backing-store-side update of the persona's * {@link Folks.UrlDetails.urls} property. It is intended to be used for * testing code which consumes this property. If the property value changes, * this results in a property change notification on the persona. * * @param urls persona's new URIs * @since UNRELEASED */ public void update_urls (Set urls) { if (!Utils.set_afd_equal (urls, this._urls)) { this._urls = this._dup_to_hash_set (urls); this._urls_ro = this._urls.read_only_view; this.notify_property ("urls"); } } /** * Update persona's IM addresses. * * This simulates a backing-store-side update of the persona's * {@link Folks.ImDetails.im_addresses} property. It is intended to be used * for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param im_addresses persona's new IM addresses * @since UNRELEASED */ public void update_im_addresses ( MultiMap im_addresses) { if (!Utils.multi_map_str_afd_equal (im_addresses, this._im_addresses)) { this._im_addresses = this._dup_to_hash_multi_map ( im_addresses); this.notify_property ("im-addresses"); } } /** * Update persona's phone numbers. * * This simulates a backing-store-side update of the persona's * {@link Folks.PhoneDetails.phone_numbers} property. It is intended to be * used for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param phone_numbers persona's new phone numbers * @since UNRELEASED */ public void update_phone_numbers (Set phone_numbers) { if (!Folks.Internal.equal_sets (phone_numbers, this._phone_numbers)) { this._phone_numbers = this._dup_to_hash_set (phone_numbers); this._phone_numbers_ro = this._phone_numbers.read_only_view; this.notify_property ("phone-numbers"); } } /** * Update persona's postal addresses. * * This simulates a backing-store-side update of the persona's * {@link Folks.PostalAddressDetails.postal_addresses} property. It is * intended to be used for testing code which consumes this property. If the * property value changes, this results in a property change notification on * the persona. * * @param postal_addresses persona's new postal addresses * @since UNRELEASED */ public void update_postal_addresses ( Set postal_addresses) { if (!Folks.Internal.equal_sets ( postal_addresses, this._postal_addresses)) { this._postal_addresses = this._dup_to_hash_set ( postal_addresses); this._postal_addresses_ro = this._postal_addresses.read_only_view; this.notify_property ("postal-addresses"); } } /** * Update persona's local IDs. * * This simulates a backing-store-side update of the persona's * {@link Folks.LocalIdDetails.local_ids} property. It is intended to be used * for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param local_ids persona's new local IDs * @since UNRELEASED */ public void update_local_ids (Set local_ids) { if (!Folks.Internal.equal_sets (local_ids, this.local_ids)) { this._local_ids = this._dup_to_hash_set (local_ids); this._local_ids_ro = this._local_ids.read_only_view; this.notify_property ("local-ids"); } } /** * Update persona's status as a favourite. * * This simulates a backing-store-side update of the persona's * {@link Folks.FavouriteDetails.is_favourite} property. It is intended to be * used for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param is_favourite persona's new status as a favourite * @since UNRELEASED */ public void update_is_favourite (bool is_favourite) { if (is_favourite != this._is_favourite) { this._is_favourite = is_favourite; this.notify_property ("is-favourite"); } } /** * Update persona's anti-links. * * This simulates a backing-store-side update of the persona's * {@link Folks.AntiLinkable.anti_links} property. It is intended to be used * for testing code which consumes this property. If the property value * changes, this results in a property change notification on the persona. * * @param anti_links persona's new anti-links * @since UNRELEASED */ public void update_anti_links (Set anti_links) { if (!Folks.Internal.equal_sets (anti_links, this._anti_links)) { this._anti_links = this._dup_to_hash_set (anti_links); this._anti_links_ro = this._anti_links.read_only_view; this.notify_property ("anti-links"); } } } address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/dummy-persona-store.vala0000644000015301777760000011022712321057324032014 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Philip Withnall * Copyright (C) 2013 Canonical Ltd * Copyright (C) 2013 Collabora Ltd. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see . * * Authors: * Philip Withnall * Renato Araujo Oliveira Filho */ using Folks; using Gee; using GLib; /** * A persona store which allows {@link FolksDummy.Persona}s to be * programmatically created and manipulated, for the purposes of testing the * core of libfolks itself. This should not be used in user-visible * applications. * * There are two sides to this class’ interface: the methods and properties * declared by {@link Folks.PersonaStore}, which form the normal libfolks * persona store API; and the mock methods and properties (such as * {@link FolksDummy.PersonaStore.add_persona_from_details_mock}) which are * intended to be used by test driver code to simulate the behaviour of a real * backing store. Calls to these mock methods effect state changes in the store * which are visible in the normal libfolks API. The ``update_``, ``register_`` * and ``unregister_`` prefixes and the ``mock`` suffix are commonly used for * backing store methods. * * The main action performed with a dummy persona store is to change its set of * personas, adding and removing them dynamically to test client-side behaviour. * The client-side APIs ({@link Folks.PersonaStore.add_persona_from_details} and * {@link Folks.PersonaStore.remove_persona}) should //not// be used for this. * Instead, the mock APIs should be used: * {@link FolksDummy.PersonaStore.freeze_personas_changed}, * {@link FolksDummy.PersonaStore.register_personas}, * {@link FolksDummy.PersonaStore.unregister_personas} and * {@link FolksDummy.PersonaStore.thaw_personas_changed}. These can be used to * build up complex {@link Folks.PersonaStore.personas_changed} signal * emissions, which are only emitted after the final call to * {@link FolksDummy.PersonaStore.thaw_personas_changed}. * * The API in {@link FolksDummy} is unstable and may change wildly. It is * designed mostly for use by libfolks unit tests. * * @since UNRELEASED */ public class FolksDummy.PersonaStore : Folks.PersonaStore { private bool _is_prepared = false; private bool _prepare_pending = false; private bool _is_quiescent = false; private bool _quiescent_on_prepare = false; private int _contact_id = 0; /** * The type of persona store this is. * * See {@link Folks.PersonaStore.type_id}. * * @since UNRELEASED */ public override string type_id { get { return BACKEND_NAME; } } private MaybeBool _can_add_personas = MaybeBool.FALSE; /** * Whether this PersonaStore can add {@link Folks.Persona}s. * * See {@link Folks.PersonaStore.can_add_personas}. * * @since UNRELEASED */ public override MaybeBool can_add_personas { get { if (!this._is_prepared) { return MaybeBool.FALSE; } return this._can_add_personas; } } private MaybeBool _can_alias_personas = MaybeBool.FALSE; /** * Whether this PersonaStore can set the alias of {@link Folks.Persona}s. * * See {@link Folks.PersonaStore.can_alias_personas}. * * @since UNRELEASED */ public override MaybeBool can_alias_personas { get { if (!this._is_prepared) { return MaybeBool.FALSE; } return this._can_alias_personas; } } /** * Whether this PersonaStore can set the groups of {@link Folks.Persona}s. * * See {@link Folks.PersonaStore.can_group_personas}. * * @since UNRELEASED */ public override MaybeBool can_group_personas { get { return ("groups" in this._always_writeable_properties) ? MaybeBool.TRUE : MaybeBool.FALSE; } } private MaybeBool _can_remove_personas = MaybeBool.FALSE; /** * Whether this PersonaStore can remove {@link Folks.Persona}s. * * See {@link Folks.PersonaStore.can_remove_personas}. * * @since UNRELEASED */ public override MaybeBool can_remove_personas { get { if (!this._is_prepared) { return MaybeBool.FALSE; } return this._can_remove_personas; } } /** * Whether this PersonaStore has been prepared. * * See {@link Folks.PersonaStore.is_prepared}. * * @since UNRELEASED */ public override bool is_prepared { get { return this._is_prepared; } } private string[] _always_writeable_properties = {}; private static string[] _always_writeable_properties_empty = {}; /* oh Vala */ /** * {@inheritDoc} * * @since UNRELEASED */ public override string[] always_writeable_properties { get { if (!this._is_prepared) { return PersonaStore._always_writeable_properties_empty; } return this._always_writeable_properties; } } /* * Whether this PersonaStore has reached a quiescent state. * * See {@link Folks.PersonaStore.is_quiescent}. * * @since UNRELEASED */ public override bool is_quiescent { get { return this._is_quiescent; } } private HashMap _personas; private Map _personas_ro; /* Personas which have been registered but not yet emitted in a * personas-changed signal. */ private HashSet _pending_persona_registrations; /* Personas which have been unregistered but not yet emitted in a * personas-changed signal. */ private HashSet _pending_persona_unregistrations; /* Freeze counter for persona changes: personas-changed is only emitted when * this is 0. */ private uint _personas_changed_frozen = 0; /** * The {@link Persona}s exposed by this PersonaStore. * * See {@link Folks.PersonaStore.personas}. * * @since UNRELEASED */ public override Map personas { get { return this._personas_ro; } } /** * Create a new persona store. * * This store will have no personas to begin with; use * {@link FolksDummy.PersonaStore.register_personas} to add some, then call * {@link FolksDummy.PersonaStore.reach_quiescence} to signal the store * reaching quiescence. * * @param id The new store's ID. * @param display_name The new store's display name. * @param always_writeable_properties The set of always writeable properties. * * @since UNRELEASED */ public PersonaStore (string id, string display_name, string[] always_writeable_properties) { Object ( id: id, display_name: display_name); this._always_writeable_properties = always_writeable_properties; } construct { this._personas = new HashMap (); this._personas_ro = this._personas.read_only_view; this._pending_persona_registrations = new HashSet (); this._pending_persona_unregistrations = new HashSet (); } /** * Add a new {@link Persona} to the PersonaStore. * * Accepted keys for ``details`` are: * - PersonaStore.detail_key (PersonaDetail.AVATAR) * - PersonaStore.detail_key (PersonaDetail.BIRTHDAY) * - PersonaStore.detail_key (PersonaDetail.EMAIL_ADDRESSES) * - PersonaStore.detail_key (PersonaDetail.FULL_NAME) * - PersonaStore.detail_key (PersonaDetail.GENDER) * - PersonaStore.detail_key (PersonaDetail.IM_ADDRESSES) * - PersonaStore.detail_key (PersonaDetail.IS_FAVOURITE) * - PersonaStore.detail_key (PersonaDetail.PHONE_NUMBERS) * - PersonaStore.detail_key (PersonaDetail.POSTAL_ADDRESSES) * - PersonaStore.detail_key (PersonaDetail.ROLES) * - PersonaStore.detail_key (PersonaDetail.STRUCTURED_NAME) * - PersonaStore.detail_key (PersonaDetail.LOCAL_IDS) * - PersonaStore.detail_key (PersonaDetail.WEB_SERVICE_ADDRESSES) * - PersonaStore.detail_key (PersonaDetail.NOTES) * - PersonaStore.detail_key (PersonaDetail.URLS) * * See {@link Folks.PersonaStore.add_persona_from_details}. * * @param details key–value pairs giving the new persona’s details * @throws Folks.PersonaStoreError.STORE_OFFLINE if the store hasn’t been * prepared * @throws Folks.PersonaStoreError.CREATE_FAILED if creating the persona in * the dummy store failed * * @since UNRELEASED */ public override async Folks.Persona? add_persona_from_details ( HashTable details) throws PersonaStoreError { /* We have to have called prepare() beforehand. */ if (!this._is_prepared) { throw new PersonaStoreError.STORE_OFFLINE ( "Persona store has not yet been prepared."); } /* Allow overriding the class used. */ var contact_id = this._contact_id.to_string(); this._contact_id++; var uid = Folks.Persona.build_uid (BACKEND_NAME, this.id, contact_id); var iid = this.id + ":" + contact_id; var persona = Object.new (this._persona_type, "display-id", contact_id, "uid", uid, "iid", iid, "store", this, "is-user", false, null) as FolksDummy.Persona; assert (persona != null); persona.update_writeable_properties (this.always_writeable_properties); unowned Value? v; try { v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.FULL_NAME)); var p_name = persona as NameDetails; if (p_name != null && v != null) { string full_name = ((!) v).get_string () ?? ""; yield p_name.change_full_name (full_name); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.STRUCTURED_NAME)); if (p_name != null && v != null) { var sname = (StructuredName) ((!) v).get_object (); if (sname != null) yield p_name.change_structured_name (sname); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.NICKNAME)); if (p_name != null && v != null) { string nickname = ((!) v).get_string () ?? ""; yield p_name.change_nickname (nickname); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.EMAIL_ADDRESSES)); var p_email = persona as EmailDetails; if (p_email != null && v != null) { var email_addresses = (Set) ((!) v).get_object (); if (email_addresses != null) yield p_email.change_email_addresses (email_addresses); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.AVATAR)); var p_avatar = persona as AvatarDetails; if (p_avatar != null && v != null) { var avatar = (LoadableIcon?) ((!) v).get_object (); if (avatar != null) yield p_avatar.change_avatar (avatar); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.IM_ADDRESSES)); var p_im = persona as ImDetails; if (p_im != null && v != null) { var im_addresses = (MultiMap) ((!) v).get_object (); if (im_addresses != null) yield p_im.change_im_addresses (im_addresses); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.PHONE_NUMBERS)); var p_phone = persona as PhoneDetails; if (p_phone != null && v != null) { var phone_numbers = (Set) ((!) v).get_object (); if (phone_numbers != null) yield p_phone.change_phone_numbers (phone_numbers); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.POSTAL_ADDRESSES)); var p_postal = persona as PostalAddressDetails; if (p_postal != null && v != null) { var postal_fds = (Set) ((!) v).get_object (); if (postal_fds != null) yield p_postal.change_postal_addresses (postal_fds); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.LOCAL_IDS)); var p_local = persona as LocalIdDetails; if (p_local != null && v != null) { var local_ids = (Set) ((!) v).get_object (); if (local_ids != null) yield p_local.change_local_ids (local_ids); } v = details.lookup ( Folks.PersonaStore.detail_key ( PersonaDetail.WEB_SERVICE_ADDRESSES)); var p_web = persona as WebServiceDetails; if (p_web != null && v != null) { var addrs = (HashMultiMap) ((!) v).get_object (); if (addrs != null) yield p_web.change_web_service_addresses (addrs); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.NOTES)); var p_note = persona as NoteDetails; if (p_note != null && v != null) { var notes = (Gee.HashSet) ((!) v).get_object (); if (notes != null) yield p_note.change_notes (notes); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.GENDER)); var p_gender = persona as GenderDetails; if (p_gender != null && v != null) { var gender = (Gender) ((!) v).get_enum (); yield p_gender.change_gender (gender); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.URLS)); var p_url = persona as UrlDetails; if (p_url != null && v != null) { var urls = (Set) ((!) v).get_object (); if (urls != null) yield p_url.change_urls (urls); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.BIRTHDAY)); var p_birthday = persona as BirthdayDetails; if (p_birthday != null && v != null) { var birthday = (DateTime?) ((!) v).get_boxed (); if (birthday != null) yield p_birthday.change_birthday (birthday); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.ROLES)); var p_role = persona as RoleDetails; if (p_role != null && v != null) { var roles = (Set) ((!) v).get_object (); if (roles != null) yield p_role.change_roles (roles); } v = details.lookup ( Folks.PersonaStore.detail_key (PersonaDetail.IS_FAVOURITE)); var p_favourite = persona as FavouriteDetails; if (p_favourite != null && v != null) { bool is_fav = ((!) v).get_boolean (); yield p_favourite.change_is_favourite (is_fav); } } catch (PropertyError e1) { throw new PersonaStoreError.CREATE_FAILED ( "Setting a property on the new persona failed: %s", e1.message); } /* Allow the caller to inject failures and delays into * add_persona_from_details() by providing a mock function. */ if (this.add_persona_from_details_mock != null) { var delay = this.add_persona_from_details_mock (persona); yield this._implement_mock_delay (delay); } /* No simulated failure: continue adding the persona. */ this._personas.set (persona.iid, persona); /* Notify of the new persona. */ var added_personas = new HashSet (); added_personas.add (persona); this._emit_personas_changed (added_personas, null); return persona; } /** * Remove a {@link Persona} from the PersonaStore. * * See {@link Folks.PersonaStore.remove_persona}. * * @param persona the persona that should be removed * @throws Folks.PersonaStoreError.STORE_OFFLINE if the store hasn’t been * prepared or has gone offline * @throws Folks.PersonaStoreError.PERMISSION_DENIED if the store denied * permission to delete the contact * @throws Folks.PersonaStoreError.READ_ONLY if the store is read only * @throws Folks.PersonaStoreError.REMOVE_FAILED if any other errors happened * in the store * * @since UNRELEASED */ public override async void remove_persona (Folks.Persona persona) throws PersonaStoreError requires (persona is FolksDummy.Persona) { /* We have to have called prepare() beforehand. */ if (!this._is_prepared) { throw new PersonaStoreError.STORE_OFFLINE ( "Persona store has not yet been prepared."); } /* Allow the caller to inject failures and delays. */ if (this.remove_persona_mock != null) { var delay = this.remove_persona_mock ((FolksDummy.Persona) persona); yield this._implement_mock_delay (delay); } Persona? _persona = this._personas.get (persona.iid); if (_persona != null) { this._personas.unset (persona.iid); /* Handle the case where a contact is removed while persona changes * are frozen. */ this._pending_persona_registrations.remove ((!) _persona); this._pending_persona_unregistrations.remove ((!) _persona); /* Notify of the removal. */ var removed_personas = new HashSet (); removed_personas.add ((!) persona); this._emit_personas_changed (null, removed_personas); } } /** * Prepare the PersonaStore for use. * * See {@link Folks.PersonaStore.prepare}. * * @throws Folks.PersonaStoreError.STORE_OFFLINE if the store is offline * @throws Folks.PersonaStoreError.PERMISSION_DENIED if permission was denied * to open the store * @throws Folks.PersonaStoreError.INVALID_ARGUMENT if any other error * occurred in the store * * @since UNRELEASED */ public override async void prepare () throws PersonaStoreError { Internal.profiling_start ("preparing Dummy.PersonaStore (ID: %s)", this.id); if (this._is_prepared == true || this._prepare_pending == true) { return; } try { this._prepare_pending = true; /* Allow the caller to inject failures and delays. */ if (this.prepare_mock != null) { var delay = this.prepare_mock (); yield this._implement_mock_delay (delay); } this._is_prepared = true; this.notify_property ("is-prepared"); /* If reach_quiescence() has been called already, signal * quiescence. */ if (this._quiescent_on_prepare == true) { this.reach_quiescence (); } } finally { this._prepare_pending = false; } Internal.profiling_end ("preparing Dummy.PersonaStore"); } /* * All the functions below here are to be used by testing code rather than by * libfolks clients. They form the interface which would normally be between * the PersonaStore and a web service or backing store of some kind. */ /** * Delay for the given number of milliseconds. * * This implements an asynchronous delay (which should be yielded on) until * the given number of milliseconds has elapsed. * * If ``delay`` is negative, this function returns immediately. If it is * zero, this function returns in an idle callback. * * @param delay number of milliseconds to delay for * * @since UNRELEASED */ private async void _implement_mock_delay (int delay) { if (delay < 0) { /* No delay. */ return; } else if (delay == 0) { /* Idle delay. */ Idle.add (() => { this._implement_mock_delay.callback (); return false; }); yield; } else { /* Timed delay. */ Timeout.add (delay, () => { this._implement_mock_delay.callback (); return false; }); yield; } } /** * Type of a mock function for * {@link Folks.PersonaStore.add_persona_from_details}. * * See {@link FolksDummy.PersonaStore.add_persona_from_details_mock}. * * @param persona the persona being added to the store, as constructed from * the details passed to {@link Folks.PersonaStore.add_persona_from_details}. * @throws PersonaStoreError to be thrown from * {@link Folks.PersonaStore.add_persona_from_details} * @return delay to apply to the add persona operation (negative delays * complete synchronously; zero delays complete in an idle callback; positive * delays complete after that many milliseconds) * * @since UNRELEASED */ public delegate int AddPersonaFromDetailsMock (Persona persona) throws PersonaStoreError; /** * Mock function for {@link Folks.PersonaStore.add_persona_from_details}. * * This function is called whenever this store's * {@link Folks.PersonaStore.add_persona_from_details} method is called. It * allows the caller to determine whether adding the given persona should * fail, by throwing an error from this mock function. If no error is thrown * from this function, adding the given persona will succeed. This is useful * for testing error handling of calls to * {@link Folks.PersonaStore.add_persona_from_details}. * * The value returned by this function gives a delay which is imposed for * completion of the {@link Folks.PersonaStore.add_persona_from_details} call. * Negative or zero delays * result in completion in an idle callback, and positive delays result in * completion after that many milliseconds. * * If this is ``null``, all calls to * {@link Folks.PersonaStore.add_persona_from_details} will succeed. * * This mock function may be changed at any time; changes will take effect for * the next call to {@link Folks.PersonaStore.add_persona_from_details}. * * @since UNRELEASED */ public unowned AddPersonaFromDetailsMock? add_persona_from_details_mock { get; set; default = null; } /** * Type of a mock function for {@link Folks.PersonaStore.remove_persona}. * * See {@link FolksDummy.PersonaStore.remove_persona_mock}. * * @param persona the persona being removed from the store * @throws PersonaStoreError to be thrown from * {@link Folks.PersonaStore.remove_persona} * @return delay to apply to the remove persona operation (negative and zero * delays complete in an idle callback; positive * delays complete after that many milliseconds) * * @since UNRELEASED */ public delegate int RemovePersonaMock (Persona persona) throws PersonaStoreError; /** * Mock function for {@link Folks.PersonaStore.remove_persona}. * * This function is called whenever this store's * {@link Folks.PersonaStore.remove_persona} method is called. It allows * the caller to determine whether removing the given persona should fail, by * throwing an error from this mock function. If no error is thrown from this * function, removing the given persona will succeed. This is useful for * testing error handling of calls to * {@link Folks.PersonaStore.remove_persona}. * * See {@link FolksDummy.PersonaStore.add_persona_from_details_mock}. * * This mock function may be changed at any time; changes will take effect for * the next call to {@link Folks.PersonaStore.remove_persona}. * * @since UNRELEASED */ public unowned RemovePersonaMock? remove_persona_mock { get; set; default = null; } /** * Type of a mock function for {@link Folks.PersonaStore.prepare}. * * See {@link FolksDummy.PersonaStore.prepare_mock}. * * @throws PersonaStoreError to be thrown from * {@link Folks.PersonaStore.prepare} * @return delay to apply to the prepare operation (negative and zero delays * complete in an idle callback; positive * delays complete after that many milliseconds) * * @since UNRELEASED */ public delegate int PrepareMock () throws PersonaStoreError; /** * Mock function for {@link Folks.PersonaStore.prepare}. * * This function is called whenever this store's * {@link Folks.PersonaStore.prepare} method is called on an unprepared store. * It allows the caller to determine whether preparing the store should fail, * by throwing an error from this mock function. If no error is thrown from * this function, preparing the store will succeed (and all future calls to * {@link Folks.PersonaStore.prepare} will return immediately without calling * this mock function). This is useful for testing error handling of calls to * {@link Folks.PersonaStore.prepare}. * * See {@link FolksDummy.PersonaStore.add_persona_from_details_mock}. * * This mock function may be changed at any time; changes will take effect for * the next call to {@link Folks.PersonaStore.prepare}. * * @since UNRELEASED */ public unowned PrepareMock? prepare_mock { get; set; default = null; } private Type _persona_type = typeof (FolksDummy.Persona); /** * Type of programmatically created personas. * * This is the type used to create new personas when * {@link Folks.PersonaStore.add_persona_from_details} is called. It must be a * subtype of {@link FolksDummy.Persona}. * * This may be modified at any time, with modifications taking effect for the * next call to {@link Folks.PersonaStore.add_persona_from_details} or * {@link FolksDummy.PersonaStore.register_personas}. * * @since UNRELEASED */ public Type persona_type { get { return this._persona_type; } set { assert (value.is_a (typeof (FolksDummy.Persona))); if (this._persona_type != value) { this._persona_type = value; this.notify_property ("persona-type"); } } } /** * Set capabilities of the persona store. * * This sets the capabilities of the store, as if they were changed on a * backing store somewhere. This is intended to be used for testing code which * depends on the values of {@link Folks.PersonaStore.can_add_personas}, * {@link Folks.PersonaStore.can_alias_personas} and * {@link Folks.PersonaStore.can_remove_personas}. * * @param can_add_personas whether the store can handle adding personas * @param can_alias_personas whether the store can handle and update * user-specified persona aliases * @param can_remove_personas whether the store can handle removing personas * * @since UNRELEASED */ public void update_capabilities (MaybeBool can_add_personas, MaybeBool can_alias_personas, MaybeBool can_remove_personas) { this.freeze_notify (); if (can_add_personas != this._can_add_personas) { this._can_add_personas = can_add_personas; this.notify_property ("can-add-personas"); } if (can_alias_personas != this._can_alias_personas) { this._can_alias_personas = can_alias_personas; this.notify_property ("can-alias-personas"); } if (can_remove_personas != this._can_remove_personas) { this._can_remove_personas = can_remove_personas; this.notify_property ("can-remove-personas"); } this.thaw_notify (); } /** * Freeze persona changes in the store. * * This freezes externally-visible changes to the set of personas in the store * until {@link FolksDummy.PersonaStore.thaw_personas_changed} is called, at * which point all pending changes are made visible in the * {@link Folks.PersonaStore.personas} property and by emitting * {@link Folks.PersonaStore.personas_changed}. * * Calls to {@link FolksDummy.PersonaStore.freeze_personas_changed} and * {@link FolksDummy.PersonaStore.thaw_personas_changed} must be well-nested. * Pending changes will only be committed after the final call to * {@link FolksDummy.PersonaStore.thaw_personas_changed}. * * @see PersonaStore.thaw_personas_changed * @since UNRELEASED */ public void freeze_personas_changed () { this._personas_changed_frozen++; } /** * Thaw persona changes in the store. * * This thaws externally-visible changes to the set of personas in the store. * If the number of calls to * {@link FolksDummy.PersonaStore.thaw_personas_changed} matches the number of * calls to {@link FolksDummy.PersonaStore.freeze_personas_changed}, all * pending changes are committed and made externally-visible. * * @see PersonaStore.freeze_personas_changed * @since UNRELEASED */ public void thaw_personas_changed () { assert (this._personas_changed_frozen > 0); this._personas_changed_frozen--; if (this._personas_changed_frozen == 0) { /* Emit the queued changes. */ this._emit_personas_changed (this._pending_persona_registrations, this._pending_persona_unregistrations); this._pending_persona_registrations.clear (); this._pending_persona_unregistrations.clear (); } } /** * Register new personas with the persona store. * * This registers a set of personas as if they had just appeared in the * backing store. If the persona store is not frozen (see * {@link FolksDummy.PersonaStore.freeze_personas_changed}) the changes are * made externally visible on the store immediately (e.g. in the * {@link Folks.PersonaStore.personas} property and through a * {@link Folks.PersonaStore.personas_changed} signal). If the store is * frozen, the changes will be pending until the store is next unfrozen. * * All elements in the @personas set be of type * {@link FolksDummy.PersonaStore.persona_type}. * * @param personas set of personas to register * * @since UNRELEASED */ public void register_personas (Set personas) { Set added_personas; var emit_notifications = (this._personas_changed_frozen == 0); /* If the persona store has persona changes frozen, queue up the * personas and emit a notification about them later. */ if (emit_notifications == false) added_personas = this._pending_persona_registrations; else added_personas = new HashSet (); foreach (var persona in personas) { assert (persona.get_type ().is_a (this._persona_type)); /* Handle the case where a persona is unregistered while the store is * frozen, then registered again before it's unfrozen. */ if (this._pending_persona_unregistrations.remove (persona)) this._personas.unset (persona.iid); if (this._personas.has_key (persona.iid)) continue; added_personas.add (persona); if (emit_notifications == true) this._personas.set (persona.iid, persona); } if (added_personas.size > 0 && emit_notifications == true) this._emit_personas_changed (added_personas, null); } /** * Unregister existing personas with the persona store. * * This unregisters a set of personas as if they had just disappeared from the * backing store. If the persona store is not frozen (see * {@link FolksDummy.PersonaStore.freeze_personas_changed}) the changes are * made externally visible on the store immediately (e.g. in the * {@link Folks.PersonaStore.personas} property and through a * {@link Folks.PersonaStore.personas_changed} signal). If the store is * frozen, the changes will be pending until the store is next unfrozen. * * @param personas set of personas to unregister * * @since UNRELEASED */ public void unregister_personas (Set personas) { Set removed_personas; var emit_notifications = (this._personas_changed_frozen == 0); /* If the persona store has persona changes frozen, queue up the * personas and emit a notification about them later. */ if (emit_notifications == false) removed_personas = this._pending_persona_unregistrations; else removed_personas = new HashSet (); foreach (var _persona in personas) { /* Handle the case where a persona is registered while the store is * frozen, then unregistered before it's unfrozen. */ this._pending_persona_registrations.remove (_persona); Persona? persona = this._personas.get (_persona.iid); if (persona == null) continue; removed_personas.add ((!) persona); } /* Modify this._personas afterwards, just in case * personas == this._personas. */ if (removed_personas.size > 0 && emit_notifications == true) { foreach (var _persona in removed_personas) this._personas.unset (_persona.iid); this._emit_personas_changed (null, removed_personas); } } /** * Reach quiescence on the store. * * If the {@link Folks.PersonaStore.prepare} method has already been called on * the store, this causes the store to signal that it has reached quiescence * immediately. If the store has not yet been prepared, this will set a flag * to ensure that quiescence is reached as soon as * {@link Folks.PersonaStore.prepare} is called. * * This must be called before the store will reach quiescence. * * @since UNRELEASED */ public void reach_quiescence () { /* Can't reach quiescence until prepare() has been called. */ if (this._is_prepared == false) { this._quiescent_on_prepare = true; return; } /* The initial query is complete, so signal that we've reached * quiescence (even if there was an error). */ if (this._is_quiescent == false) { this._is_quiescent = true; this.notify_property ("is-quiescent"); } } /** * Update the {@link Folks.PersonaStore.is_user_set_default} property. * * Backend method for use by test code to simulate a backing-store-driven * change in the {@link Folks.PersonaStore.is_user_set_default} property. * * @param is_user_set_default new value for the property * * @since UNRELEASED */ public void update_is_user_set_default (bool is_user_set_default) { /* Implemented as an ‘update_*()’ method to make it more explicit that * this is for test driver use only. */ this.is_user_set_default = is_user_set_default; } /** * Update the {@link Folks.PersonaStore.trust_level} property. * * Backend method for use by test code to simulate a backing-store-driven * change in the {@link Folks.PersonaStore.trust_level} property. * * @param trust_level new value for the property * * @since UNRELEASED */ public void update_trust_level (PersonaStoreTrust trust_level) { /* Implemented as an ‘update_*()’ method to make it more explicit that * this is for test driver use only. */ this.trust_level = trust_level; } } address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/backend.mk0000644000015301777760000000002512321057324027127 0ustar pbusernogroup00000000000000BACKEND_NAME = dummy address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/CMakeLists.txt0000644000015301777760000000124312321057324027752 0ustar pbusernogroup00000000000000project(folks-dummy-lib) vala_precompile(LIB_DUMMY_VALA_C SOURCES internal_0_9_2.vala dummy-backend.vala dummy-full-persona.vala dummy-persona-store.vala dummy-persona.vala GENERATE_VAPI folks-dummy GENERATE_HEADER folks-dummy PACKAGES posix folks gee-0.8 gio-2.0 gobject-2.0 ) add_definitions(-DBACKEND_NAME="dummy") add_definitions(-fPIC) include_directories( ${CMAKE_SOURCE_DIR} ${GLIB_INCLUDE_DIRS} ${GIO_INCLUDE_DIRS} ${FOLKS_INCLUDE_DIRS} ) add_library(folks-dummy STATIC ${LIB_DUMMY_VALA_C} ) target_link_libraries(folks-dummy ${GLIB_LIBRARIES} ${GIO_LIBRARIES} ${FOLKS_LIBRARIES} ) address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/internal_0_9_2.vala0000644000015301777760000000623312321057324030567 0ustar pbusernogroup00000000000000/* * Copyright (C) 2011 Collabora Ltd. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see . * * Authors: * Raul Gutierrez Segales */ using GLib; using Gee; using Posix; namespace Folks.Internal { public static bool equal_sets (Set a, Set b) { if (a.size != b.size) return false; foreach (var a_elem in a) { if (!b.contains (a_elem)) return false; } return true; } #if ENABLE_PROFILING /* See: http://people.gnome.org/~federico/news-2006-03.html#timeline-tools */ private static void profiling_markv (string format, va_list args) { var formatted = format.vprintf (args); var str = "MARK: %s-%p: %s".printf (Environment.get_prgname (), Thread.self (), formatted); access (str, F_OK); } #endif /** * Emit a profiling point. * * This emits a profiling point with the given message (printf-style), which * can be picked up by profiling tools and timing information extracted. * * @param format printf-style message format * @param ... message arguments * @since 0.7.2 */ public static void profiling_point (string format, ...) { #if ENABLE_PROFILING var args = va_list (); Internal.profiling_markv (format, args); #endif } /** * Start a profiling block. * * This emits a profiling start point with the given message (printf-style), * which can be picked up by profiling tools and timing information extracted. * * This is typically used in a pair with {@link Internal.profiling_end} to * delimit blocks of processing which need timing. * * @param format printf-style message format * @param ... message arguments * @since 0.7.2 */ public static void profiling_start (string format, ...) { #if ENABLE_PROFILING var args = va_list (); Internal.profiling_markv ("START: " + format, args); #endif } /** * End a profiling block. * * This emits a profiling end point with the given message (printf-style), * which can be picked up by profiling tools and timing information extracted. * * This is typically used in a pair with {@link Internal.profiling_start} to * delimit blocks of processing which need timing. * * @param format printf-style message format * @param ... message arguments * @since 0.7.2 */ public static void profiling_end (string format, ...) { #if ENABLE_PROFILING var args = va_list (); Internal.profiling_markv ("END: " + format, args); #endif } } address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/dummy-backend.vala0000644000015301777760000002712712321057324030610 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Philip Withnall * Copyright (C) 2013 Collabora Ltd. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see . * * Authors: * Philip Withnall */ using Gee; using GLib; using Folks; extern const string BACKEND_NAME; /** * A backend which allows {@link FolksDummy.PersonaStore}s and * {@link FolksDummy.Persona}s to be programmatically created and manipulated, * for the purposes of testing the core of libfolks itself. * * This backend is not meant to be enabled in production use. The methods on * {@link FolksDummy.Backend} (and other classes) for programmatically * manipulating the backend's state are considered internal to libfolks and are * not stable. * * This backend maintains two sets of persona stores: the set of all persona * stores, and the set of enabled persona stores (which must be a subset of the * former). {@link FolksDummy.Backend.register_persona_stores} adds persona * stores to the set of all stores. Optionally it also enables them, adding them * to the set of enabled stores. The set of persona stores advertised by the * backend as {@link Folks.Backend.persona_stores} is the set of enabled stores. * libfolks may internally enable or disable stores using * {@link Folks.Backend.enable_persona_store}, * {@link Folks.Backend.disable_persona_store} * and {@link Folks.Backend.set_persona_stores}. The ``register_`` and * ``unregister_`` prefixes are commonly used for backend methods. * * The API in {@link FolksDummy} is unstable and may change wildly. It is * designed mostly for use by libfolks unit tests. * * @since UNRELEASED */ public class FolksDummy.Backend : Folks.Backend { private bool _is_prepared = false; private bool _prepare_pending = false; /* used for unprepare() too */ private bool _is_quiescent = false; private HashMap _all_persona_stores; private HashMap _enabled_persona_stores; private Map _enabled_persona_stores_ro; private const string[] _always_writable_properties = { "avatar", "birthday", "email-addresses", "full-name", "gender", "im-addresses", "is-favourite", "nickname", "phone-numbers", "postal-addresses", "roles", "structured-name", "local-ids", "location", "web-service-addresses", "notes", "groups", null }; /** * {@inheritDoc} * * @since UNRELEASED */ public Backend () { Object (); } construct { this._all_persona_stores = new HashMap (); this._enabled_persona_stores = new HashMap (); this._enabled_persona_stores_ro = this._enabled_persona_stores.read_only_view; } /** * Whether this Backend has been prepared. * * See {@link Folks.Backend.is_prepared}. * * @since UNRELEASED */ public override bool is_prepared { get { return this._is_prepared; } } /** * Whether this Backend has reached a quiescent state. * * See {@link Folks.Backend.is_quiescent}. * * @since UNRELEASED */ public override bool is_quiescent { get { return this._is_quiescent; } } /** * {@inheritDoc} * * @since UNRELEASED */ public override string name { get { return BACKEND_NAME; } } /** * {@inheritDoc} * * @since UNRELEASED */ public override Map persona_stores { get { return this._enabled_persona_stores_ro; } } /** * {@inheritDoc} * * @since UNRELEASED */ public override void disable_persona_store (Folks.PersonaStore store) { this._disable_persona_store (store); } /** * {@inheritDoc} * * @since UNRELEASED */ public override void enable_persona_store (Folks.PersonaStore store) { this._enable_persona_store ((FolksDummy.PersonaStore) store); } /** * {@inheritDoc} * * @since UNRELEASED */ public override void set_persona_stores (Set? store_ids) { /* If the set is empty, load all unloaded stores then return. */ if (store_ids == null) { this.freeze_notify (); foreach (var store in this._all_persona_stores.values) { this._enable_persona_store (store); } this.thaw_notify (); return; } /* First handle adding any missing persona stores. */ this.freeze_notify (); foreach (var id in store_ids) { if (!this._enabled_persona_stores.has_key (id)) { var store = this._all_persona_stores.get (id); if (store == null) { /* Create a new persona store. */ store = new FolksDummy.PersonaStore (id, id, FolksDummy.Backend._always_writable_properties); store.persona_type = typeof (FolksDummy.FullPersona); this._all_persona_stores.set (store.id, store); } this._enable_persona_store (store); } } /* Keep persona stores to remove in a separate array so we don't * invalidate the list we are iterating over. */ PersonaStore[] stores_to_remove = {}; foreach (var store in this._enabled_persona_stores.values) { if (!store_ids.contains (store.id)) { stores_to_remove += store; } } foreach (var store in stores_to_remove) { this._disable_persona_store (store); } this.thaw_notify (); } private void _enable_persona_store (PersonaStore store) { if (this._enabled_persona_stores.has_key (store.id)) { return; } assert (this._all_persona_stores.has_key (store.id)); store.removed.connect (this._store_removed_cb); this._enabled_persona_stores.set (store.id, store); this.persona_store_added (store); this.notify_property ("persona-stores"); } private void _disable_persona_store (Folks.PersonaStore store) { if (!this._enabled_persona_stores.unset (store.id)) { return; } assert (this._all_persona_stores.has_key (store.id)); this.persona_store_removed (store); this.notify_property ("persona-stores"); store.removed.disconnect (this._store_removed_cb); } private void _store_removed_cb (Folks.PersonaStore store) { this._disable_persona_store (store); } /** * {@inheritDoc} * * @since UNRELEASED */ public override async void prepare () throws GLib.Error { Internal.profiling_start ("preparing Dummy.Backend"); if (this._is_prepared || this._prepare_pending) { return; } try { this._prepare_pending = true; this.freeze_notify (); this._is_prepared = true; this.notify_property ("is-prepared"); this._is_quiescent = true; this.notify_property ("is-quiescent"); } finally { this.thaw_notify (); this._prepare_pending = false; } Internal.profiling_end ("preparing Dummy.Backend"); } /** * {@inheritDoc} * * @since UNRELEASED */ public override async void unprepare () throws GLib.Error { if (!this._is_prepared || this._prepare_pending) { return; } try { this._prepare_pending = true; this.freeze_notify (); foreach (var persona_store in this._enabled_persona_stores.values) { this._disable_persona_store (persona_store); } this._is_quiescent = false; this.notify_property ("is-quiescent"); this._is_prepared = false; this.notify_property ("is-prepared"); } finally { this.thaw_notify (); this._prepare_pending = false; } } /* * All the functions below here are to be used by testing code rather than by * libfolks clients. They form the interface which would normally be between * the Backend and a web service or backing store of some kind. */ /** * Register and enable some {@link FolksDummy.PersonaStore}s. * * For each of the persona stores in ``stores``, register it with this * backend. If ``enable_stores`` is ``true``, added stores will also be * enabled, emitting {@link Folks.Backend.persona_store_added} for each * newly-enabled store. After all addition signals are emitted, a change * notification for {@link Folks.Backend.persona_stores} will be emitted (but * only if at least one addition signal is emitted). * * Persona stores are identified by their {@link Folks.PersonaStore.id}; if a * store in ``stores`` has the same ID as a store previously registered * through this method, the duplicate will be ignored (so * {@link Folks.Backend.persona_store_added} won't be emitted for that store). * * Persona stores must be instances of {@link FolksDummy.PersonaStore} or * subclasses of it, allowing for different persona store implementations to * be tested. * * @param stores set of persona stores to register * @param enable_stores whether to automatically enable the stores * @since UNRELEASED */ public void register_persona_stores (Set stores, bool enable_stores = true) { this.freeze_notify (); foreach (var store in stores) { assert (store is FolksDummy.PersonaStore); if (this._all_persona_stores.has_key (store.id)) { continue; } this._all_persona_stores.set (store.id, store); if (enable_stores == true) { this._enable_persona_store (store); } } this.thaw_notify (); } /** * Disable and unregister some {@link FolksDummy.PersonaStore}s. * * For each of the persona stores in ``stores``, disable it (if it was * enabled) and unregister it from the backend so that it cannot be re-enabled * using {@link Folks.Backend.enable_persona_store} or * {@link Folks.Backend.set_persona_stores}. * * {@link Folks.Backend.persona_store_removed} will be emitted for all persona * stores in ``stores`` which were previously enabled. After all removal * signals are emitted, a change notification for * {@link Folks.Backend.persona_stores} will be emitted (but only if at least * one removal signal is emitted). * * @since UNRELEASED */ public void unregister_persona_stores (Set stores) { this.freeze_notify (); foreach (var store in stores) { assert (store is FolksDummy.PersonaStore); if (!this._all_persona_stores.has_key (store.id)) { continue; } this._disable_persona_store (store); this._all_persona_stores.unset (store.id); } this.thaw_notify (); } } address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/lib/dummy-persona.vala0000644000015301777760000002524112321057324030663 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Philip Withnall * Copyright (C) 2013 Collabora Ltd. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see . * * Authors: * Philip Withnall */ using Folks; using Gee; using GLib; /** * A persona subclass representing a single contact. * * This mocks up a ‘thin’ persona which implements none of the available * property interfaces provided by libfolks, and is designed as a base class to * be subclassed by personas which will implement one or more of these * interfaces. For example, {@link FolksDummy.FullPersona} is one such subclass * which implements all available interfaces. * * There are two sides to this class’ interface: the normal methods required by * {@link Folks.Persona}, such as * {@link Folks.Persona.linkable_property_to_links}, * and the backend methods which should be called by test driver code to * simulate changes in the backing store providing this persona, such as * {@link FolksDummy.Persona.update_writeable_properties}. The ``update_``, * ``register_`` and ``unregister_`` prefixes are commonly used for backend * methods. * * All property changes for contact details of subclasses of * {@link FolksDummy.Persona} have a configurable delay before taking effect, * which can be controlled by {@link FolksDummy.Persona.property_change_delay}. * * The API in {@link FolksDummy} is unstable and may change wildly. It is * designed mostly for use by libfolks unit tests. * * @since UNRELEASED */ public class FolksDummy.Persona : Folks.Persona { private string[] _linkable_properties = new string[0]; /** * {@inheritDoc} * * @since UNRELEASED */ public override string[] linkable_properties { get { return this._linkable_properties; } } private string[] _writeable_properties = new string[0]; /** * {@inheritDoc} * * @since UNRELEASED */ public override string[] writeable_properties { get { return this._writeable_properties; } } /** * Create a new persona. * * Create a new persona for the {@link FolksDummy.PersonaStore} ``store``, * with the given construct-only properties. * * The persona’s {@link Folks.Persona.writeable_properties} are initialised to * the given ``store``’s * {@link Folks.PersonaStore.always_writeable_properties}. They may be updated * afterwards using {@link FolksDummy.Persona.update_writeable_properties}. * * @param store the store which will contain the persona * @param contact_id a unique free-form string identifier for the persona * @param is_user ``true`` if the persona represents the user, ``false`` * otherwise * @param linkable_properties an array of names of the properties which should * be used for linking this persona to others * * @since UNRELEASED */ public Persona (PersonaStore store, string contact_id, bool is_user = false, string[] linkable_properties = {}) { var uid = Folks.Persona.build_uid (BACKEND_NAME, store.id, contact_id); var iid = store.id + ":" + contact_id; Object (display_id: contact_id, uid: uid, iid: iid, store: store, is_user: is_user); this._linkable_properties = linkable_properties; this._writeable_properties = this.store.always_writeable_properties; } /** * {@inheritDoc} * * @since UNRELEASED */ public override void linkable_property_to_links (string prop_name, Folks.Persona.LinkablePropertyCallback callback) { if (prop_name == "im-addresses") { var persona = this as ImDetails; assert (persona != null); foreach (var protocol in persona.im_addresses.get_keys ()) { var im_fds = persona.im_addresses.get (protocol); foreach (var im_fd in im_fds) { callback (protocol + ":" + im_fd.value); } } } else if (prop_name == "local-ids") { var persona = this as LocalIdDetails; assert (persona != null); foreach (var id in persona.local_ids) { callback (id); } } else if (prop_name == "web-service-addresses") { var persona = this as WebServiceDetails; assert (persona != null); foreach (var web_service in persona.web_service_addresses.get_keys ()) { var web_service_addresses = persona.web_service_addresses.get (web_service); foreach (var ws_fd in web_service_addresses) { callback (web_service + ":" + ws_fd.value); } } } else if (prop_name == "email-addresses") { var persona = this as EmailDetails; assert (persona != null); foreach (var email in persona.email_addresses) { callback (email.value); } } else { /* Chain up */ base.linkable_property_to_links (prop_name, callback); } } /* * All the functions below here are to be used by testing code rather than by * libfolks clients. They form the interface which would normally be between * the Persona and a web service or backing store of some kind. */ /** * Update the persona’s set of writeable properties. * * Update the {@link Folks.Persona.writeable_properties} property to contain * the union of {@link Folks.PersonaStore.always_writeable_properties} from * the persona’s store, and the given ``writeable_properties``. * * This should be used to simulate a change in the backing store for the * persona which affects the writeability of one or more of its properties. * * @since UNRELEASED */ public void update_writeable_properties (string[] writeable_properties) { var new_writeable_properties = new HashSet (); foreach (var p in this.store.always_writeable_properties) new_writeable_properties.add (p); foreach (var p in writeable_properties) new_writeable_properties.add (p); /* Check for changes. */ var changed = false; if (this._writeable_properties.length != new_writeable_properties.size) { changed = true; } else { foreach (var p in this._writeable_properties) { if (new_writeable_properties.contains (p) == false) { changed = true; break; } } } if (changed == true) { this._writeable_properties = new_writeable_properties.to_array (); this.notify_property ("writeable-properties"); } } public void update_linkable_properties (string[] linkable_properties) { var new_linkable_properties = new HashSet (); new_linkable_properties.add_all_array(linkable_properties); /* Check for changes. */ var changed = false; if (this._linkable_properties.length != new_linkable_properties.size) { changed = true; } else { foreach (var p in this._linkable_properties) { if (new_linkable_properties.contains (p) == false) { changed = true; break; } } } if (changed == true) { this._linkable_properties = new_linkable_properties.to_array (); this.notify_property ("linkable-properties"); } } /** * Delay between property changes and notifications. * * This sets an optional delay between client code requesting a property * change (e.g. by calling {@link Folks.NameDetails.change_nickname}) and the * property change taking place and a {@link Object.notify} signal being * emitted for it. * * Delays are in milliseconds. Negative delays mean that property change * notifications happen synchronously in the change method. A delay of 0 * means that property change notifications happen in an idle callback * immediately after the change method. A positive delay means that property * change notifications happen that many milliseconds after the change method * is called. * * @since UNRELEASED */ protected int property_change_delay { get; set; } /** * Callback to effect a property change in a backing store. * * This is called by {@link FolksDummy.Persona.change_property} after the * {@link FolksDummy.Persona.property_change_delay} has expired. It must * effect the property change in the simulated backing store, for example by * calling an ‘update’ method such as * {@link FolksDummy.FullPersona.update_nickname}. * * @since UNRELEASED */ protected delegate void ChangePropertyCallback (); /** * Change a property in the simulated backing store. * * This triggers a property change in the simulated backing store, applying * the current {@link FolksDummy.Persona.property_change_delay} before calling * the given ``callback`` which should actually effect the property change. * * @param property_name name of the property being changed * @param callback callback to call once the change delay has passed * @since UNRELEASED */ protected async void change_property (string property_name, ChangePropertyCallback callback) { if (this.property_change_delay < 0) { /* No delay. */ callback (); } else if (this.property_change_delay == 0) { /* Idle delay. */ Idle.add (() => { callback (); this.change_property.callback (); return false; }); yield; } else { /* Timed delay. */ Timeout.add (this.property_change_delay, () => { callback (); this.change_property.callback (); return false; }); yield; } } } address-book-service-0.1.1+14.04.20140408.3/3rd_party/folks/dummy/CMakeLists.txt0000644000015301777760000000027212321057324027205 0ustar pbusernogroup00000000000000# Remove any link flag to keep it compatible with folks, otherwise folks would not be able to load it set(CMAKE_MODULE_LINKER_FLAGS "") add_subdirectory(lib) add_subdirectory(backend) address-book-service-0.1.1+14.04.20140408.3/CMakeLists.txt0000644000015301777760000000435312321057334023032 0ustar pbusernogroup00000000000000project(contatos) cmake_minimum_required(VERSION 2.8.9) include(FindPkgConfig) # Standard install paths include(GNUInstallDirs) find_package(Qt5Core REQUIRED) find_program(DBUS_RUNNER dbus-test-runner) add_definitions(-DQT_NO_KEYWORDS) pkg_check_modules(GLIB REQUIRED glib-2.0>=2.32) pkg_check_modules(GIO REQUIRED gio-2.0>=2.32) pkg_check_modules(FOLKS REQUIRED folks>=0.9.0) pkg_check_modules(FOLKS_EDS REQUIRED folks-eds) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) add_definitions(-std=c++11) # Coverage tools OPTION(ENABLE_COVERAGE "Build with coverage analysis support" OFF) if(ENABLE_COVERAGE) message(STATUS "Using coverage flags") find_program(COVERAGE_COMMAND gcov) if(NOT COVERAGE_COMMAND) message(FATAL_ERROR "gcov command not found") endif() SET(CMAKE_C_FLAGS "-g -O0 -Wall -fprofile-arcs -ftest-coverage") SET(CMAKE_CXX_FLAGS "-g -O0 -Wall -fprofile-arcs -ftest-coverage") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") include(${CMAKE_SOURCE_DIR}/cmake/lcov.cmake) endif() # Address Sanitizer OPTION(ENABLE_ADDRSANITIZER "Build with address sanitizer support" OFF) if(ENABLE_ADDRSANITIZER) message(STATUS "Using address sanitizer flags") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fno-omit-frame-pointer") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address") endif() configure_file("${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") enable_testing() add_custom_target(check) add_custom_command(TARGET check COMMAND ctest -V WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) add_subdirectory(3rd_party) add_subdirectory(common) add_subdirectory(lib) add_subdirectory(src) add_subdirectory(contacts) add_subdirectory(data) if(CMAKE_SYSTEM_PROCESSOR STREQUAL "ppc") # Some tests fail when running on PPPC check bug #1294229 message(STATUS "Tests disable for ppc") else() add_subdirectory(tests) endif() configure_file(config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) address-book-service-0.1.1+14.04.20140408.3/COPYING0000644000015301777760000010451312321057324021323 0ustar pbusernogroup00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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, either version 3 of the License, or (at your option) any later version. 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . address-book-service-0.1.1+14.04.20140408.3/src/0000755000015301777760000000000012321057642021056 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/src/main.cpp0000644000015301777760000000301412321057334022502 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "addressbook.h" void contactServiceMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message) { Q_UNUSED(type); Q_UNUSED(context); Q_UNUSED(message); //nothing } int main(int argc, char** argv) { galera::AddressBook::init(); QCoreApplication app(argc, argv); // disable debug message if variable not exported if (qgetenv("ADDRESS_BOOK_SERVICE_DEBUG").isEmpty()) { qInstallMessageHandler(contactServiceMessageOutput); } // disable folks linking for now if (!qEnvironmentVariableIsSet("FOLKS_DISABLE_LINKING")) { qputenv("FOLKS_DISABLE_LINKING", "on"); } galera::AddressBook book; book.start(); app.connect(&book, SIGNAL(stopped()), SLOT(quit())); return app.exec(); } address-book-service-0.1.1+14.04.20140408.3/src/CMakeLists.txt0000644000015301777760000000126212321057324023614 0ustar pbusernogroup00000000000000project(address-book-service) set(CONTACTS_SERVICE_BIN address-book-service) set(CONTACTS_SERVICE_BIN_SRC main.cpp ) add_executable(${CONTACTS_SERVICE_BIN} ${CONTACTS_SERVICE_BIN_SRC} ) target_link_libraries(${CONTACTS_SERVICE_BIN} address-book-service-lib ${GLIB_LIBRARIES} ${GIO_LIBRARIES} ${FOLKS_LIBRARIES} ) qt5_use_modules(${CONTACTS_SERVICE_BIN} Core Contacts) include_directories( ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${address-book-service-lib_SOURCE_DIR} ${GLIB_INCLUDE_DIRS} ${GIO_INCLUDE_DIRS} ${FOLKS_INCLUDE_DIRS} ) install(TARGETS ${CONTACTS_SERVICE_BIN} RUNTIME DESTINATION ${CMAKE_INSTALL_FULL_LIBEXECDIR}) address-book-service-0.1.1+14.04.20140408.3/README0000644000015301777760000000002712321057324021143 0ustar pbusernogroup00000000000000canonical pim service. address-book-service-0.1.1+14.04.20140408.3/cmake_uninstall.cmake.in0000644000015301777760000000165412321057324025052 0ustar pbusernogroup00000000000000IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) STRING(REGEX REPLACE "\n" ";" files "${files}") FOREACH(file ${files}) MESSAGE(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"") IF(EXISTS "$ENV{DESTDIR}${file}") EXEC_PROGRAM( "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" OUTPUT_VARIABLE rm_out RETURN_VALUE rm_retval ) IF(NOT "${rm_retval}" STREQUAL 0) MESSAGE(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"") ENDIF(NOT "${rm_retval}" STREQUAL 0) ELSE(EXISTS "$ENV{DESTDIR}${file}") MESSAGE(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.") ENDIF(EXISTS "$ENV{DESTDIR}${file}") ENDFOREACH(file) address-book-service-0.1.1+14.04.20140408.3/common/0000755000015301777760000000000012321057642021557 5ustar pbusernogroup00000000000000address-book-service-0.1.1+14.04.20140408.3/common/dbus-service-defs.h0000644000015301777760000000216312321057324025241 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __DBUS_SERVICE_DEFS_H__ #define __DBUS_SERVICE_DEFS_H__ #define CPIM_SERVICE_NAME "com.canonical.pim" #define CPIM_ADDRESSBOOK_OBJECT_PATH "/com/canonical/pim/AddressBook" #define CPIM_ADDRESSBOOK_IFACE_NAME "com.canonical.pim.AddressBook" #define CPIM_ADDRESSBOOK_VIEW_OBJECT_PATH "/com/canonical/pim/AddressBookView" #define CPIM_ADDRESSBOOK_VIEW_IFACE_NAME "com.canonical.pim.AddressBookView" #endif address-book-service-0.1.1+14.04.20140408.3/common/vcard-parser.cpp0000644000015301777760000003466412321057324024666 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "vcard-parser.h" #include #include #include #include #include #include #include #include using namespace QtVersit; using namespace QtContacts; namespace { class ContactExporterDetailHandler : public QVersitContactExporterDetailHandlerV2 { public: virtual void detailProcessed(const QContact& contact, const QContactDetail& detail, const QVersitDocument& document, QSet* processedFields, QList* toBeRemoved, QList* toBeAdded) { Q_UNUSED(contact); Q_UNUSED(document); Q_UNUSED(processedFields); Q_UNUSED(toBeRemoved); // Export custom property PIDMAP if (detail.type() == QContactDetail::TypeSyncTarget) { QContactSyncTarget syncTarget = static_cast(detail); QVersitProperty prop; prop.setName(galera::VCardParser::PidMapFieldName); prop.setValue(syncTarget.syncTarget()); *toBeAdded << prop; } if (toBeAdded->size() == 0) { return; } // export detailUir as PID field if (!detail.detailUri().isEmpty()) { QVersitProperty &prop = toBeAdded->last(); QMultiHash params = prop.parameters(); params.insert(galera::VCardParser::PidFieldName, detail.detailUri()); prop.setParameters(params); } // export read-only info if (detail.accessConstraints().testFlag(QContactDetail::ReadOnly)) { QVersitProperty &prop = toBeAdded->last(); QMultiHash params = prop.parameters(); params.insert(galera::VCardParser::ReadOnlyFieldName, "YES"); prop.setParameters(params); } // export Irremovable info if (detail.accessConstraints().testFlag(QContactDetail::Irremovable)) { QVersitProperty &prop = toBeAdded->last(); QMultiHash params = prop.parameters(); params.insert(galera::VCardParser::IrremovableFieldName, "YES"); prop.setParameters(params); } switch (detail.type()) { case QContactDetail::TypeAvatar: { QContactAvatar avatar = static_cast(detail); QVersitProperty &prop = toBeAdded->last(); prop.insertParameter(QStringLiteral("VALUE"), QStringLiteral("URL")); prop.setValue(avatar.imageUrl().toString(QUrl::RemoveUserInfo)); break; } case QContactDetail::TypePhoneNumber: { QString prefName = galera::VCardParser::PreferredActionNames[QContactDetail::TypePhoneNumber]; QContactDetail prefPhone = contact.preferredDetail(prefName); if (prefPhone == detail) { QVersitProperty &prop = toBeAdded->last(); QMultiHash params = prop.parameters(); params.insert(galera::VCardParser::PrefParamName, "1"); prop.setParameters(params); } break; } default: break; } } virtual void contactProcessed(const QContact& contact, QVersitDocument* document) { Q_UNUSED(contact); document->removeProperties("X-QTPROJECT-EXTENDED-DETAIL"); } }; class ContactImporterPropertyHandler : public QVersitContactImporterPropertyHandlerV2 { public: virtual void propertyProcessed(const QVersitDocument& document, const QVersitProperty& property, const QContact& contact, bool *alreadyProcessed, QList* updatedDetails) { Q_UNUSED(document); Q_UNUSED(contact); if (!*alreadyProcessed && (property.name() == galera::VCardParser::PidMapFieldName)) { QContactSyncTarget target; target.setSyncTarget(property.value()); *updatedDetails << target; *alreadyProcessed = true; } if (!*alreadyProcessed) { return; } QString pid = property.parameters().value(galera::VCardParser::PidFieldName); if (!pid.isEmpty()) { QContactDetail &det = updatedDetails->last(); det.setDetailUri(pid); } bool ro = (property.parameters().value(galera::VCardParser::ReadOnlyFieldName, "NO") == "YES"); bool irremovable = (property.parameters().value(galera::VCardParser::IrremovableFieldName, "NO") == "YES"); if (ro && irremovable) { QContactDetail &det = updatedDetails->last(); QContactManagerEngine::setDetailAccessConstraints(&det, QContactDetail::ReadOnly | QContactDetail::Irremovable); } else if (ro) { QContactDetail &det = updatedDetails->last(); QContactManagerEngine::setDetailAccessConstraints(&det, QContactDetail::ReadOnly); } else if (irremovable) { QContactDetail &det = updatedDetails->last(); QContactManagerEngine::setDetailAccessConstraints(&det, QContactDetail::Irremovable); } if (updatedDetails->size() == 0) { return; } // Remove empty phone and address subtypes QContactDetail &det = updatedDetails->last(); switch (det.type()) { case QContactDetail::TypePhoneNumber: { QContactPhoneNumber phone = static_cast(det); if (phone.subTypes().isEmpty()) { det.setValue(QContactPhoneNumber::FieldSubTypes, QVariant()); } if (property.parameters().contains(galera::VCardParser::PrefParamName)) { m_prefferedPhone = phone; } break; } case QContactDetail::TypeAvatar: { QString value = property.parameters().value("VALUE"); if (value == "URL") { det.setValue(QContactAvatar::FieldImageUrl, QUrl(property.value())); } break; } default: break; } } virtual void documentProcessed(const QVersitDocument& document, QContact* contact) { Q_UNUSED(document); Q_UNUSED(contact); if (!m_prefferedPhone.isEmpty()) { contact->setPreferredDetail(galera::VCardParser::PreferredActionNames[QContactDetail::TypePhoneNumber], m_prefferedPhone); m_prefferedPhone = QContactDetail(); } } private: QContactDetail m_prefferedPhone; }; } namespace galera { const QString VCardParser::PidMapFieldName = QStringLiteral("CLIENTPIDMAP"); const QString VCardParser::PidFieldName = QStringLiteral("PID"); const QString VCardParser::PrefParamName = QStringLiteral("PREF"); const QString VCardParser::IrremovableFieldName = QStringLiteral("IRREMOVABLE"); const QString VCardParser::ReadOnlyFieldName = QStringLiteral("READ-ONLY"); static QMap prefferedActions() { QMap values; values.insert(QContactDetail::TypeAddress, QStringLiteral("ADR")); values.insert(QContactDetail::TypeEmailAddress, QStringLiteral("EMAIL")); values.insert(QContactDetail::TypeNote, QStringLiteral("NOTE")); values.insert(QContactDetail::TypeOnlineAccount, QStringLiteral("IMPP")); values.insert(QContactDetail::TypeOrganization, QStringLiteral("ORG")); values.insert(QContactDetail::TypePhoneNumber, QStringLiteral("TEL")); values.insert(QContactDetail::TypeUrl, QStringLiteral("URL")); return values; } const QMap VCardParser::PreferredActionNames = prefferedActions(); VCardParser::VCardParser(QObject *parent) : QObject(parent), m_versitWriter(0), m_versitReader(0) { } VCardParser::~VCardParser() { if (m_versitReader) { m_versitReader->waitForFinished(); } if (m_versitWriter) { m_versitWriter->waitForFinished(); } } QList VCardParser::vcardToContactSync(const QStringList &vcardList) { QString vcards = vcardList.join("\r\n"); QVersitReader reader(vcards.toUtf8()); if (!reader.startReading()) { return QList(); } else { reader.waitForFinished(); QList documents = reader.results(); QVersitContactImporter contactImporter; contactImporter.setPropertyHandler(new ContactImporterPropertyHandler); if (!contactImporter.importDocuments(documents)) { qWarning() << "Fail to import contacts"; return QList(); } return contactImporter.contacts(); } } QtContacts::QContact VCardParser::vcardToContact(const QString &vcard) { QList contacts = vcardToContactSync(QStringList() << vcard); if (contacts.size()) { return contacts[0]; } else { return QContact(); } } void VCardParser::vcardToContact(const QStringList &vcardList) { if (m_versitReader) { qWarning() << "Import operation in progress."; return; } QString vcards = vcardList.join("\r\n"); m_versitReader = new QVersitReader(vcards.toUtf8()); connect(m_versitReader, &QVersitReader::resultsAvailable, this, &VCardParser::onReaderResultsAvailable); connect(m_versitReader, &QVersitReader::stateChanged, this, &VCardParser::onReaderStateChanged); m_versitReader->startReading(); } void VCardParser::onReaderResultsAvailable() { //NOTHING FOR NOW } QStringList VCardParser::splitVcards(const QByteArray &vcardList) { QStringList result; int start = 0; while(start < vcardList.size()) { int pos = vcardList.indexOf("BEGIN:VCARD", start + 1); if (pos == -1) { pos = vcardList.length(); } QByteArray vcard = vcardList.mid(start, (pos - start)); result << vcard; start = pos; } return result; } void VCardParser::onReaderStateChanged(QVersitReader::State state) { if (state == QVersitReader::FinishedState) { QList documents = m_versitReader->results(); QVersitContactImporter contactImporter; contactImporter.setPropertyHandler(new ContactImporterPropertyHandler); if (!contactImporter.importDocuments(documents)) { qWarning() << "Fail to import contacts"; return; } Q_EMIT contactsParsed(contactImporter.contacts()); delete m_versitReader; m_versitReader = 0; } } void VCardParser::contactToVcard(QList contacts) { QStringList result; if (m_versitWriter) { qWarning() << "Export operation in progress."; return; } QVersitContactExporter exporter; exporter.setDetailHandler(new ContactExporterDetailHandler); if (!exporter.exportContacts(contacts, QVersitDocument::VCard30Type)) { qWarning() << "Fail to export contacts" << exporter.errors(); return; } m_versitWriter = new QVersitWriter(&m_vcardData); connect(m_versitWriter, &QVersitWriter::stateChanged, this, &VCardParser::onWriterStateChanged); m_versitWriter->startWriting(exporter.documents()); } void VCardParser::onWriterStateChanged(QVersitWriter::State state) { if (state == QVersitWriter::FinishedState) { QStringList vcards = VCardParser::splitVcards(m_vcardData); Q_EMIT vcardParsed(vcards); delete m_versitWriter; m_versitWriter = 0; } } QStringList VCardParser::contactToVcardSync(QList contacts) { QVersitContactExporter exporter; exporter.setDetailHandler(new ContactExporterDetailHandler); if (!exporter.exportContacts(contacts, QVersitDocument::VCard30Type)) { qWarning() << "Fail to export contacts" << exporter.errors(); return QStringList(); } QByteArray vcardData; QVersitWriter versitWriter(&vcardData); versitWriter.startWriting(exporter.documents()); versitWriter.waitForFinished(); return VCardParser::splitVcards(vcardData); } QString VCardParser::contactToVcard(const QContact &contact) { QStringList vcards = VCardParser::contactToVcardSync(QList() << contact); if (vcards.size()) { return vcards[0]; } else { return QString(); } } } //namespace address-book-service-0.1.1+14.04.20140408.3/common/sort-clause.cpp0000644000015301777760000001603212321057324024523 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "sort-clause.h" #include #include #include #include using namespace QtContacts; namespace galera { static QMap > clauseFieldMap; SortClause::SortClause(const QString &sort) { initialize(); Q_FOREACH(QString sortClause, sort.split(",")) { QContactSortOrder sOrder = fromString(sortClause); if (sOrder.isValid()) { m_sortOrders << sOrder; } } } SortClause::SortClause(QList sort) : m_sortOrders(sort) { initialize(); } SortClause::SortClause(const SortClause &other) : m_sortOrders(other.m_sortOrders) { initialize(); } QString SortClause::toString() const { QString result; Q_FOREACH(QContactSortOrder sortOrder, m_sortOrders) { result += toString(sortOrder) + ", "; } if (result.endsWith(", ")) { result = result.mid(0, result.size() - 2); } return result; } QtContacts::QContactSortOrder SortClause::fromString(const QString &clause) const { QStringList sort = clause.trimmed().split(" "); if ((sort.count() == 0) || (sort.count() > 2)) { qWarning() << "Invalid sort clause:" << clause; return QContactSortOrder(); } QString fieldName = sort[0].trimmed().toUpper(); QString orderName = (sort.count() == 2 ? sort[1].trimmed().toUpper() : "ASC"); QtContacts::QContactSortOrder sOrder; if (clauseFieldMap.contains(fieldName)) { QPair details = clauseFieldMap[fieldName]; sOrder.setDetailType(details.first, details.second); Qt::SortOrder order = (orderName == "DESC" ? Qt::DescendingOrder : Qt::AscendingOrder); sOrder.setDirection(order); sOrder.setCaseSensitivity(Qt::CaseInsensitive); return sOrder; } else { qWarning() << "Invalid sort field:" << sort[0]; return QContactSortOrder(); } } QList SortClause::toContactSortOrder() const { return m_sortOrders; } QStringList SortClause::supportedFields() { initialize(); return clauseFieldMap.keys(); } void SortClause::initialize() { if (clauseFieldMap.isEmpty()) { clauseFieldMap["NAME_PREFIX"] = QPair(QContactDetail::TypeName, QContactName::FieldPrefix); clauseFieldMap["FIRST_NAME"] = QPair(QContactDetail::TypeName, QContactName::FieldFirstName); clauseFieldMap["MIDLE_NAME"] = QPair(QContactDetail::TypeName, QContactName::FieldMiddleName); clauseFieldMap["LAST_NAME"] = QPair(QContactDetail::TypeName, QContactName::FieldLastName); clauseFieldMap["NAME_SUFFIX"] = QPair(QContactDetail::TypeName, QContactName::FieldSuffix); clauseFieldMap["FULL_NAME"] = QPair(QContactDetail::TypeDisplayLabel, QContactDisplayLabel::FieldLabel); clauseFieldMap["NICKNAME"] = QPair(QContactDetail::TypeNickname, QContactNickname::FieldNickname); clauseFieldMap["BIRTHDAY"] = QPair(QContactDetail::TypeBirthday, QContactBirthday::FieldBirthday); clauseFieldMap["PHOTO"] = QPair(QContactDetail::TypeAvatar, QContactAvatar::FieldImageUrl); clauseFieldMap["ORG_ROLE"] = QPair(QContactDetail::TypeOrganization, QContactOrganization::FieldRole); clauseFieldMap["ORG_NAME"] = QPair(QContactDetail::TypeOrganization, QContactOrganization::FieldName); clauseFieldMap["ORG_DEPARTMENT"]= QPair(QContactDetail::TypeOrganization, QContactOrganization::FieldDepartment); clauseFieldMap["ORG_LOCATION"] = QPair(QContactDetail::TypeOrganization, QContactOrganization::FieldLocation); clauseFieldMap["ORG_TITLE"] = QPair(QContactDetail::TypeOrganization, QContactOrganization::FieldTitle); clauseFieldMap["EMAIL"] = QPair(QContactDetail::TypeEmailAddress, QContactEmailAddress::FieldEmailAddress); clauseFieldMap["PHONE"] = QPair(QContactDetail::TypePhoneNumber, QContactPhoneNumber::FieldNumber); clauseFieldMap["ADDR_STREET"] = QPair(QContactDetail::TypeAddress, QContactAddress::FieldStreet); clauseFieldMap["ADDR_LOCALITY"] = QPair(QContactDetail::TypeAddress, QContactAddress::FieldLocality); clauseFieldMap["ADDR_REGION"] = QPair(QContactDetail::TypeAddress, QContactAddress::FieldRegion); clauseFieldMap["ADDR_COUNTRY"] = QPair(QContactDetail::TypeAddress, QContactAddress::FieldCountry); clauseFieldMap["ADDR_POSTCODE"] = QPair(QContactDetail::TypeAddress, QContactAddress::FieldPostcode); clauseFieldMap["ADDR_POST_OFFICE_BOX"] = QPair(QContactDetail::TypeAddress, QContactAddress::FieldPostOfficeBox); clauseFieldMap["IM_URI"] = QPair(QContactDetail::TypeOnlineAccount, QContactOnlineAccount::FieldAccountUri); clauseFieldMap["IM_PROTOCOL"] = QPair(QContactDetail::TypeOnlineAccount, QContactOnlineAccount::FieldProtocol); clauseFieldMap["URL"] = QPair(QContactDetail::TypeUrl, QContactUrl::FieldUrl); } } QString SortClause::toString(const QContactSortOrder &sort) const { QPair clausePair = qMakePair(sort.detailType(), sort.detailField()); Q_FOREACH(QString key, clauseFieldMap.keys()) { if (clauseFieldMap[key] == clausePair) { return key + (sort.direction() == Qt::AscendingOrder ? " ASC" : " DESC"); } } return ""; } } address-book-service-0.1.1+14.04.20140408.3/common/fetch-hint.h0000644000015301777760000000312412321057324023756 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_FETCH_HINT_H__ #define __GALERA_FETCH_HINT_H__ #include #include #include namespace galera { class FetchHint { public: FetchHint(const QtContacts::QContactFetchHint &hint); FetchHint(const QString &hint); FetchHint(const FetchHint &other); FetchHint(); bool isEmpty() const; QString toString() const; QStringList fields() const; QtContacts::QContactFetchHint toContactFetchHint() const; static QMap contactFieldNames(); static QList parseFieldNames(const QStringList &fieldNames); private: QtContacts::QContactFetchHint m_hint; QString m_strHint; QStringList m_fields; void update(); static QtContacts::QContactFetchHint buildFilter(const QString &originalHint); }; } #endif address-book-service-0.1.1+14.04.20140408.3/common/vcard-parser.h0000644000015301777760000000455112321057324024323 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_VCARD_PARSER_H__ #define __GALERA_VCARD_PARSER_H__ #include #include #include #include #include #include namespace galera { class VCardParser : public QObject { Q_OBJECT public: VCardParser(QObject *parent=0); ~VCardParser(); void contactToVcard(QList contacts); void vcardToContact(const QStringList &vcardList); static const QString PidMapFieldName; static const QString PidFieldName; static const QString PrefParamName; static const QString IrremovableFieldName; static const QString ReadOnlyFieldName; static const QMap PreferredActionNames; static QtContacts::QContact vcardToContact(const QString &vcard); static QList vcardToContactSync(const QStringList &vcardList); static QString contactToVcard(const QtContacts::QContact &contact); static QStringList contactToVcardSync(QList contacts); Q_SIGNALS: void vcardParsed(const QStringList &vcards); void contactsParsed(QList contacts); void finished(); private Q_SLOTS: void onWriterStateChanged(QtVersit::QVersitWriter::State state); void onReaderStateChanged(QtVersit::QVersitReader::State state); void onReaderResultsAvailable(); private: QtVersit::QVersitWriter *m_versitWriter; QtVersit::QVersitReader *m_versitReader; QByteArray m_vcardData; static QStringList splitVcards(const QByteArray &vcardList); }; } Q_DECLARE_METATYPE(QList) #endif address-book-service-0.1.1+14.04.20140408.3/common/fetch-hint.cpp0000644000015301777760000001017412321057324024314 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "fetch-hint.h" #include #include using namespace QtContacts; namespace galera { FetchHint::FetchHint() { //empty } FetchHint::FetchHint(const QtContacts::QContactFetchHint &hint) : m_hint(hint) { update(); } bool FetchHint::isEmpty() const { return m_strHint.isEmpty(); } FetchHint::FetchHint(const QString &hint) : m_hint(buildFilter(hint)) { update(); } FetchHint::FetchHint(const FetchHint &other) : m_hint(other.m_hint) { update(); } QString FetchHint::toString() const { return m_strHint; } QStringList FetchHint::fields() const { return m_fields; } void FetchHint::update() { m_strHint.clear(); m_fields.clear(); QMap map = contactFieldNames(); Q_FOREACH(QContactDetail::DetailType type, m_hint.detailTypesHint()) { QString fieldName = map.key(type, ""); if (!fieldName.isEmpty()) { m_fields << fieldName; } } if (!m_fields.isEmpty()) { m_strHint = QString("FIELDS:") + m_fields.join(","); } } QtContacts::QContactFetchHint FetchHint::toContactFetchHint() const { return m_hint; } QMap FetchHint::contactFieldNames() { static QMap map; if (map.isEmpty()) { map.insert("ADR", QContactAddress::Type); map.insert("BDAY", QContactBirthday::Type); map.insert("EMAIL", QContactEmailAddress::Type); map.insert("FN", QContactDisplayLabel::Type); map.insert("GENDER", QContactGender::Type); map.insert("N", QContactName::Type); map.insert("NICKNAME", QContactNickname::Type); map.insert("NOTE", QContactNote::Type); map.insert("ORG", QContactOrganization::Type); map.insert("PHOTO", QContactAvatar::Type); map.insert("TEL", QContactPhoneNumber::Type); map.insert("URL", QContactUrl::Type); } return map; } QList FetchHint::parseFieldNames(const QStringList &fieldNames) { QList result; const QMap map = contactFieldNames(); Q_FOREACH(QString fieldName, fieldNames) { if (map.contains(fieldName)) { result << map[fieldName]; } } return result; } // Parse string // Format: :VALUE0,VALUE1;:VALUE0,VALUE1 QtContacts::QContactFetchHint FetchHint::buildFilter(const QString &originalHint) { QContactFetchHint result; if (!originalHint.isEmpty()) { QString hint = QString(originalHint).replace(" ",""); QStringList groups = hint.split(";"); Q_FOREACH(QString group, groups) { QStringList values = group.split(":"); if (values.count() == 2) { if (values[0] == "FIELDS") { QList fields; QMap map = contactFieldNames(); Q_FOREACH(QString field, values[1].split(",")) { if (map.contains(field)) { fields << map[field]; } } result.setDetailTypesHint(fields); } } else { qWarning() << "invalid fech hint: " << values; } } } return result; } } address-book-service-0.1.1+14.04.20140408.3/common/CMakeLists.txt0000644000015301777760000000071212321057324024314 0ustar pbusernogroup00000000000000set(GALERA_COMMON_LIB galera-common) set(GALERA_COMMON_LIB_SRC filter.cpp fetch-hint.cpp sort-clause.cpp source.cpp vcard-parser.cpp ) set(GALERA_COMMON_LIB_HEADERS filter.h fetch-hint.h sort-clause.h source.h vcard-parser.h dbus-service-defs.h ) add_library(${GALERA_COMMON_LIB} STATIC ${GALERA_COMMON_LIB_SRC} ${GALERA_COMMON_LIB_HEADERS} ) qt5_use_modules(${GALERA_COMMON_LIB} Core Versit Contacts) address-book-service-0.1.1+14.04.20140408.3/common/filter.cpp0000644000015301777760000000732512321057324023554 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "filter.h" #include #include #include #include #include #include #include #include using namespace QtContacts; namespace galera { Filter::Filter(const QString &filter) { m_filter = buildFilter(filter); } Filter::Filter(const QtContacts::QContactFilter &filter) { m_filter = parseFilter(filter); } QString Filter::toString() const { return toString(m_filter); } QtContacts::QContactFilter Filter::toContactFilter() const { return m_filter; } bool Filter::test(const QContact &contact) const { return QContactManagerEngine::testFilter(m_filter, contact); } bool Filter::isValid() const { return (m_filter.type() != QContactFilter::InvalidFilter); } QString Filter::toString(const QtContacts::QContactFilter &filter) { QByteArray filterArray; QDataStream filterData(&filterArray, QIODevice::WriteOnly); filterData << filter; return QString::fromLatin1(filterArray.toBase64()); } QtContacts::QContactFilter Filter::buildFilter(const QString &filter) { QContactFilter filterObject; QByteArray filterArray = QByteArray::fromBase64(filter.toLatin1()); QDataStream filterData(&filterArray, QIODevice::ReadOnly); filterData >> filterObject; return filterObject; } QtContacts::QContactFilter Filter::parseFilter(const QtContacts::QContactFilter &filter) { QContactUnionFilter newFilter; switch (filter.type()) { case QContactFilter::IdFilter: newFilter = parseIdFilter(filter); break; case QContactFilter::UnionFilter: newFilter = parseUnionFilter(filter); break; default: return filter; } return newFilter; } QtContacts::QContactFilter Filter::parseUnionFilter(const QtContacts::QContactFilter &filter) { QContactUnionFilter newFilter; const QContactUnionFilter *unionFilter = static_cast(&filter); Q_FOREACH(QContactFilter f, unionFilter->filters()) { newFilter << parseFilter(f); } return newFilter; } QtContacts::QContactFilter Filter::parseIdFilter(const QContactFilter &filter) { // ContactId to be serialized between process is necessary to instantiate the manager in both sides. // Since the dbus service does not instantiate the manager we translate it to QContactDetailFilter // using Guid values. This is possible because our server use the Guid to build the contactId. const QContactIdFilter *idFilter = static_cast(&filter); QContactUnionFilter newFilter; Q_FOREACH(QContactId id, idFilter->ids()) { QContactDetailFilter detailFilter; detailFilter.setMatchFlags(QContactFilter::MatchExactly); detailFilter.setDetailType(QContactDetail::TypeGuid, QContactGuid::FieldGuid); detailFilter.setValue(id.toString().split(":").last()); newFilter << detailFilter; } return newFilter; } } address-book-service-0.1.1+14.04.20140408.3/common/source.h0000644000015301777760000000331012321057324023222 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_SOURCE_H__ #define __GALERA_SOURCE_H__ #include #include namespace galera { class Source { public: Source(); Source(const Source &other); Source(QString id, const QString &displayName, bool isReadOnly, bool isPrimary); friend QDBusArgument &operator<<(QDBusArgument &argument, const Source &source); friend const QDBusArgument &operator>>(const QDBusArgument &argument, Source &source); static void registerMetaType(); QString id() const; QString displayLabel() const; bool isReadOnly() const; bool isValid() const; bool isPrimary() const; private: QString m_id; QString m_displayName; bool m_isReadOnly; bool m_isPrimary; }; typedef QList SourceList; QDBusArgument &operator<<(QDBusArgument &argument, const SourceList &sources); const QDBusArgument &operator>>(const QDBusArgument &argument, SourceList &sources); } // namespace galera Q_DECLARE_METATYPE(galera::Source) Q_DECLARE_METATYPE(galera::SourceList) #endif address-book-service-0.1.1+14.04.20140408.3/common/filter.h0000644000015301777760000000344412321057324023217 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_FILTER_H__ #define __GALERA_FILTER_H__ #include #include namespace galera { class Filter { public: Filter(const QtContacts::QContactFilter &filter); Filter(const QString &filter); Filter(const Filter &other); QString toString() const; QtContacts::QContactFilter toContactFilter() const; bool test(const QtContacts::QContact &contact) const; bool isValid() const; private: QtContacts::QContactFilter m_filter; Filter(); static QString toString(const QtContacts::QContactFilter &filter); static QtContacts::QContactFilter buildFilter(const QString &filter); static QString detailFilterToString(const QtContacts::QContactFilter &filter); static QString unionFilterToString(const QtContacts::QContactFilter &filter); static QtContacts::QContactFilter parseFilter(const QtContacts::QContactFilter &filter); static QtContacts::QContactFilter parseIdFilter(const QtContacts::QContactFilter &filter); static QtContacts::QContactFilter parseUnionFilter(const QtContacts::QContactFilter &filter); }; } #endif address-book-service-0.1.1+14.04.20140408.3/common/source.cpp0000644000015301777760000000553412321057324023567 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 "source.h" namespace galera { Source::Source() : m_isReadOnly(false) { } Source::Source(const Source &other) : m_id(other.id()), m_displayName(other.displayLabel()), m_isReadOnly(other.isReadOnly()), m_isPrimary(other.isPrimary()) { } Source::Source(QString id, const QString &displayName, bool isReadOnly, bool isPrimary) : m_id(id), m_displayName(displayName), m_isReadOnly(isReadOnly), m_isPrimary(isPrimary) { Q_ASSERT(displayName.isEmpty() == false); } bool Source::isValid() const { return !m_id.isEmpty(); } bool Source::isPrimary() const { return m_isPrimary; } QString Source::id() const { return m_id; } QString Source::displayLabel() const { return m_displayName; } bool Source::isReadOnly() const { return m_isReadOnly; } void Source::registerMetaType() { qRegisterMetaType("Source"); qRegisterMetaType("SourceList"); qDBusRegisterMetaType(); qDBusRegisterMetaType(); } QDBusArgument &operator<<(QDBusArgument &argument, const Source &source) { argument.beginStructure(); argument << source.m_id; argument << source.m_displayName; argument << source.m_isReadOnly; argument << source.m_isPrimary; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, Source &source) { argument.beginStructure(); argument >> source.m_id; argument >> source.m_displayName; argument >> source.m_isReadOnly; argument >> source.m_isPrimary; argument.endStructure(); return argument; } QDBusArgument &operator<<(QDBusArgument &argument, const SourceList &sources) { argument.beginArray(qMetaTypeId()); for(int i=0; i < sources.count(); ++i) { argument << sources[i]; } argument.endArray(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, SourceList &sources) { argument.beginArray(); sources.clear(); while(!argument.atEnd()) { Source source; argument >> source; sources << source; } argument.endArray(); return argument; } } // namespace Galera address-book-service-0.1.1+14.04.20140408.3/common/sort-clause.h0000644000015301777760000000265212321057324024173 0ustar pbusernogroup00000000000000/* * Copyright 2013 Canonical Ltd. * * This file is part of contact-service-app. * * contact-service-app 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. * * contact-service-app 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 . */ #ifndef __GALERA_SORT_CLAUSE_H__ #define __GALERA_SORT_CLAUSE_H__ #include #include #include namespace galera { class ContactEntry; class SortClause { public: SortClause(const QString &sort); SortClause(QList sort); SortClause(const SortClause &other); QString toString() const; QList toContactSortOrder() const; static QStringList supportedFields(); private: QList m_sortOrders; QtContacts::QContactSortOrder fromString(const QString &clause) const; QString toString(const QtContacts::QContactSortOrder &sort) const; static void initialize(); }; } #endif