File: kolabhelpers.cpp

package info (click to toggle)
kdepim-runtime 4%3A20.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 25,680 kB
  • sloc: cpp: 94,670; xml: 981; sh: 101; javascript: 60; makefile: 13
file content (540 lines) | stat: -rw-r--r-- 21,240 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*
    Copyright (c) 2014 Christian Mollekopf <mollekopf@kolabsys.com>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "kolabhelpers.h"
#include "kolabresource_debug.h"
#include "kolabresource_trace.h"
#include <KMime/KMimeMessage>
#include <KCalendarCore/Incidence>
#include <AkonadiCore/Collection>
#include <AkonadiCore/ItemFetchJob>
#include <AkonadiCore/ItemFetchScope>
#include <akonadi/notes/noteutils.h>
#include "pimkolab/kolabformat/kolabobject.h"
#include "pimkolab/kolabformat/errorhandler.h"
#include <KLocalizedString>
#include <QColor>

bool KolabHelpers::checkForErrors(const Akonadi::Item &item)
{
    if (!Kolab::ErrorHandler::instance().errorOccured()) {
        Kolab::ErrorHandler::instance().clear();
        return false;
    }

    QString errorMsg;
    foreach (const Kolab::ErrorHandler::Err &error, Kolab::ErrorHandler::instance().getErrors()) {
        errorMsg.append(error.message);
        errorMsg.append(QLatin1Char('\n'));
    }

    qCWarning(KOLABRESOURCE_LOG) << "Error on item with id: " << item.id() << " remote id: " << item.remoteId() << ":\n" << errorMsg;
    Kolab::ErrorHandler::instance().clear();
    return true;
}

Akonadi::Item getErrorItem(Kolab::FolderType folderType, const QString &remoteId)
{
    //TODO set title, text and icon
    Akonadi::Item item;
    item.setRemoteId(remoteId);
    switch (folderType) {
    case Kolab::EventType:
    {
        KCalendarCore::Event::Ptr event(new KCalendarCore::Event);
        //FIXME Use message creation date time
        event->setDtStart(QDateTime::currentDateTimeUtc());
        event->setSummary(i18n("Corrupt Event"));
        event->setDescription(i18n("Event could not be read. Delete this event to remove it from the server. Technical information: remote identifier %1", remoteId));
        item.setMimeType(KCalendarCore::Event::eventMimeType());
        item.setPayload(event);
        break;
    }
    case Kolab::TaskType:
    {
        KCalendarCore::Todo::Ptr task(new KCalendarCore::Todo);
        //FIXME Use message creation date time
        task->setDtStart(QDateTime::currentDateTimeUtc());
        task->setSummary(i18n("Corrupt Task"));
        task->setDescription(i18n("Task could not be read. Delete this task to remove it from the server."));
        item.setMimeType(KCalendarCore::Todo::todoMimeType());
        item.setPayload(task);
        break;
    }
    case Kolab::JournalType:
    {
        KCalendarCore::Journal::Ptr journal(new KCalendarCore::Journal);
        //FIXME Use message creation date time
        journal->setDtStart(QDateTime::currentDateTimeUtc());
        journal->setSummary(i18n("Corrupt journal"));
        journal->setDescription(i18n("Journal could not be read. Delete this journal to remove it from the server."));
        item.setMimeType(KCalendarCore::Journal::journalMimeType());
        item.setPayload(journal);
        break;
    }
    case Kolab::ContactType:
    {
        KContacts::Addressee addressee;
        addressee.setName(i18n("Corrupt Contact"));
        addressee.setNote(i18n("Contact could not be read. Delete this contact to remove it from the server."));
        item.setMimeType(KContacts::Addressee::mimeType());
        item.setPayload(addressee);
        break;
    }
    case Kolab::NoteType:
    {
        Akonadi::NoteUtils::NoteMessageWrapper note;
        note.setTitle(i18n("Corrupt Note"));
        note.setText(i18n("Note could not be read. Delete this note to remove it from the server."));
        item.setPayload(Akonadi::NoteUtils::noteMimeType());
        item.setPayload(note.message());
        break;
    }
    case Kolab::MailType:
    //We don't convert mails, so that should never fail.
    default:
        qCWarning(KOLABRESOURCE_LOG) << "unhandled folder type: " << folderType;
    }
    return item;
}

