calendartaskbasehandler.cpp 15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Copyright (C) 2020 by Shashwat Jolly <shashwat.jolly@gmail.com>
 *
 * 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 2 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 <https://www.gnu.org/licenses/>.
 */

#include "calendartaskbasehandler.h"

#include <AkonadiCore/AttributeFactory>
#include <AkonadiCore/CollectionColorAttribute>
#include <AkonadiCore/CollectionModifyJob>
23 24
#include <AkonadiCore/ItemFetchJob>
#include <AkonadiCore/ItemModifyJob>
25 26
#include <KCalendarCore/ICalFormat>
#include <KCalendarCore/MemoryCalendar>
27
#include <KLocalizedString>
28 29 30 31 32 33 34 35 36
#include <QFile>

#include "entriesfetchjob.h"
#include "etesync_debug.h"
#include "etesyncresource.h"

using namespace Akonadi;
using namespace KCalendarCore;

37
CalendarTaskBaseHandler::CalendarTaskBaseHandler(EteSyncResource *resource) : BaseHandler(resource)
38
{
39
    initialiseBaseDirectory();
40
    AttributeFactory::registerAttribute<CollectionColorAttribute>();
41 42
}

43
void CalendarTaskBaseHandler::getItemListFromEntries(std::vector<EteSyncEntryPtr> &entries, Item::List &changedItems, Item::List &removedItems, Collection &collection, const QString &journalUid, QString &prevUid)
44
{
45
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
46 47 48 49 50
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "SetupItems: Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }
51
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
52 53 54

    QMap<QString, KCalendarCore::Incidence::Ptr> incidences;

55
    for (auto &entry : entries) {
56 57
        if (!entry) {
            qCDebug(ETESYNC_LOG) << "SetupItems: Entry is null";
58
            prevUid = QStringFromCharPtr(CharPtr(etesync_entry_get_uid(entry.get())));
59 60
            continue;
        }
61
        EteSyncSyncEntryPtr syncEntry = etesync_entry_get_sync_entry(entry.get(), cryptoManager.get(), prevUid);
62

63 64
        if (!syncEntry) {
            qCDebug(ETESYNC_LOG) << "SetupItems: syncEntry is null for entry" << etesync_entry_get_uid(entry.get());
65
            qCDebug(ETESYNC_LOG) << "EteSync error" << QStringFromCharPtr(CharPtr(etesync_get_error_message()));
66
            prevUid = QStringFromCharPtr(CharPtr(etesync_entry_get_uid(entry.get())));
67 68 69
            continue;
        }

70 71 72
        CharPtr contentStr(etesync_sync_entry_get_content(syncEntry.get()));

        KCalendarCore::ICalFormat format;
Shashwat Jolly's avatar
Shashwat Jolly committed
73
        const KCalendarCore::Incidence::Ptr incidence = format.fromString(QStringFromCharPtr(contentStr));
74

75
        if (!incidence || (incidence->uid()).isEmpty()) {
76
            qCDebug(ETESYNC_LOG) << "Couldn't parse entry with uid" << etesync_entry_get_uid(entry.get());
77
            prevUid = QStringFromCharPtr(CharPtr(etesync_entry_get_uid(entry.get())));
78 79 80
            continue;
        }

81 82
        qCDebug(ETESYNC_LOG) << "Entry parsed into incidence - UID" << incidence->uid();

83 84 85 86 87 88 89 90 91 92 93
        const QString action = QStringFromCharPtr(CharPtr(etesync_sync_entry_get_action(syncEntry.get())));
        if (action == QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_ADD) || action == QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_CHANGE)) {
            incidences[incidence->uid()] = incidence;
        } else if (action == QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_DELETE)) {
            if (incidences.contains(incidence->uid())) {
                incidences.remove(incidence->uid());
            } else {
                Item item;
                item.setMimeType(mimeType());
                item.setParentCollection(collection);
                item.setRemoteId(incidence->uid());
94
                removedItems.push_back(item);
95

96
                deleteLocalCalendar(incidence->uid());
97 98 99 100 101 102 103 104 105 106 107 108
            }
        }

        prevUid = QStringFromCharPtr(CharPtr(etesync_entry_get_uid(entry.get())));
    }

    for (auto it = incidences.constBegin(); it != incidences.constEnd(); it++) {
        Item item;
        item.setMimeType(mimeType());
        item.setParentCollection(collection);
        item.setRemoteId(it.key());
        item.setPayload<KCalendarCore::Incidence::Ptr>(it.value());
109
        changedItems.push_back(item);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

        updateLocalCalendar(it.value());
    }
}

