Ejemplo n.º 1
0
void TestBirthdayPlugin::testChangeName()
{
    const QString contactID = QUuid::createUuid().toString();
    const QDateTime contactBirthDate = QDateTime::currentDateTime();

    // Add contact with birthday to tracker.
    QContactName contactName;
    contactName.setFirstName(contactID);
    QContactBirthday contactBirthday;
    contactBirthday.setDateTime(contactBirthDate);
    QContact contact;
    QVERIFY(contact.saveDetail(&contactName));
    QVERIFY(contact.saveDetail(&contactBirthday));
    QVERIFY2(mManager->saveContact(&contact), "Error saving contact to tracker");

    // Wait until calendar event gets to calendar.
    loopWait(calendarTimeout);

    // Open calendar database.
    mKCal::ExtendedCalendar::Ptr calendar =
        mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone()));
    mKCal::ExtendedStorage::Ptr storage =
        mKCal::ExtendedCalendar::defaultStorage(calendar);
    storage->open();
    QVERIFY2(not storage->notebook(calNotebookId).isNull(), "No calendar database found");

    // Check calendar database for contact.
    QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook");
    KCalCore::Event::List eventList = calendar->events();
    QCOMPARE(countCalendarEvents(eventList, contact), 1);

    // Change the contact name and see if the calendar is updated.
    const QString newContactID = QUuid::createUuid().toString();
    contactName.setFirstName(newContactID);
    QVERIFY(contact.saveDetail(&contactName));
    // TODO: Should it be necessary to refetch the contact to get the synthesised displayLabel?
    contact = mManager->contact(apiId(contact));
    QVERIFY2(mManager->saveContact(&contact), "Unable to update test contact in tracker");

    // Wait until calendar event gets to calendar.
    loopWait(calendarTimeout);

    // Search for any events in the calendar.
    QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook");
    eventList = calendar->events();
    QCOMPARE(countCalendarEvents(eventList, contact), 1);

    // Close the calendar.
    QVERIFY2(storage->close(), "Error closing the calendar");
}
Ejemplo n.º 2
0
void SymbianPluginPerfomance::createSimpleContacts()
{
    // Create N contacts
    QList<QContact> contactsList;

    for(int i=0; i<NO_OF_CONTACTS; i++) {
        QString c = QString::number(i);
        QString first("Alice");
        QContact alice;

        // Contact details
        QContactName aliceName;
        aliceName.setFirstName(first.append(c));
        alice.saveDetail(&aliceName);

        contactsList.append(alice);
    }

    // Save the contacts
    mTime.start();
    mCntMng->saveContacts(&contactsList, 0);
    int elapsed = mTime.elapsed();
    qDebug() << "Created " << contactsList.count() << " simple contacts in"
        << elapsed / 1000 << "s" << elapsed % 1000 << "ms";
}
Ejemplo n.º 3
0
void MT_CntVersitMyCardPlugin::exportOwnContact()
{
    //create contact
    QContact phonecontact;
    QContactName contactName;
    contactName.setFirstName("Jo");
    contactName.setLastName("Black");
    phonecontact.saveDetail(&contactName);
    QContactPhoneNumber number;
    number.setContexts("Home");
    number.setSubTypes("Mobile");
    number.setNumber("+02644424429");
    phonecontact.saveDetail(&number);
    
    //set MyCard detail
    QContactDetail myCard(MYCARD_DEFINTION_NAME);
    phonecontact.saveDetail(&myCard);
    
    //export
    QList<QContact> list;
    list.append(phonecontact);
    QVersitContactExporter exporter;
    QVERIFY(exporter.exportContacts(list, QVersitDocument::VCard21Type));
    QList<QVersitDocument> documents = exporter.documents();
    
    //X-SELF property is exported if MyCard
    QVersitDocument document  = documents.first();
    QVersitProperty property;
    property.setName(QLatin1String("X-SELF"));
    property.setValue("0");
    bool propertyFound = document.properties().contains(property);
    QVERIFY(propertyFound);
}
void SeasideCache::setFirstName(FilterType filterType, int index, const QString &firstName)
{
#ifdef USING_QTPIM
    CacheItem &cacheItem = m_cache[m_cacheIndices[m_contacts[filterType].at(index)]];
#else
    CacheItem &cacheItem = m_cache[m_contacts[filterType].at(index) - 1];
#endif

    QContactName name = cacheItem.contact.detail<QContactName>();
    name.setFirstName(firstName);
    cacheItem.contact.saveDetail(&name);

    QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName();
    cacheItem.nameGroup = determineNameGroup(&cacheItem);
    cacheItem.displayLabel = fullName;

    ItemListener *listener(cacheItem.listeners);
    while (listener) {
        listener->itemUpdated(&cacheItem);
        listener = listener->next;
    }

    if (m_models[filterType])
        m_models[filterType]->sourceDataChanged(index, index);
}
Ejemplo n.º 5
0
void tst_QVersitContactPlugins::testExporterPlugins() {
    QVersitContactExporter exporter("Test");
    QContact contact;
    QContactName name;
    name.setFirstName("first name");
    contact.saveDetail(&name);
    QVERIFY(exporter.exportContacts(QList<QContact>() << contact));
    QCOMPARE(exporter.documents().size(), 1);
    QList<QVersitProperty> properties(exporter.documents().first().properties());

    // The plugins have had their index set such that they should be executed in reverse order
    // Check that they are all loaded, and run in the correct order
    int n = 0;
    foreach (QVersitProperty property, properties) {
        if (property.name() == "TEST-PROPERTY") {
            switch (n) {
                case 0: QCOMPARE(property.value(), QLatin1String("5")); break;
                case 1: QCOMPARE(property.value(), QLatin1String("4")); break;
                case 2: QCOMPARE(property.value(), QLatin1String("3")); break;
                case 3: QCOMPARE(property.value(), QLatin1String("2")); break;
                case 4: QCOMPARE(property.value(), QLatin1String("1")); break;
            }
            n++;
        }
    }
    QCOMPARE(n, 5);
}
Ejemplo n.º 6
0
void SeasidePerson::setFirstName(const QString &name)
{
    QContactName nameDetail = mContact.detail<QContactName>();
    nameDetail.setFirstName(name);
    mContact.saveDetail(&nameDetail);
    emit firstNameChanged();
    recalculateDisplayLabel();
}
Ejemplo n.º 7
0
void TestBirthdayPlugin::testLeapYears()
{
    const QString contactID = QUuid::createUuid().toString();
    QFETCH(QDate, contactBirthDate);

    // Add contact with birthday to tracker.
    QContactName contactName;
    contactName.setFirstName(contactID);
    QContactBirthday contactBirthday;
    contactBirthday.setDate(contactBirthDate);
    QContact contact;
    QVERIFY(contact.saveDetail(&contactName));
    QVERIFY(contact.saveDetail(&contactBirthday));
    QVERIFY(saveContact(contact));

    // Wait until calendar event gets to calendar.
    loopWait(calendarTimeout);

    // Open calendar database.
    mKCal::ExtendedCalendar::Ptr calendar =
        mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone()));
    mKCal::ExtendedStorage::Ptr storage =
        mKCal::ExtendedCalendar::defaultStorage(calendar);

    QVERIFY(storage->open());
    QVERIFY(not storage->notebook(calNotebookId).isNull());

    // Check calendar database for contact.
    QVERIFY(storage->loadNotebookIncidences(calNotebookId));
    const KCalCore::Event::List eventList = findCalendarEvents(calendar->events(), contact);
    QCOMPARE(eventList.count(), 1);

    const KCalCore::Event::Ptr event = eventList.first();
    QCOMPARE(event->summary(), contactID);
    QCOMPARE(event->dtStart().date(), contactBirthDate);
    QCOMPARE(event->allDay(), true);

    // Check number of recurrences and their values.
    const KDateTime first(QDate(2000, 1, 1), QTime(), KDateTime::ClockTime);
    const KDateTime last(QDate(2020, 12, 31), QTime(), KDateTime::ClockTime);
    const KCalCore::DateTimeList instances = event->recurrence()->timesInInterval(first, last);

    QCOMPARE(instances.length(), 13);

    for(int i = 0; i < instances.length(); ++i) {
        QCOMPARE(instances.at(i).date(), contactBirthDate.addYears(i));
    }
}
/*!
 * The leaving function that queries the SQL database
 * 
 * \a aSqlQuery An SQL query
 * \return the list of matched contact ids
 */