Akonadi::Item KolabHelpers::translateFromImap(Kolab::FolderType folderType, const Akonadi::Item &imapItem, bool &ok)
{
    //Avoid trying to convert imap messages
    if (folderType == Kolab::MailType) {
        return imapItem;
    }

    //No payload, probably a flag change or alike, we just pass it through
    if (!imapItem.hasPayload()) {
        return imapItem;
    }
    if (!imapItem.hasPayload<KMime::Message::Ptr>()) {
        qCWarning(KOLABRESOURCE_LOG) << "Payload is not a MessagePtr!";
        Q_ASSERT(false);
        ok = false;
        return imapItem;
    }

    const KMime::Message::Ptr payload = imapItem.payload<KMime::Message::Ptr>();
    const Kolab::KolabObjectReader reader(payload);
    if (checkForErrors(imapItem)) {
        ok = true;
        //We return an error object so the sync keeps working, and we can clean up the mess by simply deleting the object in the application.
        return getErrorItem(folderType, imapItem.remoteId());
    }
    switch (reader.getType()) {
    case Kolab::EventObject:
    case Kolab::TodoObject:
    case Kolab::JournalObject:
    {
        const KCalendarCore::Incidence::Ptr incidencePtr = reader.getIncidence();
        if (!incidencePtr) {
            qCWarning(KOLABRESOURCE_LOG) << "Failed to read incidence.";
            ok = false;
            return Akonadi::Item();
        }
        Akonadi::Item newItem(incidencePtr->mimeType());
        newItem.setPayload(incidencePtr);
        newItem.setRemoteId(imapItem.remoteId());
        newItem.setGid(incidencePtr->instanceIdentifier());
        return newItem;
        break;
    }
    case Kolab::NoteObject:
    {
        const KMime::Message::Ptr note = reader.getNote();
        if (!note) {
            qCWarning(KOLABRESOURCE_LOG) << "Failed to read note.";
            ok = false;
            return Akonadi::Item();
        }
        Akonadi::Item newItem(QStringLiteral("text/x-vnd.akonadi.note"));
        newItem.setPayload(note);
        newItem.setRemoteId(imapItem.remoteId());
        const Akonadi::NoteUtils::NoteMessageWrapper wrapper(note);
        newItem.setGid(wrapper.uid());
        return newItem;
        break;
    }
    case Kolab::ContactObject:
    {
        Akonadi::Item newItem(KContacts::Addressee::mimeType());
        newItem.setPayload(reader.getContact());
        newItem.setRemoteId(imapItem.remoteId());
        newItem.setGid(reader.getContact().uid());
        return newItem;
        break;
    }
    case Kolab::DistlistObject:
    {
        KContacts::ContactGroup contactGroup = reader.getDistlist();

        QList<KContacts::ContactGroup::ContactReference> toAdd;
        for (int index = 0; index < contactGroup.contactReferenceCount(); ++index) {
            const KContacts::ContactGroup::ContactReference &reference = contactGroup.contactReference(index);
            KContacts::ContactGroup::ContactReference ref;
            ref.setGid(reference.uid()); //libkolab set a gid with setUid()
            toAdd << ref;
        }
        contactGroup.removeAllContactReferences();
        for (const KContacts::ContactGroup::ContactReference &ref : qAsConst(toAdd)) {
            contactGroup.append(ref);
        }

        Akonadi::Item newItem(KContacts::ContactGroup::mimeType());
        newItem.setPayload(contactGroup);
        newItem.setRemoteId(imapItem.remoteId());
        newItem.setGid(contactGroup.id());
        return newItem;
        break;
    }
    case Kolab::RelationConfigurationObject:
        // Do nothing about tags and relations, this is handled separately in KolabRetrieveTagTask::onMessagesAvailable
        ok = false;
        break;
    default:
        qCWarning(KOLABRESOURCE_LOG) << "Object type not handled";
        ok = false;
        break;
    }
    return Akonadi::Item();
}

Akonadi::Item::List KolabHelpers::translateToImap(const Akonadi::Item::List &items, bool &ok)
{
    Akonadi::Item::List imapItems;
    imapItems.reserve(items.count());
    for (const Akonadi::Item &item : items) {
        bool translationOk = true;
        imapItems << translateToImap(item, translationOk);
        if (!translationOk) {
            ok = false;
        }
    }
    return imapItems;
}