QString CalendarTaskBaseHandler::baseDirectoryPath() const
{
    return mResource->baseDirectoryPath() + QStringLiteral("/Calendar");
}

QString CalendarTaskBaseHandler::getLocalCalendar(const QString &incidenceUid) const
{
    const QString path = baseDirectoryPath() + QLatin1Char('/') + incidenceUid + QLatin1String(".ical");

    QFile file(path);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        qCDebug(ETESYNC_LOG) << "Unable to read " << path << file.errorString();
        return QString();
    }
    QTextStream in(&file);
    return in.readAll();
}

bool CalendarTaskBaseHandler::updateLocalCalendar(const KCalendarCore::Incidence::Ptr &incidence)
{
    const QString path = baseDirectoryPath() + QLatin1Char('/') + incidence->uid() + QLatin1String(".ical");

    QFile file(path);
    if (!file.open(QIODevice::WriteOnly)) {
        qCDebug(ETESYNC_LOG) << "Unable to open " << path << file.errorString();
        return false;
    }
    KCalendarCore::Calendar::Ptr calendar(new MemoryCalendar(QTimeZone::utc()));
    calendar->addIncidence(incidence);
    KCalendarCore::ICalFormat format;
145
    file.write(format.toString(calendar).toUtf8());
146 147 148
    return true;
}

149
void CalendarTaskBaseHandler::deleteLocalCalendar(const QString &incidenceUid)
150
{
151
    const QString path = baseDirectoryPath() + QLatin1Char('/') + incidenceUid + QLatin1String(".ical");
152 153 154 155 156 157 158 159 160 161
    QFile file(path);
    if (!file.remove()) {
        qCDebug(ETESYNC_LOG) << "Unable to remove " << path << file.errorString();
        return;
    }
}

void CalendarTaskBaseHandler::itemAdded(const Akonadi::Item &item,
                                        const Akonadi::Collection &collection)
{
162
    if (!item.hasPayload<Incidence::Ptr>()) {
163
        qCDebug(ETESYNC_LOG) << "Received item with unknown payload - Remote ID: " << item.remoteId();
164 165 166
        mResource->cancelTask(i18n("Received item with unknown payload %1", item.mimeType()));
        return;
    }
167
    KCalendarCore::Calendar::Ptr calendar(new MemoryCalendar(QTimeZone::utc()));
168
    const auto incidence = item.payload<Incidence::Ptr>();
169 170 171 172 173 174 175 176 177

    qCDebug(ETESYNC_LOG) << "Incidence mime type" << incidence->mimeType();

    if (!collection.contentMimeTypes().contains(incidence->mimeType())) {
        qCDebug(ETESYNC_LOG) << "Received item of different type";
        mResource->cancelTask(i18n("Received item of different type"));
        return;
    }

178
    calendar->addIncidence(incidence);
179 180
    KCalendarCore::ICalFormat format;

Shashwat Jolly's avatar
Shashwat Jolly committed
181
    const QString journalUid = collection.remoteId();
182
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
Shashwat Jolly's avatar
Shashwat Jolly committed
183

184 185 186 187 188 189
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

190
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
191

192
    EteSyncSyncEntryPtr syncEntry = etesync_sync_entry_new(QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_ADD), format.toString(calendar));
193 194

    if (!createEteSyncEntry(syncEntry.get(), cryptoManager.get(), collection)) {
195 196
        qCDebug(ETESYNC_LOG) << "Could not create EteSync entry";
        mResource->cancelTask(i18n("Could not create EteSync entry"));
197 198
        return;
    }
199