QList<QContact> CntSymbianSrvConnection::searchContactNamesL(const TDesC& aSqlQuery)
{
    readContactsToBufferL(aSqlQuery, CntSymbianSrvConnection::CntSearchResultList);

    RBufReadStream readStream;
    QList<QContact> contacts;
    TInt id;
    TBuf<256> firstName;
    TBuf<256> lastName;
    TBuf<256> company;

    readStream.Open(*m_buffer);
    while ((id = readStream.ReadInt32L()) != 0) {
        readStream >> firstName;
        readStream >> lastName;
        readStream >> company;

        QContact contact, tempContact;

        QContactName name;
        name.setFirstName(QString::fromUtf16(firstName.Ptr(), firstName.Length()));
        name.setLastName(QString::fromUtf16(lastName.Ptr(), lastName.Length()));
        tempContact.saveDetail(&name);

        QContactOrganization organization;
        organization.setName(QString::fromUtf16(company.Ptr(), company.Length()));
        tempContact.saveDetail(&organization);

        QContactManager::Error error(QContactManager::NoError);
        QString label = m_manager->synthesizedDisplayLabel(tempContact, &error);
        if (error != QContactManager::NoError) {
            continue;
        }
        tempContact.clearDetails();

        m_manager->setContactDisplayLabel(&contact, label);

        QContactId contactId;
        contactId.setLocalId(id);
        contactId.setManagerUri(m_manager->managerUri());
        contact.setId(contactId);

        contacts << contact;
    }

    return contacts;
}
Ejemplo n.º 9
0
void TestBirthdayPlugin::testAddAndRemoveBirthday()
{
    const QString contactID = QUuid::createUuid().toString();
    const QDateTime contactBirthDate = QDateTime::currentDateTime();

    // Add contact with birthday to tracker.
    QContactName contactName;
    contactName.setFirstName(contactID);
    QContactBirthday contactBirthday;
    contactBirthday.setDateTime(contactBirthDate);
    QContact contact;
    QVERIFY(contact.saveDetail(&contactName));
    QVERIFY(contact.saveDetail(&contactBirthday));
    QVERIFY2(mManager->saveContact(&contact), "Error saving contact to tracker");

    // Wait until calendar event gets to calendar.
    loopWait(calendarTimeout);

    // Open calendar database, which should have been created by the birthday plugin.
    mKCal::ExtendedCalendar::Ptr calendar =
        mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone()));
    mKCal::ExtendedStorage::Ptr storage =
        mKCal::ExtendedCalendar::defaultStorage(calendar);
    storage->open();
    QVERIFY2(not storage->notebook(calNotebookId).isNull(), "No calendar database found");

    // Check calendar database for contact.
    QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook");
    KCalCore::Event::List eventList = calendar->events();
    QCOMPARE(countCalendarEvents(eventList, contact), 1);

    // Delete the contact and see if the birthday is also deleted.
    QVERIFY2(mManager->removeContact(apiId(contact)), "Unable to delete test contact from tracker database");

    // Wait until calendar event gets to calendar.
    loopWait(calendarTimeout);

    // Search for any events in the calendar.
    QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook");
    eventList = calendar->events();
    QCOMPARE(countCalendarEvents(eventList, contact), 0);

    // Close the calendar.
    QVERIFY2(storage->close(), "Error closing the calendar");
}
Ejemplo n.º 10
0
void exportExample()
{
    //! [Export example]
    QVersitContactExporter contactExporter;

    QContact contact;
    // Create a name
    QContactName name;
    name.setFirstName(QString::fromAscii("John"));
    contact.saveDetail(&name);

    if (!contactExporter.exportContacts(QList<QContact>() << contact, QVersitDocument::VCard30Type))
        return;
    QList<QVersitDocument> versitDocuments = contactExporter.documents();

    // detailHandler.mUnknownDetails now contains the list of unknown details

    //! [Export example]
}
Ejemplo n.º 11
0
void MainWindow::updateContact()
{
    const QString& name = m_nameEdit->text();
    const QString& phone = m_phoneEdit->text();
    const QString& email = m_emailEdit->text();

    if (!name.isEmpty()) {
        QContactName detail = m_contact.detail<QContactName>();
        detail.setFirstName(name);
        m_contact.saveDetail(&detail);
    }

    if (!phone.isEmpty()) {
        QContactPhoneNumber detail = m_contact.detail<QContactPhoneNumber>();
        detail.setNumber(phone);
        m_contact.saveDetail(&detail);
    }

    if (!email.isEmpty()) {
        QContactEmailAddress detail = m_contact.detail<QContactEmailAddress>();
        detail.setEmailAddress(email);
        m_contact.saveDetail(&detail);
    }
}
Ejemplo n.º 12
0
QContactDetail *CntTransformName::transformItemField(const CContactItemField& field, const QContact &contact)
{
    QContactName *name = new QContactName(contact.detail<QContactName>());

    CContactTextField* storage = field.TextStorage();
    QString nameValue = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length());

    for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
        //Prefix
        if (field.ContentType().FieldType(i) == KUidContactFieldPrefixName) {
            name->setPrefix(nameValue);
        }
        //First name
        else if (field.ContentType().FieldType(i) == KUidContactFieldGivenName) {
            name->setFirstName(nameValue);
        }
        //Middle name
        else if (field.ContentType().FieldType(i) == KUidContactFieldAdditionalName) {
            name->setMiddleName(nameValue);
        }
        //Last name
        else if (field.ContentType().FieldType(i) == KUidContactFieldFamilyName) {
            name->setLastName(nameValue);
        }
        //Suffix
        else if (field.ContentType().FieldType(i) == KUidContactFieldSuffixName) {
            name->setSuffix(nameValue);
        }
        // custom label
        else if (field.ContentType().FieldType(i) == KUidContactFieldTemplateLabel) {
            name->setCustomLabel(nameValue);
        }
    }

    return name;
}
Ejemplo n.º 13
0
QContact generateContact(const QString &syncTarget = QString(QLatin1String("local")), bool possiblyAggregate = false)
{
    static const QStringList firstNames(generateFirstNamesList());
    static const QStringList middleNames(generateMiddleNamesList());
    static const QStringList lastNames(generateLastNamesList());
    static const QStringList nonOverlappingFirstNames(generateNonOverlappingFirstNamesList());
    static const QStringList nonOverlappingLastNames(generateNonOverlappingLastNamesList());
    static const QStringList phoneNumbers(generatePhoneNumbersList());
    static const QStringList emailProviders(generateEmailProvidersList());
    static const QStringList avatars(generateAvatarsList());
    static const QStringList hobbies(generateHobbiesList());

    // we randomly determine whether to generate various details
    // to ensure that we have heterogeneous contacts in the db.
    QContact retn;
    int random = qrand();
    bool preventAggregate = (syncTarget != QLatin1String("local") && !possiblyAggregate);

    // We always have a sync target.
    QContactSyncTarget synctarget;
    synctarget.setSyncTarget(syncTarget);
    retn.saveDetail(&synctarget);

    // We always have a name.  Select an overlapping name if the sync target
    // is something other than "local" and possiblyAggregate is true.
    QContactName name;
    name.setFirstName(preventAggregate ?
            nonOverlappingFirstNames.at(random % nonOverlappingFirstNames.size()) :
            firstNames.at(random % firstNames.size()));
    name.setLastName(preventAggregate ?
            nonOverlappingLastNames.at(random % nonOverlappingLastNames.size()) :
            lastNames.at(random % lastNames.size()));
    if ((random % 6) == 0) name.setMiddleName(middleNames.at(random % middleNames.size()));
    if ((random % 17) == 0) name.setPrefix(QLatin1String("Dr."));
    retn.saveDetail(&name);

    // Favorite
    if ((random % 31) == 0) {
        QContactFavorite fav;
        fav.setFavorite(true);
        retn.saveDetail(&fav);
    }

    // Phone number
    if ((random % 3) == 0) {
        QContactPhoneNumber phn;
        QString randomPhn = phoneNumbers.at(random % phoneNumbers.size());
        phn.setNumber(preventAggregate ? QString(QString::number(random % 500000) + randomPhn) : randomPhn);
        if ((random % 9) == 0) phn.setContexts(QContactDetail::ContextWork);
        retn.saveDetail(&phn);
    }

    // Email
    if ((random % 2) == 0) {
        QContactEmailAddress em;
        em.setEmailAddress(QString(QLatin1String("%1%2%3%4"))
                .arg(preventAggregate ? QString(QString::number(random % 500000) + syncTarget) : QString())
                .arg(name.firstName()).arg(name.lastName())
                .arg(emailProviders.at(random % emailProviders.size())));
        if (random % 9) em.setContexts(QContactDetail::ContextWork);
        retn.saveDetail(&em);
    }

    // Avatar
    if ((random % 5) == 0) {
        QContactAvatar av;
        av.setImageUrl(name.firstName() + avatars.at(random % avatars.size()));
        retn.saveDetail(&av);
    }

    // Hobby
    if ((random % 21) == 0) {
        QContactHobby h1;
        h1.setHobby(hobbies.at(random % hobbies.size()));
        retn.saveDetail(&h1);

        int newRandom = qrand();
        if ((newRandom % 2) == 0) {
            QContactHobby h2;
            h2.setHobby(hobbies.at(newRandom % hobbies.size()));
            retn.saveDetail(&h2);
        }
    }

    return retn;
}
void SeasideCache::reset()
{
    for (int i = 0; i < FilterTypesCount; ++i) {
        m_contacts[i].clear();
        m_populated[i] = false;
        m_models[i] = 0;
    }

    m_cache.clear();
    m_cacheIndices.clear();

    for (uint i = 0; i < sizeof(contactsData) / sizeof(Contact); ++i) {
        QContact contact;

        // This is specific to the qtcontacts-sqlite backend:
        const QString idStr(QString::fromLatin1("qtcontacts:org.nemomobile.contacts.sqlite::sql-%1"));
        contact.setId(QContactId::fromString(idStr.arg(i + 1)));

        QContactName name;
        name.setFirstName(QString::fromLatin1(contactsData[i].firstName));
        name.setMiddleName(QString::fromUtf8(contactsData[i].middleName));
        name.setLastName(QString::fromLatin1(contactsData[i].lastName));
        contact.saveDetail(&name);

        if (contactsData[i].avatar) {
            QContactAvatar avatar;
            avatar.setImageUrl(QUrl(QLatin1String(contactsData[i].avatar)));
            contact.saveDetail(&avatar);
        }

        QContactStatusFlags statusFlags;

        if (contactsData[i].email) {
            QContactEmailAddress email;
            email.setEmailAddress(QLatin1String(contactsData[i].email));
            contact.saveDetail(&email);
            statusFlags.setFlag(QContactStatusFlags::HasEmailAddress, true);
        }

        if (contactsData[i].phoneNumber) {
            QContactPhoneNumber phoneNumber;
            phoneNumber.setNumber(QLatin1String(contactsData[i].phoneNumber));
            contact.saveDetail(&phoneNumber);
            statusFlags.setFlag(QContactStatusFlags::HasPhoneNumber, true);
        }

        contact.saveDetail(&statusFlags);

        m_cacheIndices.insert(internalId(contact), m_cache.count());
        m_cache.append(CacheItem(contact));

        QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName();

        CacheItem &cacheItem = m_cache.last();
        cacheItem.nameGroup = determineNameGroup(&cacheItem);
        cacheItem.displayLabel = fullName;
    }

    insert(FilterAll, 0, getContactsForFilterType(FilterAll));
    insert(FilterFavorites, 0, getContactsForFilterType(FilterFavorites));
    insert(FilterOnline, 0, getContactsForFilterType(FilterOnline));
}
void AsyncRequestExample::performRequests()
{
//! [Creating a new contact in a manager]
    QContact exampleContact;

    QContactName nameDetail;
    nameDetail.setFirstName("Adam");
    nameDetail.setLastName("Unlikely");

    QContactPhoneNumber phoneNumberDetail;
    phoneNumberDetail.setNumber("+123 4567");

    exampleContact.saveDetail(&nameDetail);
    exampleContact.saveDetail(&phoneNumberDetail);

    // save the newly created contact in the manager
    connect(&m_contactSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactSaveRequestStateChanged(QContactAbstractRequest::State)));
    m_contactSaveRequest.setManager(m_manager);
    m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
    m_contactSaveRequest.start();