static KContacts::ContactGroup convertToGidOnly(const KContacts::ContactGroup &contactGroup)
{
    QList<KContacts::ContactGroup::ContactReference> toAdd;
    for (int index = 0; index < contactGroup.contactReferenceCount(); ++index) {
        const KContacts::ContactGroup::ContactReference &reference = contactGroup.contactReference(index);
        QString gid;
        if (!reference.gid().isEmpty()) {
            gid = reference.gid();
        } else {
            // WARNING: this is an ugly hack for backwards compatibility. Normally this codepath shouldn't be hit.
            // Replace all references with real data-sets
            // Hopefully all resources are available during saving, so we can look up
            // in the addressbook to get name+email from the UID.

            const Akonadi::Item item(reference.uid().toLongLong());
            Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(item);
            job->fetchScope().fetchFullPayload();
            if (!job->exec()) {
                continue;
            }

            const Akonadi::Item::List items = job->items();
            if (items.count() != 1) {
                continue;
            }
            const KContacts::Addressee addressee = job->items().at(0).payload<KContacts::Addressee>();
            gid = addressee.uid();
        }
        KContacts::ContactGroup::ContactReference ref;
        ref.setUid(gid); //libkolab expects a gid for uid()
        toAdd << ref;
    }
    KContacts::ContactGroup gidOnlyContactGroup = contactGroup;
    gidOnlyContactGroup.removeAllContactReferences();
    for (const KContacts::ContactGroup::ContactReference &ref : qAsConst(toAdd)) {
        gidOnlyContactGroup.append(ref);
    }
    return gidOnlyContactGroup;
}

Akonadi::Item KolabHelpers::translateToImap(const Akonadi::Item &item, bool &ok)
{
    ok = true;
    //imap messages don't need to be translated
    if (item.mimeType() == KMime::Message::mimeType()) {
        Q_ASSERT(item.hasPayload<KMime::Message::Ptr>());
        return item;
    }
    const QLatin1String productId("Akonadi-Kolab-Resource");
    //Everthing stays the same, except mime type and payload
    Akonadi::Item imapItem = item;
    imapItem.setMimeType(QStringLiteral("message/rfc822"));
    try {
        switch (getKolabTypeFromMimeType(item.mimeType())) {
        case Kolab::EventObject:
        case Kolab::TodoObject:
        case Kolab::JournalObject:
        {
            qCDebug(KOLABRESOURCE_LOG) << "converted event";
            const KMime::Message::Ptr message = Kolab::KolabObjectWriter::writeIncidence(
                item.payload<KCalendarCore::Incidence::Ptr>(),
                Kolab::KolabV3, productId, QStringLiteral("UTC"));
            imapItem.setPayload(message);
            break;
        }
        case Kolab::NoteObject:
        {
            qCDebug(KOLABRESOURCE_LOG) << "converted note";
            const KMime::Message::Ptr message = Kolab::KolabObjectWriter::writeNote(
                item.payload<KMime::Message::Ptr>(), Kolab::KolabV3, productId);
            imapItem.setPayload(message);
            break;
        }
        case Kolab::ContactObject:
        {
            qCDebug(KOLABRESOURCE_LOG) << "converted contact";
            const KMime::Message::Ptr message = Kolab::KolabObjectWriter::writeContact(
                item.payload<KContacts::Addressee>(), Kolab::KolabV3, productId);
            imapItem.setPayload(message);
            break;
        }
        case Kolab::DistlistObject:
        {
            const KContacts::ContactGroup contactGroup = convertToGidOnly(item.payload<KContacts::ContactGroup>());
            qCDebug(KOLABRESOURCE_LOG) << "converted distlist";
            const KMime::Message::Ptr message = Kolab::KolabObjectWriter::writeDistlist(
                contactGroup, Kolab::KolabV3, productId);
            imapItem.setPayload(message);
            break;
        }
        default:
            qCWarning(KOLABRESOURCE_LOG) << "object type not handled: " << item.id() << item.mimeType();
            ok = false;
            return Akonadi::Item();
        }
    } catch (const Akonadi::PayloadException &e) {
        qCWarning(KOLABRESOURCE_LOG) << "The item contains the wrong or no payload: " << item.id() << item.mimeType();
        qCWarning(KOLABRESOURCE_LOG) << e.what();
        return Akonadi::Item();
    }

    if (checkForErrors(item)) {
        qCWarning(KOLABRESOURCE_LOG) << "an error occurred while trying to translate the item to the kolab format: " << item.id();
        ok = false;
        return Akonadi::Item();
    }
    return imapItem;
}