200 201 202 203
    Item newItem(item);
    newItem.setRemoteId(incidence->uid());
    newItem.setPayload<Incidence::Ptr>(incidence);
    mResource->changeCommitted(newItem);
204 205 206 207 208 209 210

    updateLocalCalendar(item.payload<Incidence::Ptr>());
}

void CalendarTaskBaseHandler::itemChanged(const Akonadi::Item &item,
                                          const QSet<QByteArray> &parts)
{
211 212 213 214 215
    if (!item.hasPayload<Incidence::Ptr>()) {
        qCDebug(ETESYNC_LOG) << "Received item with unknown payload";
        mResource->cancelTask(i18n("Received item with unknown payload %1", item.mimeType()));
        return;
    }
216 217 218
    Collection collection = item.parentCollection();

    KCalendarCore::Calendar::Ptr calendar(new MemoryCalendar(QTimeZone::utc()));
219 220
    const auto incidence = item.payload<Incidence::Ptr>();
    calendar->addIncidence(incidence);
221 222
    KCalendarCore::ICalFormat format;

Shashwat Jolly's avatar
Shashwat Jolly committed
223
    const QString journalUid = collection.remoteId();
224
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
Shashwat Jolly's avatar
Shashwat Jolly committed
225

226 227 228 229 230 231
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

232
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
233

234
    EteSyncSyncEntryPtr syncEntry = etesync_sync_entry_new(QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_CHANGE), format.toString(calendar));
235 236

    if (!createEteSyncEntry(syncEntry.get(), cryptoManager.get(), collection)) {
237 238
        qCDebug(ETESYNC_LOG) << "Could not create EteSync entry";
        mResource->cancelTask(i18n("Could not create EteSync entry"));
239 240
        return;
    }
241

242
    // Using ItemModifyJob + changeProcessed() instead of changeCommitted to handle conflict error - ItemSync modifies local item payload
243 244
    Item newItem(item);
    newItem.setPayload<Incidence::Ptr>(incidence);
245 246 247
    Akonadi::ItemModifyJob *modifyJob = new Akonadi::ItemModifyJob(newItem);
    modifyJob->disableRevisionCheck();
    mResource->changeProcessed();
248 249 250 251 252 253 254 255

    updateLocalCalendar(item.payload<Incidence::Ptr>());
}

void CalendarTaskBaseHandler::itemRemoved(const Akonadi::Item &item)
{
    Collection collection = item.parentCollection();

256 257 258 259 260 261 262 263 264 265
    const QString calendar = getLocalCalendar(item.remoteId());
    if (calendar.isEmpty()) {
        qCDebug(ETESYNC_LOG) << "Could not get local calendar";
        mResource->cancelTask(i18n("Could not get local calendar"));
        return;
    }

    // Delete now, because itemRemoved() may be called when collection is removed
    deleteLocalCalendar(item.remoteId());

Shashwat Jolly's avatar
Shashwat Jolly committed
266
    const QString journalUid = collection.remoteId();
267
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
Shashwat Jolly's avatar
Shashwat Jolly committed
268

269 270 271 272 273
    if (!journal) {
        mResource->cancelTask();
        return;
    }

274
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
275

276
    EteSyncSyncEntryPtr syncEntry = etesync_sync_entry_new(QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_DELETE), calendar);
277 278

    if (!createEteSyncEntry(syncEntry.get(), cryptoManager.get(), collection)) {
279 280
        qCDebug(ETESYNC_LOG) << "Could not create EteSync entry";
        mResource->cancelTask(i18n("Could not create EteSync entry"));
281 282
        return;
    }
283

284
    mResource->changeProcessed();
285 286 287 288
}