//! [Creating a new contact in a manager]

    m_contactSaveRequest.waitForFinished();

//! [Creating a new contact in a manager waiting until finished]
    m_contactSaveRequest.setManager(m_manager);
    m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
    m_contactSaveRequest.start();
    m_contactSaveRequest.waitForFinished();
    QList<QContact> savedContacts = m_contactSaveRequest.contacts();
//! [Creating a new contact in a manager waiting until finished]

//! [Filtering contacts from a manager]
    connect(&m_contactFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactFetchRequestStateChanged(QContactAbstractRequest::State)));
    m_contactFetchRequest.setManager(m_manager);
    m_contactFetchRequest.setFilter(QContactPhoneNumber::match("+123 4567"));
    m_contactFetchRequest.start();
//! [Filtering contacts from a manager]

    m_contactFetchRequest.waitForFinished();

//! [Retrieving an existing contact from a manager]
    QContactLocalIdFilter idListFilter;
    idListFilter.setIds(QList<QContactLocalId>() << exampleContact.localId());
    m_contactFetchRequest.setManager(m_manager);
    m_contactFetchRequest.setFilter(idListFilter);
    m_contactFetchRequest.start();
//! [Retrieving an existing contact from a manager]

    m_contactFetchRequest.waitForFinished();

//! [Updating an existing contact in a manager]
    phoneNumberDetail.setNumber("+123 9876");
    exampleContact.saveDetail(&phoneNumberDetail);
    m_contactSaveRequest.setManager(m_manager);
    m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
    m_contactSaveRequest.start();