QByteArray KolabHelpers::kolabTypeForMimeType(const QStringList &contentMimeTypes)
{
    if (contentMimeTypes.contains(KContacts::Addressee::mimeType())) {
        return QByteArrayLiteral("contact");
    } else if (contentMimeTypes.contains(KCalendarCore::Event::eventMimeType())) {
        return QByteArrayLiteral("event");
    } else if (contentMimeTypes.contains(KCalendarCore::Todo::todoMimeType())) {
        return QByteArrayLiteral("task");
    } else if (contentMimeTypes.contains(KCalendarCore::Journal::journalMimeType())) {
        return QByteArrayLiteral("journal");
    } else if (contentMimeTypes.contains(QLatin1String("application/x-vnd.akonadi.note"))
               || contentMimeTypes.contains(QLatin1String("text/x-vnd.akonadi.note"))) {
        return QByteArrayLiteral("note");
    }
    return QByteArray();
}

Kolab::ObjectType KolabHelpers::getKolabTypeFromMimeType(const QString &type)
{
    if (type == KCalendarCore::Event::eventMimeType()) {
        return Kolab::EventObject;
    } else if (type == KCalendarCore::Todo::todoMimeType()) {
        return Kolab::TodoObject;
    } else if (type == KCalendarCore::Journal::journalMimeType()) {
        return Kolab::JournalObject;
    } else if (type == KContacts::Addressee::mimeType()) {
        return Kolab::ContactObject;
    } else if (type == KContacts::ContactGroup::mimeType()) {
        return Kolab::DistlistObject;
    } else if (type == QLatin1String("text/x-vnd.akonadi.note")
               || type == QLatin1String("application/x-vnd.akonadi.note")) {
        return Kolab::NoteObject;
    }
    return Kolab::InvalidObject;
}

QString KolabHelpers::getMimeType(Kolab::FolderType type)
{
    switch (type) {
    case Kolab::MailType:
        return KMime::Message::mimeType();
    case Kolab::ConfigurationType:
        return QStringLiteral(KOLAB_TYPE_RELATION);
    default:
        qCDebug(KOLABRESOURCE_LOG) << "unhandled folder type: " << type;
    }
    return QString();
}

QStringList KolabHelpers::getContentMimeTypes(Kolab::FolderType type)
{
    QStringList contentTypes;
    contentTypes << Akonadi::Collection::mimeType();
    switch (type) {
    case Kolab::EventType:
        contentTypes <<  KCalendarCore::Event().mimeType();
        break;
    case Kolab::TaskType:
        contentTypes <<  KCalendarCore::Todo().mimeType();
        break;
    case Kolab::JournalType:
        contentTypes <<  KCalendarCore::Journal().mimeType();
        break;
    case Kolab::ContactType:
        contentTypes << KContacts::Addressee::mimeType() << KContacts::ContactGroup::mimeType();
        break;
    case Kolab::NoteType:
        contentTypes << QStringLiteral("text/x-vnd.akonadi.note") << QStringLiteral("application/x-vnd.akonadi.note");
        break;
    case Kolab::MailType:
        contentTypes << KMime::Message::mimeType();
        break;
    case Kolab::ConfigurationType:
        contentTypes << QStringLiteral(KOLAB_TYPE_RELATION);
        break;
    default:
        break;
    }
    return contentTypes;
}

Kolab::FolderType KolabHelpers::folderTypeFromString(const QByteArray &folderTypeName)
{
    const QByteArray stripped = folderTypeName.split('.').first();
    return Kolab::folderTypeFromString(std::string(stripped.data(), stripped.size()));
}

QByteArray KolabHelpers::getFolderTypeAnnotation(const QMap< QByteArray, QByteArray > &annotations)
{
    if (annotations.contains("/shared" KOLAB_FOLDER_TYPE_ANNOTATION)
        && !annotations.value("/shared" KOLAB_FOLDER_TYPE_ANNOTATION).isEmpty()) {
        return annotations.value("/shared" KOLAB_FOLDER_TYPE_ANNOTATION);
    } else if (annotations.contains("/private" KOLAB_FOLDER_TYPE_ANNOTATION)
               && !annotations.value("/private" KOLAB_FOLDER_TYPE_ANNOTATION).isEmpty()) {
        return annotations.value("/private" KOLAB_FOLDER_TYPE_ANNOTATION);
    }
    return annotations.value(KOLAB_FOLDER_TYPE_ANNOTATION);
}

