calendartaskbasehandler.cpp 12.9 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 23 24
/*
 * 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>
#include <KCalendarCore/ICalFormat>
#include <KCalendarCore/MemoryCalendar>
25
#include <KLocalizedString>
26 27 28 29 30 31 32 33 34
#include <QFile>

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

using namespace Akonadi;
using namespace KCalendarCore;

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

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

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

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

        CharPtr contentStr(etesync_sync_entry_get_content(syncEntry.get()));

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

65
        if (!incidence || (incidence->uid()).isEmpty()) {
66
            qCDebug(ETESYNC_LOG) << "Couldn't parse entry";
67 68 69
            continue;
        }

70 71
        qCDebug(ETESYNC_LOG) << "Entry parsed into incidence - UID" << incidence->uid();

72 73 74 75 76 77 78 79 80 81 82
        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());
83
                removedItems.push_back(item);
84 85 86 87 88 89 90 91 92 93 94 95 96 97

                deleteLocalCalendar(incidence);
            }
        }

        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());
98
        changedItems.push_back(item);
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

        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;
134
    file.write(format.toString(calendar).toUtf8());
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    return true;
}

void CalendarTaskBaseHandler::deleteLocalCalendar(const KCalendarCore::Incidence::Ptr &incidence)
{
    const QString path = baseDirectoryPath() + QLatin1Char('/') + incidence->uid() + QLatin1String(".ical");
    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)
{
151 152 153 154 155
    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;
    }
156
    KCalendarCore::Calendar::Ptr calendar(new MemoryCalendar(QTimeZone::utc()));
157
    const auto incidence = item.payload<Incidence::Ptr>();
158 159 160 161 162 163 164 165 166

    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;
    }

167
    calendar->addIncidence(incidence);
168 169
    KCalendarCore::ICalFormat format;

Shashwat Jolly's avatar
Shashwat Jolly committed
170
    const QString journalUid = collection.remoteId();
171
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
Shashwat Jolly's avatar
Shashwat Jolly committed
172

173 174 175 176 177 178
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

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

181
    EteSyncSyncEntryPtr syncEntry = etesync_sync_entry_new(QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_ADD), format.toString(calendar));
182 183

    if (!createEteSyncEntry(syncEntry.get(), cryptoManager.get(), collection)) {
184 185
        qCDebug(ETESYNC_LOG) << "Could not create EteSync entry";
        mResource->cancelTask(i18n("Could not create EteSync entry"));
186 187
        return;
    }
188

189 190 191 192
    Item newItem(item);
    newItem.setRemoteId(incidence->uid());
    newItem.setPayload<Incidence::Ptr>(incidence);
    mResource->changeCommitted(newItem);
193 194 195 196 197 198 199

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

void CalendarTaskBaseHandler::itemChanged(const Akonadi::Item &item,
                                          const QSet<QByteArray> &parts)
{
200 201 202 203 204
    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;
    }
205 206 207
    Collection collection = item.parentCollection();

    KCalendarCore::Calendar::Ptr calendar(new MemoryCalendar(QTimeZone::utc()));
208 209
    const auto incidence = item.payload<Incidence::Ptr>();
    calendar->addIncidence(incidence);
210 211
    KCalendarCore::ICalFormat format;

Shashwat Jolly's avatar
Shashwat Jolly committed
212
    const QString journalUid = collection.remoteId();
213
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
Shashwat Jolly's avatar
Shashwat Jolly committed
214

215 216 217 218 219 220
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

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

223
    EteSyncSyncEntryPtr syncEntry = etesync_sync_entry_new(QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_CHANGE), format.toString(calendar));
224 225

    if (!createEteSyncEntry(syncEntry.get(), cryptoManager.get(), collection)) {
226 227
        qCDebug(ETESYNC_LOG) << "Could not create EteSync entry";
        mResource->cancelTask(i18n("Could not create EteSync entry"));
228 229
        return;
    }
230

231 232 233
    Item newItem(item);
    newItem.setPayload<Incidence::Ptr>(incidence);
    mResource->changeCommitted(newItem);
234 235 236 237 238 239 240 241

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

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

Shashwat Jolly's avatar
Shashwat Jolly committed
242
    const QString journalUid = collection.remoteId();
243
    const EteSyncJournalPtr &journal = mResource->getJournal(journalUid);
Shashwat Jolly's avatar
Shashwat Jolly committed
244

245 246 247 248 249
    if (!journal) {
        mResource->cancelTask();
        return;
    }

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

Shashwat Jolly's avatar
Shashwat Jolly committed
252
    const QString calendar = getLocalCalendar(item.remoteId());
253

254
    EteSyncSyncEntryPtr syncEntry = etesync_sync_entry_new(QStringLiteral(ETESYNC_SYNC_ENTRY_ACTION_DELETE), calendar);
255 256

    if (!createEteSyncEntry(syncEntry.get(), cryptoManager.get(), collection)) {
257 258
        qCDebug(ETESYNC_LOG) << "Could not create EteSync entry";
        mResource->cancelTask(i18n("Could not create EteSync entry"));
259 260
        return;
    }
261

262
    mResource->changeProcessed();
263 264 265 266
}

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

    /// TODO: Description?
271
    EteSyncCollectionInfoPtr info = etesync_collection_info_new(etesyncCollectionType(), collection.displayName(), QString(), ETESYNC_COLLECTION_DEFAULT_COLOR);
272

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

    etesync_journal_set_info(journal.get(), cryptoManager.get(), info.get());

277 278 279 280 281
    const auto result = etesync_journal_manager_create(mClientState->journalManager(), journal.get());
    if (result) {
        mResource->handleTokenError();
        return;
    }
282 283 284

    Collection newCollection(collection);
    mResource->setupCollection(newCollection, journal.get());
285
    mResource->mJournalsCache[newCollection.remoteId()] = std::move(journal);
286 287 288 289 290
    mResource->changeCommitted(newCollection);
}

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

294 295 296 297 298 299
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

300
    auto journalColor = ETESYNC_COLLECTION_DEFAULT_COLOR;
301 302 303 304 305 306 307
    if (collection.hasAttribute<CollectionColorAttribute>()) {
        const CollectionColorAttribute *colorAttr = collection.attribute<CollectionColorAttribute>();
        if (colorAttr) {
            journalColor = colorAttr->color().rgb();
        }
    }

308
    EteSyncCollectionInfoPtr info = etesync_collection_info_new(etesyncCollectionType(), collection.displayName(), QString(), journalColor);
309

310
    EteSyncCryptoManagerPtr cryptoManager = etesync_journal_get_crypto_manager(journal.get(), mClientState->derived(), mClientState->keypair());
311 312 313

    etesync_journal_set_info(journal.get(), cryptoManager.get(), info.get());

314 315 316 317 318
    const auto result = etesync_journal_manager_update(mClientState->journalManager(), journal.get());
    if (result) {
        mResource->handleTokenError();
        return;
    }
319

320 321 322
    Collection newCollection(collection);
    mResource->setupCollection(newCollection, journal.get());
    mResource->changeCommitted(newCollection);
323 324 325 326
}

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

330 331 332 333 334 335
    if (!journal) {
        qCDebug(ETESYNC_LOG) << "Could not get journal";
        mResource->cancelTask(i18n("Could not get journal"));
        return;
    }

336 337 338 339 340
    const auto result = etesync_journal_manager_delete(mClientState->journalManager(), journal.get());
    if (result) {
        mResource->handleTokenError();
        return;
    }
341
    mResource->changeProcessed();
342
}