File: scheduler_p.cpp

package info (click to toggle)
akonadi-calendar 4:18.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 3,808 kB
  • sloc: cpp: 14,079; xml: 36; makefile: 8; sh: 4
file content (667 lines) | stat: -rw-r--r-- 28,641 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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/*
  Copyright (c) 2001,2004 Cornelius Schumacher <schumacher@kde.org>
  Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com>
  Copyright (C) 2012-2013 Sérgio Martins <iamsergio@gmail.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 "scheduler_p.h"
#include "calendarbase_p.h"

#include <kcalutils/stringify.h>

#include <kcalcore/icalformat.h>
#include <kcalcore/freebusycache.h>

#include "akonadicalendar_debug.h"
#include <KLocalizedString>
#include <KMessageBox>
#include <QTimeZone>

using namespace KCalCore;
using namespace Akonadi;

struct Akonadi::Scheduler::Private {
public:
    Private(Scheduler *qq) : q(qq)
    {
    }

    FreeBusyCache *mFreeBusyCache = nullptr;
    bool mShowDialogs = true;
    Scheduler *const q;
};

Scheduler::Scheduler(QObject *parent) : QObject(parent)
    , d(new Akonadi::Scheduler::Private(this))
{
    mFormat = new ICalFormat();
    mFormat->setTimeZone(QTimeZone::systemTimeZone());
}

Scheduler::~Scheduler()
{
    delete mFormat;
    delete d;
}

void Scheduler::setShowDialogs(bool enable)
{
    d->mShowDialogs = enable;
}

void Scheduler::setFreeBusyCache(FreeBusyCache *c)
{
    d->mFreeBusyCache = c;
}

FreeBusyCache *Scheduler::freeBusyCache() const
{
    return d->mFreeBusyCache;
}

void Scheduler::acceptTransaction(const IncidenceBase::Ptr &incidence,
                                  const Akonadi::CalendarBase::Ptr &calendar,
                                  iTIPMethod method,
                                  ScheduleMessage::Status status, const QString &email)
{
    Q_ASSERT(incidence);
    Q_ASSERT(calendar);
    qCDebug(AKONADICALENDAR_LOG) << "method=" << ScheduleMessage::methodName(method);
    connectCalendar(calendar);
    switch (method) {
    case iTIPPublish:
        acceptPublish(incidence, calendar, status, method);
        break;
    case iTIPRequest:
        acceptRequest(incidence, calendar, status, email);
        break;
    case iTIPAdd:
        acceptAdd(incidence, status);
        break;
    case iTIPCancel:
        acceptCancel(incidence, calendar, status, email);
        break;
    case iTIPDeclineCounter:
        acceptDeclineCounter(incidence, status);
        break;
    case iTIPReply:
        acceptReply(incidence, calendar, status, method);
        break;
    case iTIPRefresh:
        acceptRefresh(incidence, status);
        break;
    case iTIPCounter:
        acceptCounter(incidence, status);
        break;
    default:
        qCWarning(AKONADICALENDAR_LOG) << "Unhandled method: " << method;
    }
}

void Scheduler::acceptPublish(const IncidenceBase::Ptr &newIncBase,
                              const Akonadi::CalendarBase::Ptr &calendar,
                              ScheduleMessage::Status status,
                              iTIPMethod method)
{
    if (newIncBase->type() == IncidenceBase::TypeFreeBusy) {
        acceptFreeBusy(newIncBase, method);
        return;
    }

    QString errorString;
    Result result = ResultSuccess;

    qCDebug(AKONADICALENDAR_LOG) << "status="
                                 << KCalUtils::Stringify::scheduleMessageStatus(status);

    Incidence::Ptr newInc = newIncBase.staticCast<Incidence>() ;
    Incidence::Ptr calInc = calendar->incidence(newIncBase->uid());
    switch (status) {
    case ScheduleMessage::Unknown:
    case ScheduleMessage::PublishNew:
    case ScheduleMessage::PublishUpdate:
        if (calInc && newInc) {
            if ((newInc->revision() > calInc->revision()) ||
                    (newInc->revision() == calInc->revision() &&
                     newInc->lastModified() > calInc->lastModified())) {
                const QString oldUid = calInc->uid();

                if (calInc->type() != newInc->type()) {
                    result = ResultAssigningDifferentTypes;
                    errorString = i18n("Error: Assigning different incidence types.");
                    qCritical() << errorString;
                } else {
                    newInc->setSchedulingID(newInc->uid(), oldUid);
                    const bool success = calendar->modifyIncidence(newInc);

                    if (!success) {
                        emit transactionFinished(ResultModifyingError, QStringLiteral("Error modifying incidence"));
                    } else {
                        // signal will be emitted in the handleModifyFinished() slot
                    }

                    return;
                }
            }
        }
        break;
    case ScheduleMessage::Obsolete:
        break;
    default:
        break;
    }

    emit transactionFinished(result, errorString);
}

void Scheduler::acceptRequest(const IncidenceBase::Ptr &incidenceBase,
                              const Akonadi::CalendarBase::Ptr &calendar,
                              ScheduleMessage::Status status,
                              const QString &email)
{
    Incidence::Ptr incidence = incidenceBase.staticCast<Incidence>() ;

    if (incidence->type() == IncidenceBase::TypeFreeBusy) {
        // reply to this request is handled in korganizer's incomingdialog
        emit transactionFinished(ResultSuccess, QString());
        return;
    }

    QString schedulingUid = incidence->uid();
    QString errorString;
    Result result = ResultSuccess;

    const Incidence::List existingIncidences = calendar->incidencesFromSchedulingID(schedulingUid);
    qCDebug(AKONADICALENDAR_LOG) << "status=" << KCalUtils::Stringify::scheduleMessageStatus(status)
                                 << ": found " << existingIncidences.count()
                                 << " incidences with schedulingID " << incidence->schedulingID()
                                 << "; uid was = " << schedulingUid;

    if (existingIncidences.isEmpty()) {
        // Perfectly normal if the incidence doesn't exist. This is probably
        // a new invitation.
        qCDebug(AKONADICALENDAR_LOG) << "incidence not found; calendar = " << calendar.data()
                                     << "; incidence count = " << calendar->incidences().count();
    }

    for (const KCalCore::Incidence::Ptr &existingIncidence : existingIncidences) {
        qCDebug(AKONADICALENDAR_LOG) << "Considering this found event ("
                                     << (existingIncidence->isReadOnly() ? "readonly" : "readwrite")
                                     << ") :" << mFormat->toString(existingIncidence);
        // If it's readonly, we can't possible update it.
        if (existingIncidence->isReadOnly()) {
            continue;
        }

        const QString existingUid = existingIncidence->uid();
        const int existingRevision = existingIncidence->revision();

        if (existingRevision <= incidence->revision()) {
            // The new incidence might be an update for the found one
            bool isUpdate = true;
            // Code for new invitations:
            // If you think we could check the value of "status" to be RequestNew:  we can't.
            // It comes from a similar check inside libical, where the event is compared to
            // other events in the calendar. But if we have another version of the event around
            // (e.g. shared folder for a group), the status could be RequestNew, Obsolete or Updated.
            qCDebug(AKONADICALENDAR_LOG) << "looking in " << existingUid << "'s attendees";
            // This is supposed to be a new request, not an update - however we want to update
            // the existing one to handle the "clicking more than once on the invitation" case.
            // So check the attendee status of the attendee.
            const Attendee::List attendees = existingIncidence->attendees();
            Attendee::List::ConstIterator ait;
            for (ait = attendees.begin(); ait != attendees.end(); ++ait) {
                if ((*ait)->email() == email && (*ait)->status() == Attendee::NeedsAction) {
                    // This incidence wasn't created by me - it's probably in a shared folder
                    // and meant for someone else, ignore it.
                    qCDebug(AKONADICALENDAR_LOG) << "ignoring " << existingUid << " since I'm still NeedsAction there";
                    isUpdate = false;
                    break;
                }
            }
            if (isUpdate) {
                if (existingRevision == incidence->revision() &&
                        existingIncidence->lastModified() > incidence->lastModified()) {
                    // This isn't an update - the found incidence was modified more recently
                    errorString = i18n("This isn't an update. "
                                       "The found incidence was modified more recently.");
//QT5 port
#if 0
                    qCWarning(AKONADICALENDAR_LOG) << errorString
                                                   << "; revision=" << existingIncidence->revision()
                                                   << "; existing->lastModified=" << existingIncidence->lastModified()
                                                   << "; update->lastModified=" << incidence->lastModified();
#endif
                    emit transactionFinished(ResultOutatedUpdate, errorString);
                    return;
                }
                qCDebug(AKONADICALENDAR_LOG) << "replacing existing incidence " << existingUid;
                if (existingIncidence->type() != incidence->type()) {
                    qCritical() << "assigning different incidence types";
                    result = ResultAssigningDifferentTypes;
                    errorString = i18n("Error: Assigning different incidence types.");
                    emit transactionFinished(result, errorString);
                } else {
                    incidence->setSchedulingID(schedulingUid, existingUid) ;

                    if (incidence->hasRecurrenceId()) {
                        Incidence::Ptr existingInstance = calendar->incidence(incidence->instanceIdentifier());
                        if (!existingInstance) {
                            // The organizer created an exception, lets create it in our calendar, we don't have it yet
                            const bool success = calendar->addIncidence(incidence);

                            if (!success) {
                                emit transactionFinished(ResultCreatingError, QStringLiteral("Error creating incidence"));
                            } else {
                                // Signal emitted in the result slot of addFinished()
                            }

                            return;
                        }
                    }

                    const bool success = calendar->modifyIncidence(incidence);

                    if (!success) {
                        emit transactionFinished(ResultModifyingError, i18n("Error modifying incidence"));
                    } else {
                        //handleModifyFinished() will emit the final signal.
                    }
                }
                return;
            }
        } else {
            errorString = i18n("This isn't an update. "
                               "The found incidence was modified more recently.");
            qCWarning(AKONADICALENDAR_LOG) << errorString;
            // This isn't an update - the found incidence has a bigger revision number
            qCDebug(AKONADICALENDAR_LOG) << "This isn't an update - the found incidence has a bigger revision number";
            emit transactionFinished(ResultOutatedUpdate, errorString);
            return;
        }
    }

    // Move the uid to be the schedulingID and make a unique UID
    incidence->setSchedulingID(schedulingUid, CalFormat::createUniqueId());
    // notify the user in case this is an update and we didn't find the to-be-updated incidence
    if (d->mShowDialogs && existingIncidences.isEmpty() && incidence->revision() > 0) {
        KMessageBox::information(
            nullptr,
            xi18nc("@info",
                   "<para>You added an invitation update, but an earlier version of the "
                   "item could not be found in your calendar.</para>"
                   "<para>This may have occurred because:<list>"
                   "<item>the organizer did not include you in the original invitation</item>"
                   "<item>you did not accept the original invitation yet</item>"
                   "<item>you deleted the original invitation from your calendar</item>"
                   "<item>you no longer have access to the calendar containing the invitation</item>"
                   "</list></para>"
                   "<para>This is not a problem, but we thought you should know.</para>"),
            i18nc("@title", "Cannot find invitation to be updated"), QStringLiteral("AcceptCantFindIncidence"));
    }
    qCDebug(AKONADICALENDAR_LOG) << "Storing new incidence with scheduling uid=" << schedulingUid << " and uid=" << incidence->uid();

    const bool success = calendar->addIncidence(incidence);
    if (!success) {
        emit transactionFinished(ResultCreatingError, i18n("Error adding incidence"));
    } else {
        // The slot will emit the result
    }
}

void Scheduler::acceptAdd(const IncidenceBase::Ptr &, ScheduleMessage::Status)
{
    emit transactionFinished(ResultSuccess, QString());
}

void Scheduler::acceptCancel(const IncidenceBase::Ptr &incidenceBase,
                             const Akonadi::CalendarBase::Ptr &calendar,
                             ScheduleMessage::Status status,
                             const QString &attendeeEmail)
{
    Incidence::Ptr incidence = incidenceBase.staticCast<Incidence>();

    if (incidence->type() == IncidenceBase::TypeFreeBusy) {
        // reply to this request is handled in korganizer's incomingdialog
        emit transactionFinished(ResultSuccess, QString());
        return;
    }

    if (incidence->type() == IncidenceBase::TypeJournal) {
        emit transactionFinished(ResultUnsupported, QStringLiteral("Unsupported incidence type"));
        return;
    }

    const Incidence::List existingIncidences = calendar->incidencesFromSchedulingID(incidence->uid());
    qCDebug(AKONADICALENDAR_LOG) << "Scheduler::acceptCancel="
                                 << KCalUtils::Stringify::scheduleMessageStatus(status)
                                 << ": found " << existingIncidences.count()
                                 << " incidences with schedulingID " << incidence->schedulingID();

    Result result = ResultIncidenceToDeleteNotFound;
    QString errorString = i18n("Could not find incidence to delete.");
    foreach (const KCalCore::Incidence::Ptr &existingIncidence, existingIncidences) {
        qCDebug(AKONADICALENDAR_LOG) << "Considering this found event ("
                                     << (existingIncidence->isReadOnly() ? "readonly" : "readwrite")
                                     << ") :" << mFormat->toString(existingIncidence);

        // If it's readonly, we can't possible remove it.
        if (existingIncidence->isReadOnly()) {
            continue;
        }

        const QString existingUid = existingIncidence->uid();

        // Code for new invitations:
        // We cannot check the value of "status" to be RequestNew because
        // "status" comes from a similar check inside libical, where the event
        // is compared to other events in the calendar. But if we have another
        // version of the event around (e.g. shared folder for a group), the
        // status could be RequestNew, Obsolete or Updated.
        qCDebug(AKONADICALENDAR_LOG) << "looking in " << existingUid << "'s attendees";

        // This is supposed to be a new request, not an update - however we want
        // to update the existing one to handle the "clicking more than once
        // on the invitation" case. So check the attendee status of the attendee.
        bool isMine = true;
        const Attendee::List attendees = existingIncidence->attendees();
        for (const KCalCore::Attendee::Ptr &attendee : attendees) {
            if (attendee->email() == attendeeEmail &&
                    attendee->status() == Attendee::NeedsAction) {
                // This incidence wasn't created by me - it's probably in a shared
                // folder and meant for someone else, ignore it.
                qCDebug(AKONADICALENDAR_LOG) << "ignoring " << existingUid << " since I'm still NeedsAction there";
                isMine = false;
                break;
            }
        }

        if (!isMine) {
            continue;
        }

        qCDebug(AKONADICALENDAR_LOG) << "removing existing incidence " << existingUid;
        if (incidence->hasRecurrenceId()) {
            Incidence::Ptr existingInstance = calendar->incidence(incidence->instanceIdentifier());

            if (existingInstance) {
                existingInstance->setStatus(Incidence::StatusCanceled);
                result = calendar->modifyIncidence(existingInstance) ? ResultSuccess : ResultModifyingError;
            } else {
                incidence->setSchedulingID(incidence->uid(), existingIncidence->uid());
                incidence->setStatus(Incidence::StatusCanceled);
                result = calendar->addIncidence(incidence) ? ResultSuccess : ResultCreatingError;
            }

            if (result != ResultSuccess) {
                emit transactionFinished(result, i18n("Error recording exception"));
            }

        } else {
            result = calendar->deleteIncidence(existingIncidence) ? ResultSuccess : ResultErrorDelete;
            if (result != ResultSuccess) {
                emit transactionFinished(result, errorString);
            }
        }

        // The success case will be handled in handleDeleteFinished()
        return;
    }

    // in case we didn't find the to-be-removed incidencez
    if (d->mShowDialogs && !existingIncidences.isEmpty() && incidence->revision() > 0) {
        KMessageBox::error(
            nullptr,
            i18nc("@info",
                  "The event or task could not be removed from your calendar. "
                  "Maybe it has already been deleted or is not owned by you. "
                  "Or it might belong to a read-only or disabled calendar."));
    }
    emit transactionFinished(result, errorString);
}

void Scheduler::acceptDeclineCounter(const IncidenceBase::Ptr &, ScheduleMessage::Status)
{
    //Not sure why KCalUtils::Scheduler returned false here
    emit transactionFinished(ResultGenericError, i18n("Generic Error"));
}

void Scheduler::acceptReply(const IncidenceBase::Ptr &incidenceBase,
                            const Akonadi::CalendarBase::Ptr &calendar,
                            ScheduleMessage::Status status,
                            iTIPMethod method)
{
    Q_UNUSED(status);
    if (incidenceBase->type() == IncidenceBase::TypeFreeBusy) {
        acceptFreeBusy(incidenceBase, method);
        return;
    }

    Result result = ResultGenericError;
    QString errorString = i18n("Generic Error");

    Incidence::Ptr incidence = calendar->incidence(incidenceBase->uid());

    // try harder to find the correct incidence
    if (!incidence) {
        const Incidence::List list = calendar->incidences();
        for (Incidence::List::ConstIterator it = list.constBegin(), end = list.constEnd();
                it != end; ++it) {
            if ((*it)->schedulingID() == incidenceBase->uid()) {
                incidence = (*it).dynamicCast<Incidence>();
                break;
            }
        }
    }

    if (incidence) {
        //get matching attendee in calendar
        qCDebug(AKONADICALENDAR_LOG) << "match found!";
        Attendee::List attendeesIn = incidenceBase->attendees();
        Attendee::List attendeesNew;
        Attendee::List attendeesEv = incidence->attendees();
        Attendee::List::ConstIterator inIt;
        Attendee::List::ConstIterator evIt;
        for (inIt = attendeesIn.constBegin(); inIt != attendeesIn.constEnd(); ++inIt) {
            Attendee::Ptr attIn = *inIt;
            bool found = false;
            for (evIt = attendeesEv.constBegin(); evIt != attendeesEv.constEnd(); ++evIt) {
                Attendee::Ptr attEv = *evIt;
                if (attIn->email().toLower() == attEv->email().toLower()) {
                    //update attendee-info
                    qCDebug(AKONADICALENDAR_LOG) << "update attendee";
                    attEv->setStatus(attIn->status());
                    attEv->setDelegate(attIn->delegate());
                    attEv->setDelegator(attIn->delegator());
                    result = ResultSuccess;
                    errorString.clear();
                    found = true;
                }
            }
            if (!found && attIn->status() != Attendee::Declined) {
                attendeesNew.append(attIn);
            }
        }

        bool attendeeAdded = false;
        for (Attendee::List::ConstIterator it = attendeesNew.constBegin(), end = attendeesNew.constEnd();
                it != end; ++it) {
            Attendee::Ptr attNew = *it;
            QString msg =
                i18nc("@info", "%1 wants to attend %2 but was not invited.",
                      attNew->fullName(), incidence->summary());
            if (!attNew->delegator().isEmpty()) {
                msg = i18nc("@info", "%1 wants to attend %2 on behalf of %3.",
                            attNew->fullName(), incidence->summary(), attNew->delegator());
            }
            if (KMessageBox::questionYesNo(
                        nullptr, msg, i18nc("@title", "Uninvited attendee"),
                        KGuiItem(i18nc("@option", "Accept Attendance")),
                        KGuiItem(i18nc("@option", "Reject Attendance"))) != KMessageBox::Yes) {
                Incidence::Ptr cancel = incidence;
                cancel->addComment(i18nc("@info",
                                         "The organizer rejected your attendance at this meeting."));
                performTransaction(incidenceBase, iTIPCancel, attNew->fullName());
                continue;
            }

            Attendee::Ptr a(new Attendee(attNew->name(), attNew->email(), attNew->RSVP(),
                                         attNew->status(), attNew->role(), attNew->uid()));

            a->setDelegate(attNew->delegate());
            a->setDelegator(attNew->delegator());
            incidence->addAttendee(a);

            result = ResultSuccess;
            errorString.clear();
            attendeeAdded = true;
        }

        // send update about new participants
        if (attendeeAdded) {
            bool sendMail = false;
            if (KMessageBox::questionYesNo(
                        nullptr,
                        i18nc("@info",
                              "An attendee was added to the incidence. "
                              "Do you want to email the attendees an update message?"),
                        i18nc("@title", "Attendee Added"),
                        KGuiItem(i18nc("@option", "Send Messages")),
                        KGuiItem(i18nc("@option", "Do Not Send"))) == KMessageBox::Yes) {
                sendMail = true;
            }

            incidence->setRevision(incidence->revision() + 1);
            if (sendMail) {
                performTransaction(incidence, iTIPRequest);
            }
        }

        if (incidence->type() == Incidence::TypeTodo) {
            // for VTODO a REPLY can be used to update the completion status of
            // a to-do. see RFC2446 3.4.3
            Todo::Ptr update = incidenceBase.dynamicCast<Todo>();
            Todo::Ptr calendarTodo = incidence.staticCast<Todo>();
            Q_ASSERT(update);
            if (update && (calendarTodo->percentComplete() != update->percentComplete())) {
                calendarTodo->setPercentComplete(update->percentComplete());
                calendarTodo->updated();
                const bool success = calendar->modifyIncidence(calendarTodo);
                if (!success) {
                    emit transactionFinished(ResultModifyingError, i18n("Error modifying incidence"));
                } else {
                    // success will be emitted in the handleModifyFinished() slot
                }
                return;
            }
        }

        if (result == ResultSuccess) {
            // We set at least one of the attendees, so the incidence changed
            // Note: This should not result in a sequence number bump
            incidence->updated();
            const bool success = calendar->modifyIncidence(incidence);

            if (!success) {
                emit transactionFinished(ResultModifyingError, i18n("Error modifying incidence"));
            } else {
                // success will be emitted in the handleModifyFinished() slot
            }

            return;
        }
    } else {
        result = ResultSuccess;
        errorString = i18n("No incidence for scheduling.");
        qCritical() << errorString;
    }
    emit transactionFinished(result, errorString);
}

void Scheduler::acceptRefresh(const IncidenceBase::Ptr &, ScheduleMessage::Status)
{
    // handled in korganizer's IncomingDialog
    // Not sure why it returns false here
    emit transactionFinished(ResultGenericError, i18n("Generic Error"));
}

void Scheduler::acceptCounter(const IncidenceBase::Ptr &, ScheduleMessage::Status)
{
    // Not sure why it returns false here
    emit transactionFinished(ResultGenericError, i18n("Generic Error"));
}

void Scheduler::acceptFreeBusy(const IncidenceBase::Ptr &incidence, iTIPMethod method)
{
    if (!d->mFreeBusyCache) {
        qCritical() << "Scheduler: no FreeBusyCache.";
        emit transactionFinished(ResultNoFreeBusyCache, i18n("No Free Busy Cache"));
        return;
    }

    FreeBusy::Ptr freebusy = incidence.staticCast<FreeBusy>();

    qCDebug(AKONADICALENDAR_LOG) << "freeBusyDirName:" << freeBusyDir();

    Person::Ptr from;
    if (method == iTIPPublish) {
        from = freebusy->organizer();
    }
    if ((method == iTIPReply) && (freebusy->attendeeCount() == 1)) {
        Attendee::Ptr attendee = freebusy->attendees().at(0);
        from->setName(attendee->name());
        from->setEmail(attendee->email());
    }

    if (!d->mFreeBusyCache->saveFreeBusy(freebusy, from)) {
        emit transactionFinished(ResultErrorSavingFreeBusy, i18n("Error saving freebusy object"));
    } else {
        emit transactionFinished(ResultNoFreeBusyCache, QString());
    }
}

void Scheduler::handleCreateFinished(bool success, const QString &errorMessage)
{
    CalendarBase *calendar = qobject_cast<Akonadi::CalendarBase *>(sender());
    const bool cancelled = calendar && calendar->d_ptr->mLastCreationCancelled;

    emit transactionFinished(success ? ResultSuccess
                             : (cancelled ? ResultUserCancelled
                                : ResultCreatingError),
                             errorMessage);
}

void Scheduler::handleModifyFinished(bool success, const QString &errorMessage)
{
    qCDebug(AKONADICALENDAR_LOG) << "Modification finished. Success=" << success << errorMessage;
    emit transactionFinished(success ? ResultSuccess : ResultModifyingError, errorMessage);
}

void Scheduler::handleDeleteFinished(bool success, const QString &errorMessage)
{
    emit transactionFinished(success ? ResultSuccess : ResultDeletingError, errorMessage);
}

void Scheduler::connectCalendar(const Akonadi::CalendarBase::Ptr &calendar)
{
    connect(calendar.data(), &CalendarBase::createFinished,
            this, &Scheduler::handleCreateFinished, Qt::UniqueConnection);
    connect(calendar.data(), &CalendarBase::modifyFinished,
            this, &Scheduler::handleModifyFinished, Qt::UniqueConnection);
    connect(calendar.data(), &CalendarBase::deleteFinished,
            this, &Scheduler::handleDeleteFinished, Qt::UniqueConnection);
}