void CalendarTaskBaseHandler::collectionAdded(const Akonadi::Collection &collection, const Akonadi::Collection &parent)
{
Shashwat Jolly's avatar
Shashwat Jolly committed
289
    const QString journalUid = QStringFromCharPtr(CharPtr(etesync_gen_uid()));
290
    EteSyncJournalPtr journal = etesync_journal_new(journalUid, ETESYNC_CURRENT_VERSION);
291

292
    EteSyncCollectionInfoPtr info = etesync_collection_info_new(etesyncCollectionType(), collection.displayName(), QString(), ETESYNC_COLLECTION_DEFAULT_COLOR);
293

294
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
295

Shashwat Jolly's avatar
Shashwat Jolly committed
296 297
    if (etesync_journal_set_info(journal.get(), cryptoManager.get(), info.get())) {
        qCDebug(ETESYNC_LOG) << "Could not set journal info";
298
        qCDebug(ETESYNC_LOG) << "EteSync error" << QStringFromCharPtr(CharPtr(etesync_get_error_message()));
Shashwat Jolly's avatar
Shashwat Jolly committed
299 300 301
        mResource->cancelTask(i18n("Could not set journal info"));
        return;
    };
302

Shashwat Jolly's avatar
Shashwat Jolly committed
303 304
    if (etesync_journal_manager_create(mClientState->journalManager(), journal.get())) {
        qCDebug(ETESYNC_LOG) << "Could not create journal";
305
        qCDebug(ETESYNC_LOG) << "EteSync error" << QStringFromCharPtr(CharPtr(etesync_get_error_message()));
306 307 308
        mResource->handleTokenError();
        return;
    }
309 310 311

    Collection newCollection(collection);
    mResource->setupCollection(newCollection, journal.get());
312
    mResource->mJournalsCache[newCollection.remoteId()] = std::move(journal);
313 314 315 316 317
    mResource->changeCommitted(newCollection);
}

void CalendarTaskBaseHandler::collectionChanged(const Akonadi::Collection &collection)
{
Shashwat Jolly's avatar
Shashwat Jolly committed
318
    const QString journalUid = collection.remoteId();
319
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
320

321 322 323 324 325 326
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

327
    auto journalColor = ETESYNC_COLLECTION_DEFAULT_COLOR;
328 329 330 331 332 333 334
    if (collection.hasAttribute<CollectionColorAttribute>()) {
        const CollectionColorAttribute *colorAttr = collection.attribute<CollectionColorAttribute>();
        if (colorAttr) {
            journalColor = colorAttr->color().rgb();
        }
    }

335
    EteSyncCollectionInfoPtr info = etesync_collection_info_new(etesyncCollectionType(), collection.displayName(), QString(), journalColor);
336

337
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
338

Shashwat Jolly's avatar
Shashwat Jolly committed
339 340
    if (etesync_journal_set_info(journal.get(), cryptoManager.get(), info.get())) {
        qCDebug(ETESYNC_LOG) << "Could not set journal info";
341
        qCDebug(ETESYNC_LOG) << "EteSync error" << QStringFromCharPtr(CharPtr(etesync_get_error_message()));
Shashwat Jolly's avatar
Shashwat Jolly committed
342 343 344
        mResource->cancelTask(i18n("Could not set journal info"));
        return;
    };
345

Shashwat Jolly's avatar
Shashwat Jolly committed
346 347
    if (etesync_journal_manager_update(mClientState->journalManager(), journal.get())) {
        qCDebug(ETESYNC_LOG) << "Could not update journal";
348
        qCDebug(ETESYNC_LOG) << "EteSync error" << QStringFromCharPtr(CharPtr(etesync_get_error_message()));
349 350 351
        mResource->handleTokenError();
        return;
    }
352

353 354 355
    Collection newCollection(collection);
    mResource->setupCollection(newCollection, journal.get());
    mResource->changeCommitted(newCollection);
356 357 358 359
}

void CalendarTaskBaseHandler::collectionRemoved(const Akonadi::Collection &collection)
{
Shashwat Jolly's avatar
Shashwat Jolly committed
360
    const QString journalUid = collection.remoteId();
361
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
362

363 364 365 366 367 368
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

Shashwat Jolly's avatar
Shashwat Jolly committed
369 370
    if (etesync_journal_manager_delete(mClientState->journalManager(), journal.get())) {
        qCDebug(ETESYNC_LOG) << "Could not delete journal";
371
        qCDebug(ETESYNC_LOG) << "EteSync error" << QStringFromCharPtr(CharPtr(etesync_get_error_message()));
372 373 374
        mResource->handleTokenError();
        return;
    }
375
    mResource->changeProcessed();
376
}