//! [Updating an existing contact in a manager]

    m_contactFetchRequest.waitForFinished();

//! [Removing a contact from a manager]
    connect(&m_contactRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactRemoveRequestStateChanged(QContactAbstractRequest::State)));
    m_contactRemoveRequest.setManager(m_manager);
    m_contactRemoveRequest.setContactIds(QList<QContactLocalId>() << exampleContact.localId());
    m_contactRemoveRequest.start();
//! [Removing a contact from a manager]

    m_contactFetchRequest.waitForFinished();

//! [Creating a new relationship between two contacts]
    // first, create the group and the group member
    QContact exampleGroup;
    exampleGroup.setType(QContactType::TypeGroup);
    QContactNickname groupName;
    groupName.setNickname("Example Group");
    exampleGroup.saveDetail(&groupName);
    
    QContact exampleGroupMember;
    QContactName groupMemberName;
    groupMemberName.setFirstName("Member");
    exampleGroupMember.saveDetail(&groupMemberName);

    // second, save those contacts in the manager
    QList<QContact> saveList;
    saveList << exampleGroup << exampleGroupMember;
    m_contactSaveRequest.setContacts(saveList);
    m_contactSaveRequest.start();
    m_contactSaveRequest.waitForFinished();

    // third, create the relationship between those contacts
    QContactRelationship groupRelationship;
    groupRelationship.setFirst(exampleGroup.id());
    groupRelationship.setRelationshipType(QContactRelationship::HasMember);
    groupRelationship.setSecond(exampleGroupMember.id());

    // finally, save the relationship in the manager
    connect(&m_relationshipSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipSaveRequestStateChanged(QContactAbstractRequest::State)));
    m_relationshipSaveRequest.setManager(m_manager);
    m_relationshipSaveRequest.setRelationships(QList<QContactRelationship>() << groupRelationship);
    m_relationshipSaveRequest.start();
