diff --git a/resources/google-new/calendarhandler.cpp b/resources/google-new/calendarhandler.cpp index d45e8e68e..baaed5509 100644 --- a/resources/google-new/calendarhandler.cpp +++ b/resources/google-new/calendarhandler.cpp @@ -1,369 +1,396 @@ /* Copyright (C) 2011-2013 Daniel Vrátil 2020 Igor Poboiko 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 . */ #include "calendarhandler.h" #include "defaultreminderattribute.h" #include "googleresource.h" #include "googlesettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "googlecalendar_debug.h" using namespace KGAPI2; using namespace Akonadi; static constexpr uint32_t KGAPIEventVersion = 1; QString CalendarHandler::mimetype() { return KCalendarCore::Event::eventMimeType(); } bool CalendarHandler::canPerformTask(const Akonadi::Item &item) { return m_resource->canPerformTask(item, mimetype()); } void CalendarHandler::retrieveCollections() { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Retrieving calendars")); qCDebug(GOOGLE_CALENDAR_LOG) << "Retrieving calendars..."; auto job = new CalendarFetchJob(m_settings->accountPtr(), this); connect(job, &KGAPI2::Job::finished, this, &CalendarHandler::slotCollectionsRetrieved); } void CalendarHandler::slotCollectionsRetrieved(KGAPI2::Job* job) { if (!m_resource->handleError(job)) { return; } qCDebug(GOOGLE_CALENDAR_LOG) << "Calendars retrieved"; const ObjectsList calendars = qobject_cast(job)->items(); Collection::List collections; const QStringList activeCalendars = m_settings->calendars(); for (const auto &object : calendars) { const CalendarPtr &calendar = object.dynamicCast(); qCDebug(GOOGLE_CALENDAR_LOG) << "Retrieved calendar:" << calendar->title() << "(" << calendar->uid() << ")"; - if (!activeCalendars.contains(calendar->uid())) { qCDebug(GOOGLE_CALENDAR_LOG) << "Skipping, not subscribed"; continue; } - Collection collection; collection.setContentMimeTypes({ mimetype() }); collection.setName(calendar->uid()); collection.setParentCollection(m_resource->rootCollection()); collection.setRemoteId(calendar->uid()); if (calendar->editable()) { collection.setRights(Collection::CanChangeCollection |Collection::CanDeleteCollection |Collection::CanCreateItem |Collection::CanChangeItem |Collection::CanDeleteItem); } else { collection.setRights(Collection::ReadOnly); } - - EntityDisplayAttribute *attr = collection.attribute(Collection::AddIfMissing); + // Setting icon + auto attr = collection.attribute(Collection::AddIfMissing); attr->setDisplayName(calendar->title()); attr->setIconName(QStringLiteral("view-calendar")); - + // Setting color auto colorAttr = collection.attribute(Collection::AddIfMissing); colorAttr->setColor(calendar->backgroundColor()); - - DefaultReminderAttribute *reminderAttr = collection.attribute(Collection::AddIfMissing); + // Setting default remoinders + auto reminderAttr = collection.attribute(Collection::AddIfMissing); reminderAttr->setReminders(calendar->defaultReminders()); - // Block email reminders, since Google sends them for us - BlockAlarmsAttribute *blockAlarms = collection.attribute(Collection::AddIfMissing); + auto blockAlarms = collection.attribute(Collection::AddIfMissing); blockAlarms->blockAlarmType(KCalendarCore::Alarm::Audio, false); blockAlarms->blockAlarmType(KCalendarCore::Alarm::Display, false); blockAlarms->blockAlarmType(KCalendarCore::Alarm::Procedure, false); collections << collection; } Q_EMIT collectionsRetrieved(collections); } void CalendarHandler::retrieveItems(const Collection &collection) { qCDebug(GOOGLE_CALENDAR_LOG) << "Retrieving events for calendar" << collection.remoteId(); QString syncToken = collection.remoteRevision(); auto job = new EventFetchJob(collection.remoteId(), m_settings->accountPtr(), this); if (!syncToken.isEmpty()) { qCDebug(GOOGLE_CALENDAR_LOG) << "Using sync token" << syncToken; job->setSyncToken(syncToken); } else if (!m_settings->eventsSince().isEmpty()) { const QDate date = QDate::fromString(m_settings->eventsSince(), Qt::ISODate); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) job->setTimeMin(QDateTime(date).toSecsSinceEpoch()); #else job->setTimeMin(QDateTime(date.startOfDay()).toSecsSinceEpoch()); #endif } job->setProperty(COLLECTION_PROPERTY, QVariant::fromValue(collection)); connect(job, &KGAPI2::Job::finished, this, &CalendarHandler::slotItemsRetrieved); Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Retrieving events for calendar '%1'", collection.displayName())); } void CalendarHandler::slotItemsRetrieved(KGAPI2::Job *job) { if (!m_resource->handleError(job)) { return; } Item::List changedItems, removedItems; Collection collection = job->property(COLLECTION_PROPERTY).value(); DefaultReminderAttribute *attr = collection.attribute(); auto fetchJob = qobject_cast(job); const ObjectsList objects = fetchJob->items(); bool isIncremental = !fetchJob->syncToken().isEmpty(); qCDebug(GOOGLE_CALENDAR_LOG) << "Retrieved" << objects.count() << "events for calendar" << collection.remoteId(); for (const ObjectPtr &object : objects) { const EventPtr event = object.dynamicCast(); if (event->useDefaultReminders() && attr) { const KCalendarCore::Alarm::List alarms = attr->alarms(event.data()); for (const KCalendarCore::Alarm::Ptr &alarm : alarms) { event->addAlarm(alarm); } } Item item; item.setMimeType(KCalendarCore::Event::eventMimeType()); item.setParentCollection(collection); item.setRemoteId(event->id()); item.setRemoteRevision(event->etag()); item.setPayload(event.dynamicCast()); if (event->deleted()) { qCDebug(GOOGLE_CALENDAR_LOG) << " - removed" << event->uid(); removedItems << item; } else { qCDebug(GOOGLE_CALENDAR_LOG) << " - changed" << event->uid(); changedItems << item; } } if (!isIncremental) { m_resource->itemsRetrieved(changedItems); } else { m_resource->itemsRetrievedIncremental(changedItems, removedItems); } qCDebug(GOOGLE_CALENDAR_LOG) << "Next sync token:" << fetchJob->syncToken(); collection.setRemoteRevision(fetchJob->syncToken()); new CollectionModifyJob(collection, this); emitReadyStatus(); } void CalendarHandler::itemAdded(const Item &item, const Collection &collection) { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Adding event to calendar '%1'", collection.name())); qCDebug(GOOGLE_CALENDAR_LOG) << "Event added to calendar" << collection.remoteId(); KCalendarCore::Event::Ptr event = item.payload(); EventPtr kevent(new Event(*event)); auto *job = new EventCreateJob(kevent, collection.remoteId(), m_settings->accountPtr(), this); job->setSendUpdates(SendUpdatesPolicy::None); connect(job, &KGAPI2::Job::finished, this, [this, item](KGAPI2::Job *job){ if (!m_resource->handleError(job)) { return; } Item newItem = item; const EventPtr event = qobject_cast(job)->items().first().dynamicCast(); qCDebug(GOOGLE_CALENDAR_LOG) << "Event added"; newItem.setRemoteId(event->id()); newItem.setRemoteRevision(event->etag()); newItem.setGid(event->uid()); m_resource->changeCommitted(newItem); newItem.setPayload(event.dynamicCast()); new ItemModifyJob(newItem, this); emitReadyStatus(); }); } void CalendarHandler::itemChanged(const Item &item, const QSet< QByteArray > &partIdentifiers) { Q_UNUSED(partIdentifiers); Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Changing event in calendar '%1'", item.parentCollection().displayName())); qCDebug(GOOGLE_CALENDAR_LOG) << "Changing event" << item.remoteId(); KCalendarCore::Event::Ptr event = item.payload(); EventPtr kevent(new Event(*event)); auto job = new EventModifyJob(kevent, item.parentCollection().remoteId(), m_settings->accountPtr(), this); job->setSendUpdates(SendUpdatesPolicy::None); job->setProperty(ITEM_PROPERTY, QVariant::fromValue(item)); connect(job, &EventModifyJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void CalendarHandler::itemsRemoved(const Item::List &items) { Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Removing %1 events", "Removing %1 event", items.count())); QStringList eventIds; eventIds.reserve(items.count()); std::transform(items.cbegin(), items.cend(), std::back_inserter(eventIds), [](const Item &item){ return item.remoteId(); }); qCDebug(GOOGLE_CALENDAR_LOG) << "Removing events:" << eventIds; // TODO: what if events are from diferent calendars? auto job = new EventDeleteJob(eventIds, items.first().parentCollection().remoteId(), m_settings->accountPtr(), this); job->setProperty(ITEMS_PROPERTY, QVariant::fromValue(items)); connect(job, &EventDeleteJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void CalendarHandler::itemsMoved(const Item::List &items, const Collection &collectionSource, const Collection &collectionDestination) { - Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Moving %1 events from calendar '%2' to calendar '%3'", - "Moving %1 event from calendar '%2' to calendar '%3'", + Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Moving %1 events from calendar '%2' to calendar '%3'", + "Moving %1 event from calendar '%2' to calendar '%3'", items.count(), collectionSource.displayName(), collectionDestination.displayName())); QStringList eventIds; eventIds.reserve(items.count()); std::transform(items.cbegin(), items.cend(), std::back_inserter(eventIds), [](const Item &item){ return item.remoteId(); }); qCDebug(GOOGLE_CALENDAR_LOG) << "Moving events" << eventIds << "from" << collectionSource.remoteId() << "to" << collectionDestination.remoteId(); auto job = new EventMoveJob(eventIds, collectionSource.remoteId(), collectionDestination.remoteId(), m_settings->accountPtr(), this); job->setProperty(ITEMS_PROPERTY, QVariant::fromValue(items)); connect(job, &EventMoveJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void CalendarHandler::collectionAdded(const Akonadi::Collection &collection, const Akonadi::Collection &parent) { Q_UNUSED(parent); Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Creating calendar '%1'", collection.displayName())); qCDebug(GOOGLE_CALENDAR_LOG) << "Adding calendar" << collection.displayName(); CalendarPtr calendar(new Calendar()); calendar->setTitle(collection.displayName()); calendar->setEditable(true); auto job = new CalendarCreateJob(calendar, m_settings->accountPtr(), this); job->setProperty(COLLECTION_PROPERTY, QVariant::fromValue(collection)); - connect(job, &KGAPI2::Job::finished, m_resource, &GoogleResource::slotGenericJobFinished); + + connect(job, &KGAPI2::Job::finished, this, [this, collection](KGAPI2::Job *job){ + if (!m_resource->handleError(job)) { + return; + } + const CalendarPtr calendar = qobject_cast(job)->items().first().dynamicCast(); + // Enable newly added calendar in settings + m_settings->addCalendar(calendar->uid()); + Collection newCollection = collection; + newCollection.setName(calendar->uid()); + newCollection.setRemoteId(calendar->uid()); + newCollection.setRights(Collection::CanChangeCollection + |Collection::CanDeleteCollection + |Collection::CanCreateItem + |Collection::CanChangeItem + |Collection::CanDeleteItem); + // TODO: for some reason, KOrganizer creates virtual collections (???) + //newCollection.setVirtual(false); + // Setting icon + auto attr = newCollection.attribute(Collection::AddIfMissing); + attr->setDisplayName(calendar->title()); + attr->setIconName(QStringLiteral("view-calendar")); + // TODO: google does not return color on create, so probably we should ask for it (when LibKGAPI will add support for it) + // Block email reminders, since Google sends them for us + auto blockAlarms = newCollection.attribute(Collection::AddIfMissing); + blockAlarms->blockAlarmType(KCalendarCore::Alarm::Audio, false); + blockAlarms->blockAlarmType(KCalendarCore::Alarm::Display, false); + blockAlarms->blockAlarmType(KCalendarCore::Alarm::Procedure, false); + m_resource->changeCommitted(newCollection); + emitReadyStatus(); + }); } void CalendarHandler::collectionChanged(const Akonadi::Collection &collection) { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Changing calendar '%1'", collection.displayName())); qCDebug(GOOGLE_CALENDAR_LOG) << "Changing calendar" << collection.remoteId(); CalendarPtr calendar(new Calendar()); calendar->setUid(collection.remoteId()); calendar->setTitle(collection.displayName()); calendar->setEditable(true); auto job = new CalendarModifyJob(calendar, m_settings->accountPtr(), this); job->setProperty(COLLECTION_PROPERTY, QVariant::fromValue(collection)); connect(job, &KGAPI2::Job::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void CalendarHandler::collectionRemoved(const Akonadi::Collection &collection) { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Removing calendar '%1'", collection.displayName())); qCDebug(GOOGLE_CALENDAR_LOG) << "Removing calendar" << collection.remoteId(); auto job = new CalendarDeleteJob(collection.remoteId(), m_settings->accountPtr(), this); job->setProperty(COLLECTION_PROPERTY, QVariant::fromValue(collection)); connect(job, &KGAPI2::Job::finished, m_resource, &GoogleResource::slotGenericJobFinished); } QDateTime CalendarHandler::lastCacheUpdate() const { return QDateTime(); } void CalendarHandler::canHandleFreeBusy(const QString &email) const { if (m_resource->canPerformTask()) { m_resource->handlesFreeBusy(email, false); return; } auto job = new FreeBusyQueryJob(email, QDateTime::currentDateTimeUtc(), QDateTime::currentDateTimeUtc().addSecs(3600), m_settings->accountPtr(), const_cast(this)); connect(job, &KGAPI2::Job::finished, this, [this](KGAPI2::Job *job){ auto queryJob = qobject_cast(job); if (!m_resource->handleError(job, false)) { m_resource->handlesFreeBusy(queryJob->id(), false); return; } m_resource->handlesFreeBusy(queryJob->id(), true); }); } void CalendarHandler::retrieveFreeBusy(const QString &email, const QDateTime &start, const QDateTime &end) { if (m_resource->canPerformTask()) { m_resource->freeBusyRetrieved(email, QString(), false, QString()); return; } auto job = new FreeBusyQueryJob(email, start, end, m_settings->accountPtr(), this); connect(job, &KGAPI2::Job::finished, this, [this](KGAPI2::Job *job) { auto queryJob = qobject_cast(job); if (!m_resource->handleError(job, false)) { m_resource->freeBusyRetrieved(queryJob->id(), QString(), false, QString()); return; } KCalendarCore::FreeBusy::Ptr fb(new KCalendarCore::FreeBusy); fb->setUid(QStringLiteral("%1%2@google.com").arg(QDateTime::currentDateTimeUtc().toString(QStringLiteral("yyyyMMddTHHmmssZ")))); fb->setOrganizer(job->account()->accountName()); fb->addAttendee(KCalendarCore::Attendee(QString(), queryJob->id())); // FIXME: is it really sort? fb->setDateTime(QDateTime::currentDateTimeUtc(), KCalendarCore::IncidenceBase::RoleSort); - - for (const auto &range : queryJob->busy()) { + const auto ranges = queryJob->busy(); + for (const auto &range : ranges) { fb->addPeriod(range.busyStart, range.busyEnd); } KCalendarCore::ICalFormat format; const QString fbStr = format.createScheduleMessage(fb, KCalendarCore::iTIPRequest); m_resource->freeBusyRetrieved(queryJob->id(), fbStr, true, QString()); }); } diff --git a/resources/google-new/contacthandler.cpp b/resources/google-new/contacthandler.cpp index 4db33c7d6..28d6795ee 100644 --- a/resources/google-new/contacthandler.cpp +++ b/resources/google-new/contacthandler.cpp @@ -1,494 +1,494 @@ /* Copyright (C) 2011-2013 Daniel Vrátil 2020 Igor Poboiko 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 . */ #include "contacthandler.h" #include "googleresource.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "googlecontacts_debug.h" #define OTHERCONTACTS_REMOTEID QStringLiteral("OtherContacts") #define MODIFIED_PROPERTY "modifiedItems" using namespace KGAPI2; using namespace Akonadi; QString ContactHandler::mimetype() { return KContacts::Addressee::mimeType(); } bool ContactHandler::canPerformTask(const Item &item) { return m_resource->canPerformTask(item, mimetype()); } QString ContactHandler::myContactsRemoteId() const { return QStringLiteral("http://www.google.com/m8/feeds/groups/%1/base/6").arg(QString::fromLatin1(QUrl::toPercentEncoding(m_settings->accountPtr()->accountName()))); } Collection ContactHandler::setupCollection(const ContactsGroupPtr &group, const QString &realName) { Collection collection; collection.setContentMimeTypes({ KContacts::Addressee::mimeType() }); collection.setName(group->id()); collection.setRemoteId(group->id()); collection.setParentCollection(m_resource->rootCollection()); // "My Contacts" is the only one not virtual if (group->id() == myContactsRemoteId()) { collection.setRights(Collection::CanCreateItem |Collection::CanChangeItem |Collection::CanDeleteItem); } else { collection.setRights(Collection::CanLinkItem |Collection::CanUnlinkItem |Collection::CanChangeItem); collection.setVirtual(true); if (!group->isSystemGroup()) { collection.setRights(collection.rights() |Collection::CanChangeCollection |Collection::CanDeleteCollection); } } auto attr = collection.attribute(Collection::AddIfMissing); attr->setDisplayName(realName); attr->setIconName(QStringLiteral("view-pim-contacts")); return collection; } void ContactHandler::retrieveCollections() { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Retrieving contacts groups")); qCDebug(GOOGLE_CONTACTS_LOG) << "Retrieving contacts groups..."; m_collections.clear(); Collection otherCollection; otherCollection.setContentMimeTypes({ KContacts::Addressee::mimeType() }); otherCollection.setName(i18n("Other Contacts")); otherCollection.setParentCollection(m_resource->rootCollection()); otherCollection.setRights(Collection::CanCreateItem |Collection::CanChangeItem |Collection::CanDeleteItem); otherCollection.setRemoteId(OTHERCONTACTS_REMOTEID); auto attr = otherCollection.attribute(Collection::AddIfMissing); attr->setDisplayName(i18n("Other Contacts")); attr->setIconName(QStringLiteral("view-pim-contacts")); m_collections[ OTHERCONTACTS_REMOTEID ] = otherCollection; auto job = new ContactsGroupFetchJob(m_settings->accountPtr(), this); connect(job, &ContactFetchJob::finished, this, &ContactHandler::slotCollectionsRetrieved); } void ContactHandler::slotCollectionsRetrieved(KGAPI2::Job* job) { if (!m_resource->handleError(job)) { return; } qCDebug(GOOGLE_CONTACTS_LOG) << "Contacts groups retrieved"; const ObjectsList objects = qobject_cast(job)->items(); for (const auto &object : objects) { const ContactsGroupPtr group = object.dynamicCast(); qCDebug(GOOGLE_CONTACTS_LOG) << "Retrieved contact group:" << group->id() << "(" << group->title() << ")"; QString realName = group->title(); if (group->isSystemGroup()) { if (group->title().contains(QLatin1String("Coworkers"))) { realName = i18nc("Name of a group of contacts", "Coworkers"); } else if (group->title().contains(QLatin1String("Friends"))) { realName = i18nc("Name of a group of contacts", "Friends"); } else if (group->title().contains(QLatin1String("Family"))) { realName = i18nc("Name of a group of contacts", "Family"); } else if (group->title().contains(QLatin1String("My Contacts"))) { realName = i18nc("Name of a group of contacts", "My Contacts"); } } Collection collection = setupCollection(group, realName); m_collections[ collection.remoteId() ] = collection; } Q_EMIT collectionsRetrieved(valuesToVector(m_collections)); emitReadyStatus(); } void ContactHandler::retrieveItems(const Collection &collection) { // Contacts are stored inside "My Contacts" and "Other Contacts" only if ((collection.remoteId() != OTHERCONTACTS_REMOTEID) && (collection.remoteId() != myContactsRemoteId())) { m_resource->itemsRetrievalDone(); return; } Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Retrieving contacts for group '%1'", collection.displayName())); qCDebug(GOOGLE_CONTACTS_LOG) << "Retreiving contacts for group" << collection.remoteId() << "..."; auto job = new ContactFetchJob(m_settings->accountPtr(), this); job->setFetchDeleted(true); if (!collection.remoteRevision().isEmpty()) { job->setFetchOnlyUpdated(collection.remoteRevision().toLongLong()); } connect(job, &ContactFetchJob::finished, this, &ContactHandler::slotItemsRetrieved); } void ContactHandler::slotItemsRetrieved(KGAPI2::Job *job) { if (!m_resource->handleError(job)) { return; } Collection collection = m_resource->currentCollection(); Item::List changedItems, removedItems; QMap groupsMap; QList changedPhotos; auto fetchJob = qobject_cast(job); bool isIncremental = (fetchJob->fetchOnlyUpdated() > 0); const ObjectsList objects = fetchJob->items(); qCDebug(GOOGLE_CONTACTS_LOG) << "Retrieved" << objects.count() << "contacts"; for (const ObjectPtr &object : objects) { const ContactPtr contact = object.dynamicCast(); // Items inside "My Contacts" should have at least 1 group added, // otherwise contact belongs to "Other Contacts" if (((collection.remoteId() == myContactsRemoteId()) && contact->groups().isEmpty()) || ((collection.remoteId() == OTHERCONTACTS_REMOTEID) && !contact->groups().isEmpty())) { continue; } Item item; item.setMimeType(KContacts::Addressee::mimeType()); item.setParentCollection(collection); item.setRemoteId(contact->uid()); item.setRemoteRevision(contact->etag()); item.setPayload(*contact.dynamicCast()); if (contact->deleted()) { qCDebug(GOOGLE_CONTACTS_LOG) << " - removed" << contact->uid(); removedItems << item; } else { qCDebug(GOOGLE_CONTACTS_LOG) << " - changed" << contact->uid(); changedItems << item; changedPhotos << contact->uid(); } const QStringList groups = contact->groups(); for (const QString &group : groups) { // We don't link contacts to "My Contacts" if (group != myContactsRemoteId()) { groupsMap[group] << item; } } } if (isIncremental) { m_resource->itemsRetrievedIncremental(changedItems, removedItems); } else { m_resource->itemsRetrieved(changedItems); } for (auto iter = groupsMap.constBegin(), iterEnd = groupsMap.constEnd(); iter != iterEnd; ++iter) { new LinkJob(m_collections[iter.key()], iter.value(), this); } if (!changedPhotos.isEmpty()) { QVariantMap map; map[QStringLiteral("collection")] = QVariant::fromValue(collection); map[QStringLiteral("modified")] = QVariant::fromValue(changedPhotos); m_resource->scheduleCustomTask(this, "retrieveContactsPhotos", map); } const QDateTime local(QDateTime::currentDateTime()); const QDateTime UTC(local.toUTC()); collection.setRemoteRevision(QString::number(UTC.toSecsSinceEpoch())); new CollectionModifyJob(collection, this); emitReadyStatus(); } void ContactHandler::retrieveContactsPhotos(const QVariant &argument) { if (!m_resource->canPerformTask()) { return; } const auto map = argument.value(); const auto collection = map[QStringLiteral("collection")].value(); const auto changedPhotos = map[QStringLiteral("modified")].toStringList(); Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Retrieving %1 contacts photos for group '%2'", "Retrieving %1 contact photo for group '%2'", changedPhotos.count(), collection.displayName())); Item::List items; items.reserve(changedPhotos.size()); for (const QString& contact : changedPhotos) { Item item; item.setRemoteId(contact); items << item; } auto job = new ItemFetchJob(items, this); job->setCollection(collection); job->fetchScope().fetchFullPayload(true); connect(job, &ItemFetchJob::finished, this, &ContactHandler::slotUpdatePhotosItemsRetrieved); } void ContactHandler::slotUpdatePhotosItemsRetrieved(KJob *job) { auto fetchJob = qobject_cast(job); ContactsList contacts; const Item::List items = fetchJob->items(); qCDebug(GOOGLE_CONTACTS_LOG) << "Fetched" << items.count() << "contacts for photo update"; for (const Item &item : items) { const KContacts::Addressee addressee = item.payload(); const ContactPtr contact(new Contact(addressee)); contacts << contact; } // Make sure account is still valid if (!m_resource->canPerformTask()) { return; } qCDebug(GOOGLE_CONTACTS_LOG) << "Starting fetching photos..."; auto photoJob = new ContactFetchPhotoJob(contacts, m_settings->accountPtr(), this); photoJob->setProperty("processedItems", 0); connect(photoJob, &ContactFetchPhotoJob::photoFetched, this, [this, items](KGAPI2::Job *job, const ContactPtr &contact){ qCDebug(GOOGLE_CONTACTS_LOG) << " - fetched photo for contact" << contact->uid(); int processedItems = job->property("processedItems").toInt(); processedItems++; job->setProperty("processedItems", processedItems); Q_EMIT percent(100.0f*processedItems / items.count()); for (const Item& item : items) { if (item.remoteId() == contact->uid()) { Item newItem = item; newItem.setPayload(*contact.dynamicCast()); new ItemModifyJob(newItem, this); return; } } }); connect(photoJob, &ContactFetchPhotoJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::itemAdded(const Item &item, const Collection &collection) { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Adding contact to group '%1'", collection.displayName())); auto addressee = item.payload< KContacts::Addressee >(); ContactPtr contact(new Contact(addressee)); qCDebug(GOOGLE_CONTACTS_LOG) << "Creating contact"; if (collection.remoteId() == myContactsRemoteId()) { contact->addGroup(myContactsRemoteId()); } auto job = new ContactCreateJob(contact, m_settings->accountPtr(), this); connect(job, &ContactCreateJob::finished, this, [this, item](KGAPI2::Job* job){ if (!m_resource->handleError(job)) { return; } ContactPtr contact = qobject_cast(job)->items().first().dynamicCast(); Item newItem = item; qCDebug(GOOGLE_CONTACTS_LOG) << "Contact" << contact->uid() << "created"; newItem.setRemoteId(contact->uid()); newItem.setRemoteRevision(contact->etag()); m_resource->changeCommitted(newItem); newItem.setPayload(*contact.dynamicCast()); new ItemModifyJob(newItem, this); emitReadyStatus(); }); } void ContactHandler::itemChanged(const Item &item, const QSet< QByteArray > &partIdentifiers) { Q_UNUSED(partIdentifiers); Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Changing contact")); qCDebug(GOOGLE_CONTACTS_LOG) << "Changing contact" << item.remoteId(); KContacts::Addressee addressee = item.payload< KContacts::Addressee >(); ContactPtr contact(new Contact(addressee)); auto job = new ContactModifyJob(contact, m_settings->accountPtr(), this); job->setProperty(ITEM_PROPERTY, QVariant::fromValue(item)); connect(job, &ContactModifyJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::itemsRemoved(const Item::List &items) { Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Removing contact", "Removing contacts", items.count())); QStringList contactIds; contactIds.reserve(items.count()); std::transform(items.cbegin(), items.cend(), std::back_inserter(contactIds), [](const Item &item){ return item.remoteId(); }); qCDebug(GOOGLE_CONTACTS_LOG) << "Removing contacts" << contactIds; auto job = new ContactDeleteJob(contactIds, m_settings->accountPtr(), this); job->setProperty(ITEMS_PROPERTY, QVariant::fromValue(items)); connect(job, &ContactDeleteJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::itemsMoved(const Item::List &items, const Collection &collectionSource, const Collection &collectionDestination) { qCDebug(GOOGLE_CONTACTS_LOG) << "Moving contacts from" << collectionSource.remoteId() << "to" << collectionDestination.remoteId(); if (!(((collectionSource.remoteId() == myContactsRemoteId()) && (collectionDestination.remoteId() == OTHERCONTACTS_REMOTEID)) || ((collectionSource.remoteId() == OTHERCONTACTS_REMOTEID) && (collectionDestination.remoteId() == myContactsRemoteId())))) { m_resource->cancelTask(i18n("Invalid source or destination collection")); } Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Moving %1 contacts from group '%2' to '%3'", "Moving %1 contact from group '%2' to '%3'", items.count(), collectionSource.remoteId(), collectionDestination.remoteId())); ContactsList contacts; contacts.reserve(items.count()); std::transform(items.cbegin(), items.cend(), std::back_inserter(contacts), [this, &collectionSource, &collectionDestination](const Item &item){ KContacts::Addressee addressee = item.payload(); ContactPtr contact(new Contact(addressee)); // MyContacts -> OtherContacts if (collectionSource.remoteId() == myContactsRemoteId() && collectionDestination.remoteId() == OTHERCONTACTS_REMOTEID) { contact->clearGroups(); // OtherContacts -> MyContacts } else if (collectionSource.remoteId() == OTHERCONTACTS_REMOTEID && collectionDestination.remoteId() == myContactsRemoteId()) { contact->addGroup(myContactsRemoteId()); } return contact; }); qCDebug(GOOGLE_CONTACTS_LOG) << "Moving contacts from" << collectionSource.remoteId() << "to" << collectionDestination.remoteId(); auto job = new ContactModifyJob(contacts, m_settings->accountPtr(), this); job->setProperty(ITEMS_PROPERTY, QVariant::fromValue(items)); connect(job, &ContactModifyJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::itemsLinked(const Item::List &items, const Collection &collection) { Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Linking %1 contact", "Linking %1 contacts", items.count())); qCDebug(GOOGLE_CONTACTS_LOG) << "Linking" << items.count() << "contacts to group" << collection.remoteId(); ContactsList contacts; contacts.reserve(items.count()); std::transform(items.cbegin(), items.cend(), std::back_inserter(contacts), [this, &collection](const Akonadi::Item &item){ KContacts::Addressee addressee = item.payload(); ContactPtr contact(new Contact(addressee)); contact->addGroup(collection.remoteId()); return contact; }); auto job = new ContactModifyJob(contacts, m_settings->accountPtr(), this); job->setProperty(ITEMS_PROPERTY, QVariant::fromValue(items)); connect(job, &ContactModifyJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::itemsUnlinked(const Item::List &items, const Collection &collection) { Q_EMIT status(AgentBase::Running, i18ncp("@info:status", "Unlinking %1 contact", "Unlinking %1 contacts", items.count())); qCDebug(GOOGLE_CONTACTS_LOG) << "Unlinking" << items.count() << "contacts from group" << collection.remoteId(); ContactsList contacts; contacts.reserve(items.count()); std::transform(items.cbegin(), items.cend(), std::back_inserter(contacts), [this, &collection](const Akonadi::Item &item){ KContacts::Addressee addressee = item.payload(); ContactPtr contact(new Contact(addressee)); contact->removeGroup(collection.remoteId()); return contact; }); auto job = new ContactModifyJob(contacts, m_settings->accountPtr(), this); job->setProperty(ITEMS_PROPERTY, QVariant::fromValue(items)); connect(job, &ContactModifyJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::collectionAdded(const Collection &collection, const Collection &parent) { Q_UNUSED(parent); Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Creating new contact group '%1'", collection.displayName())); qCDebug(GOOGLE_CONTACTS_LOG) << "Adding contact group" << collection.displayName(); ContactsGroupPtr group(new ContactsGroup); group->setTitle(collection.name()); group->setIsSystemGroup(false); auto job = new ContactsGroupCreateJob(group, m_settings->accountPtr(), this); - connect(job, &ContactsGroupCreateJob::finished, this, [this, &collection](KGAPI2::Job* job){ + connect(job, &ContactsGroupCreateJob::finished, this, [this](KGAPI2::Job* job){ if (!m_resource->handleError(job)) { return; } ContactsGroupPtr group = qobject_cast(job)->items().first().dynamicCast(); qCDebug(GOOGLE_CONTACTS_LOG) << "Contact group created:" << group->id(); Collection newCollection = setupCollection(group, group->title()); m_collections[ newCollection.remoteId() ] = newCollection; m_resource->changeCommitted(newCollection); emitReadyStatus(); }); } void ContactHandler::collectionChanged(const Collection &collection) { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Changing contact group '%1'", collection.displayName())); qCDebug(GOOGLE_CONTACTS_LOG) << "Changing contact group" << collection.remoteId(); ContactsGroupPtr group(new ContactsGroup()); group->setId(collection.remoteId()); group->setTitle(collection.displayName()); auto job = new ContactsGroupModifyJob(group, m_settings->accountPtr(), this); job->setProperty(COLLECTION_PROPERTY, QVariant::fromValue(collection)); connect(job, &ContactsGroupModifyJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } void ContactHandler::collectionRemoved(const Collection &collection) { Q_EMIT status(AgentBase::Running, i18nc("@info:status", "Removing contact group '%1'", collection.displayName())); qCDebug(GOOGLE_CONTACTS_LOG) << "Removing contact group" << collection.remoteId(); auto job = new ContactsGroupDeleteJob(collection.remoteId(), m_settings->accountPtr(), this); job->setProperty(COLLECTION_PROPERTY, QVariant::fromValue(collection)); connect(job, &ContactsGroupDeleteJob::finished, m_resource, &GoogleResource::slotGenericJobFinished); } diff --git a/resources/google-new/googleresource.cpp b/resources/google-new/googleresource.cpp index fed3cd3a4..11e27a1f0 100644 --- a/resources/google-new/googleresource.cpp +++ b/resources/google-new/googleresource.cpp @@ -1,529 +1,529 @@ /* Copyright (C) 2011-2013 Daniel Vrátil 2020 Igor Poboiko 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 . */ #include "googleresource.h" #include "googlesettings.h" #include "googlesettingsdialog.h" #include "googleresource_debug.h" #include "settingsadaptor.h" #include "calendarhandler.h" #include "contacthandler.h" #include "taskhandler.h" #include "defaultreminderattribute.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define ACCESS_TOKEN_PROPERTY "AccessToken" #define CALENDARS_PROPERTY "_KGAPI2CalendarPtr" #define ROOT_COLLECTION_REMOTEID QStringLiteral("RootCollection") Q_DECLARE_METATYPE(KGAPI2::Job *) using namespace KGAPI2; using namespace Akonadi; GoogleResource::GoogleResource(const QString &id) : ResourceBase(id) , AgentBase::ObserverV3() { AttributeFactory::registerAttribute< DefaultReminderAttribute >(); connect(this, &GoogleResource::abortRequested, this, [this](){ cancelTask(i18n("Aborted")); }); connect(this, &GoogleResource::reloadConfiguration, this, &GoogleResource::reloadConfig); setNeedsNetwork(true); changeRecorder()->itemFetchScope().fetchFullPayload(true); changeRecorder()->itemFetchScope().setAncestorRetrieval(ItemFetchScope::All); changeRecorder()->fetchCollection(true); changeRecorder()->collectionFetchScope().setAncestorRetrieval(CollectionFetchScope::All); m_settings = new GoogleSettings(); m_settings->setWindowId(winIdForDialogs()); connect(m_settings, &GoogleSettings::accountReady, this, [this](bool ready){ if (accountId() > 0) { return; } if (!ready) { Q_EMIT status(Broken, i18n("Can't access KWallet")); return; } if (m_settings->accountPtr().isNull()) { Q_EMIT status(NotConfigured); return; } Q_EMIT status(Idle, i18nc("@info:status", "Ready")); synchronize(); }); Q_EMIT status(NotConfigured, i18n("Waiting for KWallet...")); updateResourceName(); m_freeBusyHandler.reset(new CalendarHandler(this, m_settings)); m_handlers << m_freeBusyHandler; m_handlers << GenericHandler::Ptr(new ContactHandler(this, m_settings)); m_handlers << GenericHandler::Ptr(new TaskHandler(this, m_settings)); - for (auto handler : m_handlers) { + for (const auto &handler : qAsConst(m_handlers)) { connect(handler.data(), &GenericHandler::status, this, [this](int code, QString message){ Q_EMIT status(code, message); }); connect(handler.data(), &GenericHandler::percent, this, [this](int value){ Q_EMIT percent(value); }); connect(handler.data(), &GenericHandler::collectionsRetrieved, this, &GoogleResource::collectionsPartiallyRetrieved); } new SettingsAdaptor(m_settings); QDBusConnection::sessionBus().registerObject(QStringLiteral("/Settings"), m_settings, QDBusConnection::ExportAdaptors); } GoogleResource::~GoogleResource() { } void GoogleResource::cleanup() { m_settings->cleanup(); ResourceBase::cleanup(); } Akonadi::Collection GoogleResource::rootCollection() const { return m_rootCollection; } void GoogleResource::configure(WId windowId) { if (!m_settings->isReady() || m_isConfiguring) { Q_EMIT configurationDialogAccepted(); return; } m_isConfiguring = true; QScopedPointer settingsDialog(new GoogleSettingsDialog(this, m_settings, windowId)); settingsDialog->setWindowIcon(QIcon::fromTheme(QStringLiteral("im-google"))); if (settingsDialog->exec() == QDialog::Accepted) { updateResourceName(); Q_EMIT configurationDialogAccepted(); if (m_settings->accountPtr().isNull()) { Q_EMIT status(NotConfigured, i18n("Configured account does not exist")); m_isConfiguring = false; return; } Q_EMIT status(Idle, i18nc("@info:status", "Ready")); synchronize(); } else { updateResourceName(); Q_EMIT configurationDialogRejected(); } m_isConfiguring = false; } QList GoogleResource::scopes() const { // TODO: determine it based on what user wants? const QList< QUrl > scopes = {Account::accountInfoScopeUrl(), Account::calendarScopeUrl(), Account::contactsScopeUrl(), Account::tasksScopeUrl()}; return scopes; } void GoogleResource::updateResourceName() { const QString accountName = m_settings->account(); setName(i18nc("%1 is account name (user@gmail.com)", "Google Groupware (%1)", accountName.isEmpty() ? i18n("not configured") : accountName)); } void GoogleResource::reloadConfig() { const AccountPtr account = m_settings->accountPtr(); if (account.isNull() || account->accountName().isEmpty()) { Q_EMIT status(NotConfigured, i18n("Configured account does not exist")); } else { Q_EMIT status(Idle, i18nc("@info:status", "Ready")); } } bool GoogleResource::handleError(KGAPI2::Job *job, bool _cancelTask) { if ((job->error() == KGAPI2::NoError) || (job->error() == KGAPI2::OK)) { return true; } qCWarning(GOOGLE_LOG) << "Got error:" << job << job->errorString(); AccountPtr account = job->account(); if (job->error() == KGAPI2::Unauthorized) { const QList resourceScopes = scopes(); for (const QUrl &scope : resourceScopes) { if (!account->scopes().contains(scope)) { account->addScope(scope); } } AuthJob *authJob = new AuthJob(account, m_settings->clientId(), m_settings->clientSecret(), this); authJob->setProperty(JOB_PROPERTY, QVariant::fromValue(job)); connect(authJob, &AuthJob::finished, this, &GoogleResource::slotAuthJobFinished); return false; } if (_cancelTask) { cancelTask(job->errorString()); } return false; } bool GoogleResource::canPerformTask() { if (!m_settings->accountPtr() && accountId() == 0) { cancelTask(i18nc("@info:status", "Resource is not configured")); Q_EMIT status(NotConfigured, i18nc("@info:status", "Resource is not configured")); return false; } return true; } void GoogleResource::slotAuthJobFinished(KGAPI2::Job *job) { if (job->error() != KGAPI2::NoError) { cancelTask(i18n("Failed to refresh tokens")); return; } AuthJob *authJob = qobject_cast(job); AccountPtr account = authJob->account(); if (!m_settings->storeAccount(account)) { qCWarning(GOOGLE_LOG) << "Failed to store account in KWallet"; } KGAPI2::Job *otherJob = job->property(JOB_PROPERTY).value(); if (otherJob) { otherJob->setAccount(account); otherJob->restart(); } } void GoogleResource::slotGenericJobFinished(KGAPI2::Job *job) { if (!handleError(job)) { return; } qCDebug(GOOGLE_LOG) << "Job finished"; if (job->property(ITEM_PROPERTY).isValid()) { changeCommitted(job->property(ITEM_PROPERTY).value()); } else if (job->property(ITEMS_PROPERTY).isValid()) { changesCommitted(job->property(ITEMS_PROPERTY).value()); } else if (job->property(COLLECTION_PROPERTY).isValid()) { changeCommitted(job->property(COLLECTION_PROPERTY).value()); } else { taskDone(); } Q_EMIT status(Idle, i18nc("@info:status", "Ready")); } int GoogleResource::accountId() const { return 0; } QDateTime GoogleResource::lastCacheUpdate() const { if (m_freeBusyHandler) { return m_freeBusyHandler->lastCacheUpdate(); } return QDateTime(); } void GoogleResource::canHandleFreeBusy(const QString &email) const { if (m_freeBusyHandler) { m_freeBusyHandler->canHandleFreeBusy(email); } else { handlesFreeBusy(email, false); } } void GoogleResource::retrieveFreeBusy(const QString &email, const QDateTime &start, const QDateTime &end) { if (m_freeBusyHandler) { m_freeBusyHandler->retrieveFreeBusy(email, start, end); } else { freeBusyRetrieved(email, QString(), false, QString()); } } /* * Collection handling */ void GoogleResource::retrieveCollections() { qCDebug(GOOGLE_LOG) << "Retrieve Collections"; if (!canPerformTask()) { return; } CachePolicy cachePolicy; if (m_settings->enableIntervalCheck()) { cachePolicy.setInheritFromParent(false); cachePolicy.setIntervalCheckTime(m_settings->intervalCheckTime()); } // Setting up root collection m_rootCollection = Collection(); m_rootCollection.setContentMimeTypes({ Collection::mimeType(), Collection::virtualMimeType() }); m_rootCollection.setRemoteId(ROOT_COLLECTION_REMOTEID); m_rootCollection.setName(m_settings->accountPtr()->accountName()); m_rootCollection.setParentCollection(Collection::root()); m_rootCollection.setRights(Collection::CanCreateCollection); m_rootCollection.setCachePolicy(cachePolicy); EntityDisplayAttribute *attr = m_rootCollection.attribute(Collection::AddIfMissing); attr->setDisplayName(m_settings->accountPtr()->accountName()); attr->setIconName(QStringLiteral("im-google")); m_collections = { m_rootCollection }; m_jobs = 0; - for (auto handler : m_handlers) { + for (auto &handler : m_handlers) { handler->retrieveCollections(); m_jobs++; } } void GoogleResource::collectionsPartiallyRetrieved(const Collection::List& collections) { m_jobs--; m_collections << collections; if (m_jobs == 0) { qCDebug(GOOGLE_LOG) << "Collections retrieved!"; collectionsRetrieved(m_collections); } } void GoogleResource::retrieveItems(const Akonadi::Collection &collection) { if (!canPerformTask()) { return; } auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&collection](const GenericHandler::Ptr &handler){ return collection.contentMimeTypes().contains(handler->mimetype()); }); if (it != m_handlers.end()) { (*it)->retrieveItems(collection); } else { qCWarning(GOOGLE_LOG) << "Unknown collection" << collection.name(); itemsRetrieved({}); } } void GoogleResource::itemAdded(const Akonadi::Item &item, const Akonadi::Collection &collection) { if (!canPerformTask()) { return; } auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&collection, &item](const GenericHandler::Ptr &handler){ return collection.contentMimeTypes().contains(handler->mimetype()) && handler->canPerformTask(item); }); if (it != m_handlers.end()) { (*it)->itemAdded(item, collection); } else { qCWarning(GOOGLE_LOG) << "Could not add item" << item.mimeType(); cancelTask(i18n("Invalid payload type")); } } void GoogleResource::itemChanged(const Akonadi::Item &item, const QSet< QByteArray > &partIdentifiers) { Q_UNUSED(partIdentifiers); if (!canPerformTask()) { return; } auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&item](const GenericHandler::Ptr &handler){ return handler->canPerformTask(item); }); if (it != m_handlers.end()) { (*it)->itemChanged(item, partIdentifiers); } else { qCWarning(GOOGLE_LOG) << "Could not change item" << item.mimeType(); cancelTask(i18n("Invalid payload type")); } } void GoogleResource::itemsRemoved(const Item::List &items) { if (!canPerformTask()) { return; } // TODO: what if items have different mimetypes? const QString mimeType = items.first().mimeType(); auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&mimeType](const GenericHandler::Ptr &handler){ return handler->mimetype() == mimeType; }); if (it != m_handlers.end()) { (*it)->itemsRemoved(items); } else { qCWarning(GOOGLE_LOG) << "Could not remove item" << mimeType; cancelTask(i18n("Invalid payload type")); } } void GoogleResource::itemsMoved(const Item::List &items, const Akonadi::Collection &collectionSource, const Akonadi::Collection &collectionDestination) { if (!canPerformTask()) { return; } // TODO: what if items have different mimetypes? auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&item = items.first()](const GenericHandler::Ptr &handler){ return handler->canPerformTask(item); }); if (it != m_handlers.end()) { (*it)->itemsMoved(items, collectionSource, collectionDestination); } else { qCWarning(GOOGLE_LOG) << "Could not move item" << items.first().mimeType() << "from" << collectionSource.remoteId() << "to" << collectionDestination.remoteId(); cancelTask(i18n("Invalid payload type")); } } void GoogleResource::itemsLinked(const Item::List &items, const Akonadi::Collection &collection) { if (!canPerformTask()) { return; } // TODO: what if items have different mimetypes? auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&item = items.first()](const GenericHandler::Ptr &handler){ return handler->canPerformTask(item); }); if (it != m_handlers.end()) { (*it)->itemsLinked(items, collection); } else { qCWarning(GOOGLE_LOG) << "Could not link item" << items.first().mimeType() << "to" << collection.remoteId(); cancelTask(i18n("Invalid payload type")); } } void GoogleResource::itemsUnlinked(const Item::List &items, const Akonadi::Collection &collection) { if (!canPerformTask()) { return; } // TODO: what if items have different mimetypes? auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&item = items.first()](const GenericHandler::Ptr &handler){ return handler->canPerformTask(item); }); if (it != m_handlers.end()) { (*it)->itemsUnlinked(items, collection); } else { qCWarning(GOOGLE_LOG) << "Could not unlink item mimetype" << items.first().mimeType() << "from" << collection.remoteId(); cancelTask(i18n("Invalid payload type")); } } void GoogleResource::collectionAdded(const Akonadi::Collection &collection, const Akonadi::Collection &parent) { if (!canPerformTask()) { return; } auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&collection](const GenericHandler::Ptr &handler){ return collection.contentMimeTypes().contains(handler->mimetype()); }); if (it != m_handlers.end()) { (*it)->collectionAdded(collection, parent); } else { qCWarning(GOOGLE_LOG) << "Could not add collection" << collection.displayName() << "mimetypes:" << collection.contentMimeTypes(); cancelTask(i18n("Unknown collection mimetype")); } } void GoogleResource::collectionChanged(const Akonadi::Collection &collection) { if (!canPerformTask()) { return; } auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&collection](const GenericHandler::Ptr &handler){ return collection.contentMimeTypes().contains(handler->mimetype()); }); if (it != m_handlers.end()) { (*it)->collectionChanged(collection); } else { qCWarning(GOOGLE_LOG) << "Could not change collection" << collection.displayName() << "mimetypes:" << collection.contentMimeTypes(); cancelTask(i18n("Unknown collection mimetype")); } } void GoogleResource::collectionRemoved(const Akonadi::Collection &collection) { if (!canPerformTask()) { return; } auto it = std::find_if(m_handlers.begin(), m_handlers.end(), [&collection](const GenericHandler::Ptr &handler){ return collection.contentMimeTypes().contains(handler->mimetype()); }); if (it != m_handlers.end()) { (*it)->collectionRemoved(collection); } else { qCWarning(GOOGLE_LOG) << "Could not remove collection" << collection.displayName() << "mimetypes:" << collection.contentMimeTypes(); cancelTask(i18n("Unknown collection mimetype")); } } AKONADI_RESOURCE_MAIN(GoogleResource) diff --git a/resources/google-new/googlesettings.cpp b/resources/google-new/googlesettings.cpp index 98fd2729d..d6153ad42 100644 --- a/resources/google-new/googlesettings.cpp +++ b/resources/google-new/googlesettings.cpp @@ -1,166 +1,175 @@ /* Copyright (C) 2011-2013 Dan Vratil 2020 Igor Poboiko 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 . */ #include "googlesettings.h" #include "settingsbase.h" #include "googleresource_debug.h" #include #include #include using namespace KWallet; using namespace KGAPI2; static const QString googleWalletFolder = QStringLiteral("Akonadi Google"); GoogleSettings::GoogleSettings() : m_winId(0) , m_isReady(false) { m_wallet = Wallet::openWallet(Wallet::NetworkWallet(), m_winId, Wallet::Asynchronous); if (m_wallet) { connect(m_wallet.data(), &Wallet::walletOpened, this, &GoogleSettings::slotWalletOpened); } else { qCWarning(GOOGLE_LOG) << "Failed to open wallet!"; } } void GoogleSettings::slotWalletOpened(bool success) { if (!success) { qCWarning(GOOGLE_LOG) << "Failed to open wallet!"; Q_EMIT accountReady(false); return; } if (!m_wallet->hasFolder(googleWalletFolder) && !m_wallet->createFolder(googleWalletFolder)) { qCWarning(GOOGLE_LOG) << "Failed to create wallet folder" << googleWalletFolder; Q_EMIT accountReady(false); return; } if (!m_wallet->setFolder(googleWalletFolder)) { qWarning() << "Failed to open wallet folder" << googleWalletFolder; Q_EMIT accountReady(false); return; } qCDebug(GOOGLE_LOG) << "Wallet opened, reading" << account(); if (!account().isEmpty()) { m_account = fetchAccountFromWallet(account()); } m_isReady = true; Q_EMIT accountReady(true); } KGAPI2::AccountPtr GoogleSettings::fetchAccountFromWallet(const QString &accountName) { if (!m_wallet->entryList().contains(accountName)) { qCDebug(GOOGLE_LOG) << "Account" << accountName << "not found in KWallet"; return AccountPtr(); } QMap map; m_wallet->readMap(accountName, map); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) const QStringList scopes = map[QStringLiteral("scopes")].split(QLatin1Char(','), QString::SkipEmptyParts); #else const QStringList scopes = map[QStringLiteral("scopes")].split(QLatin1Char(','), Qt::SkipEmptyParts); #endif QList scopeUrls; scopeUrls.reserve(scopes.count()); for (const QString &scope : scopes) { scopeUrls << QUrl(scope); } AccountPtr account(new Account(accountName, map[QStringLiteral("accessToken")], map[QStringLiteral("refreshToken")], scopeUrls)); return account; } bool GoogleSettings::storeAccount(AccountPtr account) { // Removing the old one (if present) if (m_account && (account->accountName() != m_account->accountName())) { cleanup(); } // Populating the new one m_account = account; QStringList scopes; const QList urlScopes = m_account->scopes(); scopes.reserve(urlScopes.count()); for (const QUrl &url : urlScopes) { scopes << url.toString(); } QMap map; map[QStringLiteral("accessToken")] = m_account->accessToken(); map[QStringLiteral("refreshToken")] = m_account->refreshToken(); map[QStringLiteral("scopes")] = scopes.join(QLatin1Char(',')); // Removing previous junk (if present) cleanup(); if (m_wallet->writeMap(m_account->accountName(), map) != 0) { qCWarning(GOOGLE_LOG) << "Failed to write new account entry to wallet"; return false; } SettingsBase::setAccount(m_account->accountName()); m_isReady = true; return true; } void GoogleSettings::cleanup() { if (m_account && m_wallet) { m_wallet->removeEntry(m_account->accountName()); } } +void GoogleSettings::addCalendar(const QString& calendar) +{ + if (calendars().isEmpty()) { + return; + } + setCalendars(calendars() << calendar); + save(); +} + QString GoogleSettings::clientId() const { return QStringLiteral("554041944266.apps.googleusercontent.com"); } QString GoogleSettings::clientSecret() const { return QStringLiteral("mdT1DjzohxN3npUUzkENT0gO"); } bool GoogleSettings::isReady() const { return m_isReady; } AccountPtr GoogleSettings::accountPtr() { return m_account; } void GoogleSettings::setWindowId(WId id) { m_winId = id; } void GoogleSettings::setResourceId(const QString &resourceIdentificator) { m_resourceId = resourceIdentificator; } diff --git a/resources/google-new/googlesettings.h b/resources/google-new/googlesettings.h index 0af56da00..0664ffc13 100644 --- a/resources/google-new/googlesettings.h +++ b/resources/google-new/googlesettings.h @@ -1,74 +1,76 @@ /* Copyright (C) 2013 Daniel Vrátil 2020 Igor Poboiko 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 . */ #ifndef GOOGLESETTINGS_H #define GOOGLESETTINGS_H #include "settingsbase.h" #include #include #include namespace KWallet { class Wallet; } /** * @brief Settings object * * Provides read-only access to application clientId and * clientSecret and read-write access to accessToken and * refreshToken. Interacts with KWallet. */ class GoogleSettings : public SettingsBase { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.Akonadi.Google.ExtendedSettings") public: GoogleSettings(); void setWindowId(WId id); void setResourceId(const QString &resourceIdentifier); QString appId() const; QString clientId() const; QString clientSecret() const; + void addCalendar(const QString& calendar); + KGAPI2::AccountPtr accountPtr(); // Wallet bool isReady() const; bool storeAccount(KGAPI2::AccountPtr account); void cleanup(); Q_SIGNALS: void accountReady(bool ready); void accountChanged(); private Q_SLOTS: void slotWalletOpened(bool success); private: WId m_winId; QString m_resourceId; bool m_isReady; KGAPI2::AccountPtr m_account; QPointer m_wallet; KGAPI2::AccountPtr fetchAccountFromWallet(const QString &accountName); }; #endif // GOOGLESETTINGS_H