void KolabHelpers::setFolderTypeAnnotation(QMap< QByteArray, QByteArray > &annotations, const QByteArray &value)
{
    annotations["/shared" KOLAB_FOLDER_TYPE_ANNOTATION] = value;
}

QColor KolabHelpers::getFolderColor(const QMap<QByteArray, QByteArray> &annotations)
{
    // kolab saves the color without a "#", so we need to add it to the rgb string to have a proper QColor
    if (annotations.contains("/shared" KOLAB_COLOR_ANNOTATION) && !annotations.value("/shared" KOLAB_COLOR_ANNOTATION).isEmpty()) {
        return QColor(QStringLiteral("#").append(QString::fromUtf8(annotations.value("/shared" KOLAB_COLOR_ANNOTATION))));
    } else if (annotations.contains("/private" KOLAB_COLOR_ANNOTATION) && !annotations.value("/private" KOLAB_COLOR_ANNOTATION).isEmpty()) {
        return QColor(QStringLiteral("#").append(QString::fromUtf8(annotations.value("/private" KOLAB_COLOR_ANNOTATION))));
    }
    return QColor();
}

void KolabHelpers::setFolderColor(QMap<QByteArray, QByteArray> &annotations, const QColor &color)
{
    // kolab saves the color without a "#", so we need to delete the prefix "#" if we save it to the annotations
    annotations["/shared" KOLAB_COLOR_ANNOTATION] = color.name().toLatin1().remove(0, 1);
}

QString KolabHelpers::getIcon(Kolab::FolderType type)
{
    switch (type) {
    case Kolab::EventType:
    case Kolab::TaskType:
    case Kolab::JournalType:
        return QStringLiteral("view-calendar");
    case Kolab::ContactType:
        return QStringLiteral("view-pim-contacts");
    case Kolab::NoteType:
        return QStringLiteral("view-pim-notes");
    case Kolab::MailType:
    case Kolab::ConfigurationType:
    case Kolab::FreebusyType:
    case Kolab::FileType:
    case Kolab::LastType:
        return QString();
    }
    return QString();
}

bool KolabHelpers::isHandledType(Kolab::FolderType type)
{
    switch (type) {
    case Kolab::EventType:
    case Kolab::TaskType:
    case Kolab::JournalType:
    case Kolab::ContactType:
    case Kolab::NoteType:
    case Kolab::MailType:
        return true;
    case Kolab::ConfigurationType:
    case Kolab::FreebusyType:
    case Kolab::FileType:
    case Kolab::LastType:
        return false;
    }
    return false;
}

QList<QByteArray> KolabHelpers::ancestorChain(const Akonadi::Collection &col)
{
    Q_ASSERT(col.isValid());
    if (col.parentCollection() == Akonadi::Collection::root() || col == Akonadi::Collection::root() || !col.isValid()) {
        return QList<QByteArray>();
    }
    QList<QByteArray> ancestors = ancestorChain(col.parentCollection());
    Q_ASSERT(!col.remoteId().isEmpty());
    ancestors << col.remoteId().toLatin1().mid(1); //We strip the first character which is always the separator
    return ancestors;
}

QString KolabHelpers::createMemberUrl(const Akonadi::Item &item, const QString &user)
{
    qCDebug(KOLABRESOURCE_TRACE) << item.id() << item.mimeType() << item.gid() << item.hasPayload();
    Kolab::RelationMember member;
    if (item.mimeType() == KMime::Message::mimeType()) {
        if (!item.hasPayload<KMime::Message::Ptr>()) {
            qCWarning(KOLABRESOURCE_LOG) << "Email without payload, failed to add to tag: " << item.id() << item.remoteId();
            return QString();
        }
        KMime::Message::Ptr msg = item.payload<KMime::Message::Ptr>();
        member.uid = item.remoteId().toLong();
        member.user = user;
        member.subject = msg->subject()->asUnicodeString();
        member.messageId = msg->messageID()->asUnicodeString();
        member.date = msg->date()->asUnicodeString();
        member.mailbox = ancestorChain(item.parentCollection());
    } else {
        if (item.gid().isEmpty()) {
            qCWarning(KOLABRESOURCE_LOG) << "Groupware object without GID, failed to add to tag: " << item.id() << item.remoteId();
            return QString();
        }
        member.gid = item.gid();
    }
    return Kolab::generateMemberUrl(member);
}