//! [Creating a new relationship between two contacts]

    m_contactFetchRequest.waitForFinished();

//! [Retrieving relationships between contacts]
    connect(&m_relationshipFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipFetchRequestStateChanged(QContactAbstractRequest::State)));
    m_relationshipFetchRequest.setManager(m_manager);
    // retrieve the list of relationships between the example group contact and the example member contact
    // where the group contact is the first contact in the relationship, and the member contact is the
    // second contact in the relationship.  In order to fetch all relationships between them, another
    // relationship fetch must be performed with their roles reversed, and the results added together.
    m_relationshipFetchRequest.setFirst(exampleGroup.id());
    m_relationshipFetchRequest.setSecond(exampleGroupMember.id());
    m_relationshipFetchRequest.start();
//! [Retrieving relationships between contacts]

    m_contactFetchRequest.waitForFinished();

//! [Providing a fetch hint]
    QContactFetchHint hasMemberRelationshipsOnly;
    hasMemberRelationshipsOnly.setRelationshipTypesHint(QStringList(QContactRelationship::HasMember));

    m_contactFetchRequest.setManager(m_manager);
    m_contactFetchRequest.setFilter(QContactFilter()); // all contacts
    m_contactFetchRequest.setFetchHint(hasMemberRelationshipsOnly);
    m_contactFetchRequest.start();
//! [Providing a fetch hint]

//! [Removing a relationship]
    connect(&m_relationshipRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipRemoveRequestStateChanged(QContactAbstractRequest::State)));
    m_relationshipRemoveRequest.setManager(m_manager);
    m_relationshipRemoveRequest.setRelationships(QList<QContactRelationship>() << groupRelationship);
    m_relationshipRemoveRequest.start();
//! [Removing a relationship]

    connect(&m_definitionFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(definitionFetchRequestStateChanged(QContactAbstractRequest::State)));
//! [Querying the schema supported by a manager]
    m_definitionFetchRequest.setManager(m_manager);
    m_definitionFetchRequest.setDefinitionNames(QStringList(QContactName::DefinitionName));
    m_definitionFetchRequest.start();
    m_definitionFetchRequest.waitForFinished();
    QMap<QString, QContactDetailDefinition> definitions = m_definitionFetchRequest.definitions();
    qDebug() << "This manager"
             << (definitions.value(QContactName::DefinitionName).fields().contains(QContactName::FieldCustomLabel) ? "supports" : "does not support")
             << "the custom label field of QContactName";
//! [Querying the schema supported by a manager]

    connect(&m_definitionSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(definitionSaveRequestStateChanged(QContactAbstractRequest::State)));
    connect(&m_definitionRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(definitionRemoveRequestStateChanged(QContactAbstractRequest::State)));
//! [Modifying the schema supported by a manager]
    // modify the name definition, adding a patronym field
    QContactDetailDefinition nameDefinition = definitions.value(QContactName::DefinitionName);
    QContactDetailFieldDefinition fieldPatronym;
    fieldPatronym.setDataType(QVariant::String);
    nameDefinition.insertField("Patronym", fieldPatronym);

    // save the updated definition in the manager if supported...
    if (m_manager->hasFeature(QContactManager::MutableDefinitions)) {
        m_definitionSaveRequest.setManager(m_manager);
        m_definitionSaveRequest.setContactType(QContactType::TypeContact);
        m_definitionSaveRequest.setDefinitions(QList<QContactDetailDefinition>() << nameDefinition);
        m_definitionSaveRequest.start();
    }
//! [Modifying the schema supported by a manager]

    QCoreApplication::exit(0);
}
/**
 * Method to get the result for a network request.
 * @param aOperation The type of operation to be requested
 * @param aTransportResult The result of transport operation
 * @param aResponse The QByteArray instance containing the network response.
 * The plugins should delete this instance once they have read the 
 * data from it.
 * @param aResult [out] An output parameter to the plugin manager.If the 
 * return value is SmfSendRequestAgain, QVariant will be of type 
 * SmfPluginRequestData.
 * For SmfGalleryPlugin: If last operation was pictures(), aResult will 
 * be of type QList<SmfPicture>. If last operation was description(), 
 * aResult will be of type QString. If last operation was upload() or 
 * postComment(), aResult will be of type bool.
 * @param aRetType [out] SmfPluginRetType
 * @param aPageResult [out] The SmfResultPage structure variable
 */
SmfPluginError FlickrContactFetcherPlugin::responseAvailable( 
		const SmfRequestTypeID aOperation,
		const SmfTransportResult &aTransportResult, 
		QByteArray *aResponse, 
		QVariant* aResult, 
		SmfPluginRetType &aRetType,
		SmfResultPage &aPageResult )
	{
	Q_UNUSED(aPageResult)
	qDebug()<<"Inside FlickrContactFetcherPlugin::responseAvailable()";
	
	SmfPluginError error = SmfPluginErrNetworkError;
	
	if( !aResponse || (0 == aResponse->size()) )
		{
		qDebug()<<"Response is NULL or empty";
		aRetType = SmfRequestError;
		return error;
		}
	
	QByteArray response(*aResponse);
	delete aResponse;
	
	QFile respFile("c://data//SmfPluginFlickrContactResponse.txt");
	if(!respFile.open(QIODevice::WriteOnly))
		{
		qDebug()<<"File to write the response could not be opened, so writing to this file";
		qDebug()<<"Flickr response = "<<QString(response);
		}
	else
		{
		respFile.write(response);
		respFile.close();
		qDebug()<<"Writing FB response to a file named 'SmfPluginFlickrContactResponse.txt'";
		}
	qDebug()<<"FB response size = "<<response.size();
	
	if(SmfTransportOpNoError == aTransportResult)
		{
		qDebug()<<"No transport error";
		
#ifndef TESTINGTHISFUNCTION	
		if(SmfContactGetFriends == aOperation)
#else
		if(SmfContactGetFriends == aOperation ||aOperation == SmfContactGetFollowers||aOperation== SmfContactSearch ||aOperation ==SmfContactSearchNear||aOperation ==SmfContactSearchInGroup)
#endif
			{
			qDebug()<<"For getting friends response";
			
			QList<SmfContact> list;
			
#ifdef SMF_XMLPARSING // Xml parsing
			// For getting contacts from xml response
			QXmlStreamReader xml(response);
			while (!xml.atEnd())
				{
				xml.readNext();
				if (xml.tokenType() == QXmlStreamReader::StartElement)
					{
					// If the tag is contact
					if (xml.name() == "contact")
						{
						qDebug()<<"Contact tag found";
						SmfContact contact;
						QStringRef str;
						QContactName contactname;
						QString username = xml.attributes().value("username").toString();
						qDebug()<<"Username = "******"Name",namevar1);
						list.append(contact);
						}
					}
				}
#else
			// To remove the "jsonFlickrApi(" and also remove the last ")" from the response,
			// as these gives a Json parsing error
			response.remove(0, 14);
			response.chop(1);
			
			// For getting contacts from json response
			bool ok;
			SmfPluginUtil util;
			QVariantMap result = util.parse(response, &ok).toMap();
			if (!ok) {
				qDebug()<<"An error occurred during json parsing";
				aResult->setValue(list);
				aRetType = SmfRequestError;
				return SmfPluginErrParsingFailed;
			}
			
			QVariantMap map1 = result["contacts"].toMap();
			qDebug()<<"page = "<<map1["page"].toString();
			qDebug()<<"pages = "<<map1["pages"].toString();
			qDebug()<<"per_page = "<<map1["per_page"].toString();
			qDebug()<<"perpage = "<<map1["perpage"].toString();
			qDebug()<<"total = "<<map1["perpage"].toString();
			
			QList<QVariant> list1 = map1["contact"].toList();
			
			QListIterator<QVariant> i(list1);
			while(i.hasNext())
				{
				SmfContact contact;
				QVariantMap map2 = i.next().toMap();
				qDebug()<<"nsid = "<<map2["nsid"].toString();
				qDebug()<<"username = "******"username"].toString();
				qDebug()<<"iconserver = "<<map2["iconserver"].toString();
				qDebug()<<"iconfarm = "<<map2["iconfarm"].toString();
				qDebug()<<"ignored = "<<map2["ignored"].toString();
				qDebug()<<"realname = "<<map2["realname"].toString();
				qDebug()<<"friend = "<<map2["friend"].toString();
				qDebug()<<"family = "<<map2["family"].toString();
				qDebug()<<"path_alias = "<<map2["path_alias"].toString();
				qDebug()<<"location = "<<map2["location"].toString();
				
				// Contact Name
				QContactName contactname;
				QString username = map2["username"].toString();
				qDebug()<<"Username = "******"Name",nameVar);
				
				// Contact's Flickr Specific ID to QContactGuid
				QContactGuid guid;
				guid.setGuid(map2["nsid"].toString());
				QVariant guidVar = QVariant::fromValue(guid);
				contact.setValue("Guid",guidVar);
					
				// Contact's profile image url
				QUrl url;
				if((0 == map2["iconfarm"].toInt()) && (0 == map2["iconserver"].toInt()))
					url = QString("http://www.flickr.com/images/buddyicon.jpg");
				else
					{
					QString str("http://farm");
					str.append(map2["iconfarm"].toString());
					str.append(".static.flickr.com/");
					str.append(map2["iconserver"].toString());
					str.append("/buddyicons/");
					str.append(map2["nsid"].toString());
					str.append(".jpg");
					url = str;
					}
				QContactAvatar avatar;
				qDebug()<<"Profile image URL = "<<url.toString();
				avatar.setImageUrl(url);
				QVariant avatarVar = QVariant::fromValue(avatar);
				contact.setValue("Avatar",avatarVar);
				
				
				list.append(contact);
				}
#endif
			
			qDebug()<<"list count = "<<list.count();
			aResult->setValue(list);
			aRetType = SmfRequestComplete;
			error = SmfPluginErrNone;
			}
		else if(aOperation==SmfContactGetGroups)
			{
		        response.remove(0, 14);
				response.chop(1);
			
			    bool ok;
				qDebug()<<"Before Parser--";

				SmfPluginUtil util;
				QVariant result = util.parse(response, &ok);
				if (!ok) 
				{
				    qDebug()<<"An error occurred during json parsing";
					aRetType = SmfRequestError;
					return SmfPluginErrParsingFailed;
								 //return 0;
				}
							
				QVariantMap map1 = result.toMap();
		        QList<SmfGroup> list;
				QVariantMap map2 = map1["groups"].toMap();
				int page = map2["page"].toInt(&ok);
				qDebug()<<"PAGE = "<<map2["page"].toString();
				QList<QVariant> list1 = map2["group"].toList();
				QListIterator<QVariant> iter(list1);
						
				//Getting the group list from QJson Parser 
				 while(iter.hasNext())
				 {
					QVariantMap map2 = iter.next().toMap();
					qDebug()<<"name = "<<map2["name"].toString();
					qDebug()<<"id = "<<map2["id"].toString();
					SmfGroup group;
					QString id(map2["id"].toString());
					group.setId(id);
					QString grpname(map2["name"].toString());
					group.setName(grpname);
						   
					list.append(group);
						   
				 }//end While
				 qDebug()<<"list count = "<<QString::number(list.count(),10);
				aResult->setValue(list);
			}
		else
			{
			qDebug()<<"Service unsupported, currently only SmfContactGetFriends !!!";
			aRetType = SmfRequestError;
			error = SmfPluginErrServiceNotSupported;
			}
		}

	else if(SmfTransportOpOperationCanceledError == aTransportResult)
		{
		qDebug()<<"Operation Cancelled !!!";
		error = SmfPluginErrCancelComplete;
		aRetType = SmfRequestComplete;
		}

	else
		{
		qDebug()<<"Transport Error !!!";
		error = SmfPluginErrNetworkError;
		aRetType = SmfRequestError;
		}
	
	return error;
	}
Ejemplo n.º 17
0
void SymbianPluginPerfomance::createComplexContacts()
{
    // Create N contacts
    QList<QContact> contactsList;
    for(int i=0; i<NO_OF_CONTACTS; i++) {
        QContact alice;

        // Contact details
        QString c = QString::number(i);
        QString first("Alice");
        QString last("Jones");

        QContactName aliceName;
        aliceName.setFirstName(first.append(c));
        aliceName.setLastName(last.append(c));
        alice.saveDetail(&aliceName);

        QContactPhoneNumber number;
        number.setContexts("Home");
        number.setSubTypes("Mobile");
        number.setNumber("12345678");
        alice.saveDetail(&number);
        alice.setPreferredDetail("DialAction", number);

        QContactPhoneNumber number2;
        number2.setContexts("Work");
        number2.setSubTypes("Landline");
        number2.setNumber("555-4444");
        alice.saveDetail(&number2);

        QContactAddress add;
        add.setStreet("Leeds West Yorkshire");
        add.setPostcode("10087");
        add.setRegion("New York");
        add.setCountry("United States");
        alice.saveDetail(&add);

        /* Commented out to ensure compatibility with pre-10.1 platforms
        QContactGender gender;
        gender.setGender("Female");
        alice.saveDetail(&gender);
        */

        QContactBirthday bday;
        bday.setDate(QDate(25,10,1978));
        alice.saveDetail(&bday);

        /* Commented out to ensure compatibility with pre-10.1 platforms
        QContactOnlineAccount acc;
        acc.setAccountUri("sips:[email protected]");
        acc.setSubTypes(QContactOnlineAccount::SubTypeSip);
        alice.saveDetail(&acc);
        */

        QContactEmailAddress email;
        email.setEmailAddress("mailto:[email protected]");
        alice.saveDetail(&email);

        QContactOrganization org;
        org.setDepartment(QStringList("Services"));
        org.setTitle("Assistant Manager");
        // Commented out to ensure compatibility with pre-10.1 platforms
        //org.setLocation("Nokia Cyber Park");
        alice.saveDetail(&org);

        contactsList.append(alice);
    }
    // Save the contacts
    mTime.restart();
    QMap<int, QContactManager::Error> errors;
    mCntMng->saveContacts(&contactsList, &errors);
    foreach(QContactManager::Error error, errors) {
        QCOMPARE(error, QContactManager::NoError);
    }
void TestCntPresenceInfoProvider::testRequestInfo()
{
    PrcPresenceWriter *writer = PrcPresenceWriter::createWriter();
    
    PrcPresenceBuddyInfoQt *buddy = PrcPresenceBuddyInfoQt::createInstance();
    buddy->setIdentity("sip:[email protected]");
    buddy->setAvailability(PrcPresenceBuddyInfoQt::PrcNotAvailable, "meh");
    writer->writePresence(*buddy);
    
    QContactManager manager("symbian");
    
    QContact c;
    QContactName name;
    name.setFirstName("firstname");
    name.setLastName("lastname");
    c.saveDetail(&name);
    QContactPhoneNumber number;
    number.setNumber("1234567");
    number.setContexts(QContactDetail::ContextHome);
    number.setSubTypes(QContactPhoneNumber::SubTypeMobile);
    c.saveDetail(&number);
    manager.saveContact(&c);
    
    ContactInfoFields fields;
    fields = ContactInfoTextField;
    
    QSignalSpy spy(mCntPresenceInfoProvider, SIGNAL(infoFieldReady(CntInfoProvider*, int, ContactInfoField, const QString&)));
    
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy.count(), 0);
    QVERIFY(mCntPresenceInfoProvider->mBuddyMap.isEmpty());
    
    fields = ContactInfoIcon2Field;
    
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy.count(), 0);
    QVERIFY(mCntPresenceInfoProvider->mBuddyMap.isEmpty());
    
    QContactOnlineAccount account;
    account.setSubTypes(QStringList() << QContactOnlineAccount::SubTypeSip);
    account.setServiceProvider("sip");
    account.setAccountUri("*****@*****.**");
    c.saveDetail(&account);
    QContactOnlineAccount account2;
    account2.setSubTypes(QStringList() << QContactOnlineAccount::SubTypeSipVoip);
    account.setServiceProvider("sip");
    account2.setAccountUri("*****@*****.**");
    c.saveDetail(&account2);
    QContactOnlineAccount account3;
    account3.setSubTypes(QStringList() << QContactOnlineAccount::SubTypeSip);
    account3.setAccountUri("malformatted");
    c.saveDetail(&account3);
    manager.saveContact(&c);
    
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy.count(), 0);
    QCOMPARE(mCntPresenceInfoProvider->mBuddyMap.count(), 1);
    
    delete mCntPresenceInfoProvider;
    mCntPresenceInfoProvider = NULL;
    
    buddy->setAvailability(PrcPresenceBuddyInfoQt::PrcAvailable, "meh");
    writer->writePresence(*buddy);
    
    mCntPresenceInfoProvider = new CntPresenceInfoProvider();
    
    QSignalSpy spy2(mCntPresenceInfoProvider, SIGNAL(infoFieldReady(CntInfoProvider*, int, ContactInfoField, const QString&)));
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy2.count(), 1);
    QCOMPARE(mCntPresenceInfoProvider->mBuddyMap.count(), 1);
    
    delete buddy;
    delete writer;
}