File: freebusymanager.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 (1055 lines) | stat: -rw-r--r-- 36,367 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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
/*
  Copyright (c) 2011 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

  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 "freebusymanager.h"
#include "freebusymanager_p.h"
#include "freebusydownloadjob_p.h"
#include "mailscheduler_p.h"
#include "publishdialog.h"
#include "calendarsettings.h"
#include "utils_p.h"

#include <agentinstance.h>
#include <agentmanager.h>
#include <contactsearchjob.h>

#include <kcalcore/event.h>
#include <kcalcore/freebusy.h>
#include <kcalcore/person.h>

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

#include <QUrl>
#include <KIO/Job>
#include <KIO/JobUiDelegate>
#include <KLocalizedString>

#include <QDir>
#include <QFile>
#include <QRegExp>
#include <QTextStream>
#include <QTimer>
#include <QTimerEvent>
#include <QStandardPaths>
#include <QTemporaryFile>
#include <KJobWidgets/KJobWidgets>

using namespace Akonadi;
using namespace KCalCore;

/// Free helper functions

QUrl replaceVariablesUrl(const QUrl &url, const QString &email)
{
    QString emailName;
    QString emailHost;

    const int atPos = email.indexOf(QLatin1Char('@'));
    if (atPos >= 0) {
        emailName = email.left(atPos);
        emailHost = email.mid(atPos + 1);
    }

    QString saveStr = url.path();
    saveStr.replace(QRegExp(QStringLiteral("%[Ee][Mm][Aa][Ii][Ll]%")), email);
    saveStr.replace(QRegExp(QStringLiteral("%[Nn][Aa][Mm][Ee]%")), emailName);
    saveStr.replace(QRegExp(QStringLiteral("%[Ss][Ee][Rr][Vv][Ee][Rr]%")), emailHost);

    QUrl retUrl(url);
    retUrl.setPath(saveStr);
    return retUrl;
}

// We need this function because using KIO::NetAccess::exists()
// is useless for the http and https protocols. And getting back
// arbitrary data is also useless because a server can respond back
// with a "no such document" page.  So we need smart checking.
FbCheckerJob::FbCheckerJob(const QList<QUrl> &urlsToCheck, QObject *parent)
    : KJob(parent),
      mUrlsToCheck(urlsToCheck)
{
}

void FbCheckerJob::start()
{
    checkNextUrl();
}

void FbCheckerJob::checkNextUrl()
{
    if (mUrlsToCheck.isEmpty()) {
        qCDebug(AKONADICALENDAR_LOG) << "No fb file found";
        setError(KJob::UserDefinedError);
        emitResult();
        return;
    }
    const QUrl url = mUrlsToCheck.takeFirst();

    mData.clear();
    KIO::TransferJob *job = KIO::get(url, KIO::NoReload, KIO::HideProgressInfo);
    connect(job, &KIO::TransferJob::data, this, &FbCheckerJob::dataReceived);
    connect(job, &KIO::TransferJob::result, this, &FbCheckerJob::onGetJobFinished);
}

void FbCheckerJob::dataReceived(KIO::Job *, const QByteArray &data)
{
    mData.append(data);
}

void FbCheckerJob::onGetJobFinished(KJob *job)
{
    KIO::TransferJob *transferJob = static_cast<KIO::TransferJob *>(job);
    if (mData.contains("BEGIN:VCALENDAR")) {
        qCDebug(AKONADICALENDAR_LOG) << "found freebusy";
        mValidUrl = transferJob->url();
        emitResult();
    } else {
        checkNextUrl();
    }
}

QUrl FbCheckerJob::validUrl() const
{
    return mValidUrl;
}

/// FreeBusyManagerPrivate::FreeBusyProviderRequest

FreeBusyManagerPrivate::FreeBusyProviderRequest::FreeBusyProviderRequest(const QString &provider)
    : mRequestStatus(NotStarted), mInterface(nullptr)
{
    mInterface =
        QSharedPointer<QDBusInterface>(
            new QDBusInterface(QStringLiteral("org.freedesktop.Akonadi.Resource.") + provider,
                               QStringLiteral("/FreeBusyProvider"),
                               QStringLiteral("org.freedesktop.Akonadi.Resource.FreeBusyProvider")));
}

/// FreeBusyManagerPrivate::FreeBusyProvidersRequestsQueue

FreeBusyManagerPrivate::FreeBusyProvidersRequestsQueue::FreeBusyProvidersRequestsQueue()
    : mHandlersCount(0), mResultingFreeBusy(nullptr)
{
    // Set the start of the period to today 00:00:00
    mStartTime = QDateTime(QDate::currentDate(), QTime());
    mEndTime = mStartTime.addDays(14);
    mResultingFreeBusy = KCalCore::FreeBusy::Ptr(new KCalCore::FreeBusy(mStartTime, mEndTime));
}

FreeBusyManagerPrivate::FreeBusyProvidersRequestsQueue::FreeBusyProvidersRequestsQueue(
    const QDateTime &start, const QDateTime &end)
    : mHandlersCount(0), mResultingFreeBusy(nullptr)
{
    mStartTime = start;
    mEndTime = end;
    mResultingFreeBusy = KCalCore::FreeBusy::Ptr(new KCalCore::FreeBusy(start, end));
}

/// FreeBusyManagerPrivate

FreeBusyManagerPrivate::FreeBusyManagerPrivate(FreeBusyManager *q)
    : QObject(),
      q_ptr(q),
      mTimerID(0),
      mUploadingFreeBusy(false),
      mBrokenUrl(false),
      mParentWidgetForRetrieval(nullptr)
{
    connect(this, &FreeBusyManagerPrivate::freeBusyUrlRetrieved,
            this, &FreeBusyManagerPrivate::finishProcessRetrieveQueue);
}

QString FreeBusyManagerPrivate::freeBusyDir() const
{
    return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/korganizer/freebusy");
}

void FreeBusyManagerPrivate::checkFreeBusyUrl()
{
    QUrl targetURL(CalendarSettings::self()->freeBusyPublishUrl());
    mBrokenUrl = targetURL.isEmpty() || !targetURL.isValid();
}

static QString configFile()
{
    static QString file = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/korganizer/freebusyurls");
    return file;
}

void FreeBusyManagerPrivate::fetchFreeBusyUrl(const QString &email)
{
    // First check if there is a specific FB url for this email
    KConfig cfg(configFile());
    KConfigGroup group = cfg.group(email);
    QString url = group.readEntry(QStringLiteral("url"));
    if (!url.isEmpty()) {
        qCDebug(AKONADICALENDAR_LOG) << "Found cached url:" << url;
        QUrl cachedUrl(url);
        if (Akonadi::CalendarUtils::thatIsMe(email)) {
            cachedUrl.setUserName(CalendarSettings::self()->freeBusyRetrieveUser());
            cachedUrl.setPassword(CalendarSettings::self()->freeBusyRetrievePassword());
        }
        emit freeBusyUrlRetrieved(email, replaceVariablesUrl(cachedUrl, email));
        return;
    }
    // Try with the url configured by preferred email in kcontactmanager
    Akonadi::ContactSearchJob *job = new Akonadi::ContactSearchJob();
    job->setQuery(Akonadi::ContactSearchJob::Email, email);
    job->setProperty("contactEmail", QVariant::fromValue(email));
    connect(job, &Akonadi::ContactSearchJob::result, this, &FreeBusyManagerPrivate::contactSearchJobFinished);
    job->start();
}

void FreeBusyManagerPrivate::contactSearchJobFinished(KJob *_job)
{
    const QString email = _job->property("contactEmail").toString();

    if (_job->error()) {
        qCritical() << "Error while searching for contact: "
                    << _job->errorString() << ", email = " << email;
        emit freeBusyUrlRetrieved(email, QUrl());
        return;
    }

    Akonadi::ContactSearchJob *job = qobject_cast<Akonadi::ContactSearchJob *>(_job);
    KConfig cfg(configFile());
    KConfigGroup group = cfg.group(email);
    QString url = group.readEntry(QStringLiteral("url"));

    const KContacts::Addressee::List contacts = job->contacts();
    for (const KContacts::Addressee &contact : contacts) {
        const QString pref = contact.preferredEmail();
        if (!pref.isEmpty() && pref != email) {
            group = cfg.group(pref);
            url = group.readEntry("url");
            qCDebug(AKONADICALENDAR_LOG) << "Preferred email of" << email << "is" << pref;
            if (!url.isEmpty()) {
                qCDebug(AKONADICALENDAR_LOG) << "Taken url from preferred email:" << url;
                emit freeBusyUrlRetrieved(email, replaceVariablesUrl(QUrl(url), email));
                return;
            }
        }
    }
    // None found. Check if we do automatic FB retrieving then
    if (!CalendarSettings::self()->freeBusyRetrieveAuto()) {
        // No, so no FB list here
        qCDebug(AKONADICALENDAR_LOG) << "No automatic retrieving";
        emit freeBusyUrlRetrieved(email, QUrl());
        return;
    }

    // Sanity check: Don't download if it's not a correct email
    // address (this also avoids downloading for "(empty email)").
    int emailpos = email.indexOf(QLatin1Char('@'));
    if (emailpos == -1) {
        qCWarning(AKONADICALENDAR_LOG) << "No '@' found in" << email;
        emit freeBusyUrlRetrieved(email, QUrl());
        return;
    }

    const QString emailHost = email.mid(emailpos + 1);

    // Build the URL
    if (CalendarSettings::self()->freeBusyCheckHostname()) {
        // Don't try to fetch free/busy data for users not on the specified servers
        // This tests if the hostnames match, or one is a subset of the other
        const QString hostDomain = QUrl(CalendarSettings::self()->freeBusyRetrieveUrl()).host();
        if (hostDomain != emailHost &&
                !hostDomain.endsWith(QLatin1Char('.') + emailHost) &&
                !emailHost.endsWith(QLatin1Char('.') + hostDomain)) {
            // Host names do not match
            qCDebug(AKONADICALENDAR_LOG) << "Host '" << hostDomain << "' doesn't match email '" << email << '\'';
            emit freeBusyUrlRetrieved(email, QUrl());
            return;
        }
    }

    if (CalendarSettings::self()->freeBusyRetrieveUrl().contains(QRegExp(QStringLiteral("\\.[xiv]fb$")))) {
        // user specified a fullpath
        // do variable string replacements to the URL (MS Outlook style)
        const QUrl sourceUrl(CalendarSettings::self()->freeBusyRetrieveUrl());
        QUrl fullpathURL = replaceVariablesUrl(sourceUrl, email);

        // set the User and Password part of the URL
        fullpathURL.setUserName(CalendarSettings::self()->freeBusyRetrieveUser());
        fullpathURL.setPassword(CalendarSettings::self()->freeBusyRetrievePassword());

        // no need to cache this URL as this is pretty fast to get from the config value.
        // return the fullpath URL
        qCDebug(AKONADICALENDAR_LOG) << "Found url. email=" << email << "; url=" << fullpathURL;
        emit freeBusyUrlRetrieved(email, fullpathURL);
        return;
    }

    // else we search for a fb file in the specified URL with known possible extensions
    QStringList extensions;
    extensions.reserve(3);
    extensions << QStringLiteral("xfb");
    extensions << QStringLiteral("ifb");
    extensions << QStringLiteral("vfb");

    QStringList::ConstIterator ext;
    QList<QUrl> urlsToCheck;
    urlsToCheck.reserve(extensions.count());
    QStringList::ConstIterator extEnd(extensions.constEnd());
    for (ext = extensions.constBegin(); ext != extEnd; ++ext) {
        // build a url for this extension
        const QUrl sourceUrl = QUrl(CalendarSettings::self()->freeBusyRetrieveUrl());
        QUrl dirURL = replaceVariablesUrl(sourceUrl, email);
        if (CalendarSettings::self()->freeBusyFullDomainRetrieval()) {
            dirURL = dirURL.adjusted(QUrl::StripTrailingSlash);
            dirURL.setPath(QString(dirURL.path() + QLatin1Char('/') + email + QLatin1Char('.') + (*ext)));
        } else {
            // Cut off everything left of the @ sign to get the user name.
            const QString emailName = email.left(emailpos);
            dirURL = dirURL.adjusted(QUrl::StripTrailingSlash);
            dirURL.setPath(QString(dirURL.path() + QLatin1Char('/') + emailName + QLatin1Char('.') + (*ext)));
        }
        dirURL.setUserName(CalendarSettings::self()->freeBusyRetrieveUser());
        dirURL.setPassword(CalendarSettings::self()->freeBusyRetrievePassword());
        urlsToCheck << dirURL;
    }
    KJob *checkerJob = new FbCheckerJob(urlsToCheck, this);
    checkerJob->setProperty("email", email);
    connect(checkerJob, &KJob::result, this, &FreeBusyManagerPrivate::fbCheckerJobFinished);
    checkerJob->start();
}

void FreeBusyManagerPrivate::fbCheckerJobFinished(KJob *job)
{
    const QString email = job->property("email").toString();
    if (!job->error()) {
        FbCheckerJob *checkerJob = static_cast<FbCheckerJob *>(job);
        QUrl dirURL = checkerJob->validUrl();
        // write the URL to the cache
        KConfig cfg(configFile());
        KConfigGroup group = cfg.group(email);
        group.writeEntry("url", dirURL.toDisplayString());   // prettyURL() does not write user nor password
        qCDebug(AKONADICALENDAR_LOG) << "Found url email=" << email << "; url=" << dirURL;
        emit freeBusyUrlRetrieved(email, dirURL);
    } else {
        qCDebug(AKONADICALENDAR_LOG) << "Returning invalid url";
        emit freeBusyUrlRetrieved(email, QUrl());
    }
}

QString FreeBusyManagerPrivate::freeBusyToIcal(const KCalCore::FreeBusy::Ptr &freebusy)
{
    return mFormat.createScheduleMessage(freebusy, KCalCore::iTIPPublish);
}

KCalCore::FreeBusy::Ptr FreeBusyManagerPrivate::iCalToFreeBusy(const QByteArray &freeBusyData)
{
    const QString freeBusyVCal(QString::fromUtf8(freeBusyData));
    KCalCore::FreeBusy::Ptr fb = mFormat.parseFreeBusy(freeBusyVCal);

    if (!fb) {
        qCDebug(AKONADICALENDAR_LOG) << "Error parsing free/busy";
        qCDebug(AKONADICALENDAR_LOG) << freeBusyVCal;
    }

    return fb;
}

KCalCore::FreeBusy::Ptr FreeBusyManagerPrivate::ownerFreeBusy()
{
    QDateTime start = QDateTime::currentDateTimeUtc();
    QDateTime end = start.addDays(CalendarSettings::self()->freeBusyPublishDays());

    KCalCore::Event::List events = mCalendar ? mCalendar->rawEvents(start.date(), end.date()) : KCalCore::Event::List();
    KCalCore::FreeBusy::Ptr freebusy(new KCalCore::FreeBusy(events, start, end));
    freebusy->setOrganizer(KCalCore::Person::Ptr(
                               new KCalCore::Person(Akonadi::CalendarUtils::fullName(),
                                       Akonadi::CalendarUtils::email())));
    return freebusy;
}

QString FreeBusyManagerPrivate::ownerFreeBusyAsString()
{
    return freeBusyToIcal(ownerFreeBusy());
}

void FreeBusyManagerPrivate::processFreeBusyDownloadResult(KJob *_job)
{
    Q_Q(FreeBusyManager);

    FreeBusyDownloadJob *job = qobject_cast<FreeBusyDownloadJob *>(_job);
    Q_ASSERT(job);
    if (job->error()) {
        qCritical() << "Error downloading freebusy" << _job->errorString();
        KMessageBox::sorry(
            mParentWidgetForRetrieval,
            i18n("Failed to download free/busy data from: %1\nReason: %2",
                 job->url().toDisplayString(), job->errorText()),
            i18n("Free/busy retrieval error"));

        // TODO: Ask for a retry? (i.e. queue  the email again when the user wants it).

        // Make sure we don't fill up the map with unneeded data on failures.
        mFreeBusyUrlEmailMap.take(job->url());
    } else {
        KCalCore::FreeBusy::Ptr fb = iCalToFreeBusy(job->rawFreeBusyData());

        Q_ASSERT(mFreeBusyUrlEmailMap.contains(job->url()));
        const QString email = mFreeBusyUrlEmailMap.take(job->url());

        if (fb) {
            KCalCore::Person::Ptr p = fb->organizer();
            p->setEmail(email);
            q->saveFreeBusy(fb, p);
            qCDebug(AKONADICALENDAR_LOG) << "Freebusy retrieved for " << email;
            emit q->freeBusyRetrieved(fb, email);
        } else {
            qCritical() << "Error downloading freebusy, invalid fb.";
            KMessageBox::sorry(
                mParentWidgetForRetrieval,
                i18n("Failed to parse free/busy information that was retrieved from: %1",
                     job->url().toDisplayString()),
                i18n("Free/busy retrieval error"));
        }
    }

    // When downloading failed or finished, start a job for the next one in the
    // queue if needed.
    processRetrieveQueue();
}

void FreeBusyManagerPrivate::processFreeBusyUploadResult(KJob *_job)
{
    KIO::FileCopyJob *job = static_cast<KIO::FileCopyJob *>(_job);
    if (job->error()) {
        KMessageBox::sorry(
            nullptr,
            i18n("<qt><p>The software could not upload your free/busy list to "
                 "the URL '%1'. There might be a problem with the access "
                 "rights, or you specified an incorrect URL. The system said: "
                 "<em>%2</em>.</p>"
                 "<p>Please check the URL or contact your system administrator."
                 "</p></qt>", job->destUrl().toString(),
                 job->errorString()));
    }
    // Delete temp file
    QUrl src = job->srcUrl();
    Q_ASSERT(src.isLocalFile());
    if (src.isLocalFile()) {
        QFile::remove(src.toLocalFile());
    }
    mUploadingFreeBusy = false;
}

void FreeBusyManagerPrivate::processRetrieveQueue()
{
    if (mRetrieveQueue.isEmpty()) {
        return;
    }

    QString email = mRetrieveQueue.takeFirst();

    // First, try to find all agents that are free-busy providers
    QStringList providers = getFreeBusyProviders();
    qCDebug(AKONADICALENDAR_LOG) << "Got the following FreeBusy providers: " << providers;

    // If some free-busy providers were found let's query them first and ask them
    // if they manage the free-busy information for the email address we have.
    if (!providers.isEmpty()) {
        queryFreeBusyProviders(providers, email);
    } else {
        fetchFreeBusyUrl(email);
    }

    return;
}

void FreeBusyManagerPrivate::finishProcessRetrieveQueue(const QString &email,
        const QUrl &freeBusyUrlForEmail)
{
    Q_Q(FreeBusyManager);

    if (!freeBusyUrlForEmail.isValid()) {
        qCDebug(AKONADICALENDAR_LOG) << "Invalid FreeBusy URL" << freeBusyUrlForEmail.toDisplayString() << email;
        return;
    }

    if (mFreeBusyUrlEmailMap.contains(freeBusyUrlForEmail)) {
        qCDebug(AKONADICALENDAR_LOG) << "Download already in progress for " << freeBusyUrlForEmail;
        return;
    }

    mFreeBusyUrlEmailMap.insert(freeBusyUrlForEmail, email);

    FreeBusyDownloadJob *job = new FreeBusyDownloadJob(freeBusyUrlForEmail, mParentWidgetForRetrieval);
    q->connect(job, &FreeBusyDownloadJob::result, this, [this](KJob*job) { processFreeBusyDownloadResult(job);});
    job->start();
}

void FreeBusyManagerPrivate::uploadFreeBusy()
{
    Q_Q(FreeBusyManager);

    // user has automatic uploading disabled, bail out
    if (!CalendarSettings::self()->freeBusyPublishAuto() ||
            CalendarSettings::self()->freeBusyPublishUrl().isEmpty()) {
        return;
    }

    if (mTimerID != 0) {
        // A timer is already running, so we don't need to do anything
        return;
    }

    const QDateTime currentDateTime = QDateTime::currentDateTime();
    int now = static_cast<int>(currentDateTime.toTime_t());
    int eta = static_cast<int>(mNextUploadTime.toTime_t()) - now;

    if (!mUploadingFreeBusy) {
        // Not currently uploading
        if (mNextUploadTime.isNull() || currentDateTime > mNextUploadTime) {
            // No uploading have been done in this session, or delay time is over
            q->publishFreeBusy();
            return;
        }

        // We're in the delay time and no timer is running. Start one
        if (eta <= 0) {
            // Sanity check failed - better do the upload
            q->publishFreeBusy();
            return;
        }
    } else {
        // We are currently uploading the FB list. Start the timer
        if (eta <= 0) {
            qCDebug(AKONADICALENDAR_LOG) << "This shouldn't happen! eta <= 0";
            eta = 10; // whatever
        }
    }

    // Start the timer
    mTimerID = q->startTimer(eta * 1000);

    if (mTimerID == 0) {
        // startTimer failed - better do the upload
        q->publishFreeBusy();
    }
}

QStringList FreeBusyManagerPrivate::getFreeBusyProviders() const
{
    QStringList providers;
    const Akonadi::AgentInstance::List agents = Akonadi::AgentManager::self()->instances();
    for (const Akonadi::AgentInstance &agent : agents) {
        if (agent.type().capabilities().contains(QLatin1String("FreeBusyProvider"))) {
            providers << agent.identifier();
        }
    }
    return providers;
}

void FreeBusyManagerPrivate::queryFreeBusyProviders(const QStringList &providers,
        const QString &email)
{
    if (!mProvidersRequestsByEmail.contains(email)) {
        mProvidersRequestsByEmail[email] = FreeBusyProvidersRequestsQueue();
    }

    for (const QString &provider : providers) {
        FreeBusyProviderRequest request(provider);

        connect(request.mInterface.data(), SIGNAL(handlesFreeBusy(QString,bool)),
                this, SLOT(onHandlesFreeBusy(QString,bool)));

        request.mInterface->call(QStringLiteral("canHandleFreeBusy"), email);
        request.mRequestStatus = FreeBusyProviderRequest::HandlingRequested;
        mProvidersRequestsByEmail[email].mRequests << request;
    }
}

void FreeBusyManagerPrivate::queryFreeBusyProviders(const QStringList &providers,
        const QString &email,
        const QDateTime &start,
        const QDateTime &end)
{
    if (!mProvidersRequestsByEmail.contains(email)) {
        mProvidersRequestsByEmail[email] = FreeBusyProvidersRequestsQueue(start, end);
    }

    queryFreeBusyProviders(providers, email);
}

void FreeBusyManagerPrivate::onHandlesFreeBusy(const QString &email, bool handles)
{
    if (!mProvidersRequestsByEmail.contains(email)) {
        return;
    }

    QDBusInterface *iface = dynamic_cast<QDBusInterface *>(sender());
    if (!iface) {
        return;
    }

    FreeBusyProvidersRequestsQueue *queue = &mProvidersRequestsByEmail[email];
    QString respondingService = iface->service();
    qCDebug(AKONADICALENDAR_LOG) << respondingService << "responded to our FreeBusy request:" << handles;
    int requestIndex = -1;

    const int requestsSize(queue->mRequests.size());
    for (int i = 0; i < requestsSize; ++i) {
        if (queue->mRequests.at(i).mInterface->service() == respondingService) {
            requestIndex = i;
        }
    }

    if (requestIndex == -1) {
        return;
    }

    disconnect(iface, SIGNAL(handlesFreeBusy(QString,bool)),
               this, SLOT(onHandlesFreeBusy(QString,bool)));

    if (!handles) {
        queue->mRequests.removeAt(requestIndex);
        // If no more requests are left and no handler responded
        // then fall back to the URL mechanism
        if (queue->mRequests.isEmpty() && queue->mHandlersCount == 0) {
            mProvidersRequestsByEmail.remove(email);
            fetchFreeBusyUrl(email);
        }
    } else {
        ++queue->mHandlersCount;
        connect(iface, SIGNAL(freeBusyRetrieved(QString,QString,bool,QString)),
                this, SLOT(onFreeBusyRetrieved(QString,QString,bool,QString)));
        iface->call(QStringLiteral("retrieveFreeBusy"), email, queue->mStartTime, queue->mEndTime);
        queue->mRequests[requestIndex].mRequestStatus = FreeBusyProviderRequest::FreeBusyRequested;
    }
}

void FreeBusyManagerPrivate::processMailSchedulerResult(Akonadi::Scheduler::Result result,
        const QString &errorMsg)
{
    if (result == Scheduler::ResultSuccess) {
        KMessageBox::information(
            mParentWidgetForMailling,
            i18n("The free/busy information was successfully sent."),
            i18n("Sending Free/Busy"),
            QStringLiteral("FreeBusyPublishSuccess"));
    } else {
        KMessageBox::error(mParentWidgetForMailling,
                           i18n("Unable to publish the free/busy data: %1", errorMsg));
    }

    sender()->deleteLater();
}

void FreeBusyManagerPrivate::onFreeBusyRetrieved(const QString &email,
        const QString &freeBusy,
        bool success,
        const QString &errorText)
{
    Q_Q(FreeBusyManager);
    Q_UNUSED(errorText);

    if (!mProvidersRequestsByEmail.contains(email)) {
        return;
    }

    QDBusInterface *iface = dynamic_cast<QDBusInterface *>(sender());
    if (!iface) {
        return;
    }

    FreeBusyProvidersRequestsQueue *queue = &mProvidersRequestsByEmail[email];
    QString respondingService = iface->service();
    int requestIndex = -1;

    const int requestsSize(queue->mRequests.size());
    for (int i = 0; i < requestsSize; ++i) {
        if (queue->mRequests.at(i).mInterface->service() == respondingService) {
            requestIndex = i;
        }
    }

    if (requestIndex == -1) {
        return;
    }

    disconnect(iface, SIGNAL(freeBusyRetrieved(QString,QString,bool,QString)),
               this, SLOT(onFreeBusyRetrieved(QString,QString,bool,QString)));

    queue->mRequests.removeAt(requestIndex);

    if (success) {
        KCalCore::FreeBusy::Ptr fb = iCalToFreeBusy(freeBusy.toUtf8());
        if (!fb) {
            --queue->mHandlersCount;
        } else {
            queue->mResultingFreeBusy->merge(fb);
        }
    }

    if (queue->mRequests.isEmpty()) {
        if (queue->mHandlersCount == 0) {
            fetchFreeBusyUrl(email);
        } else {
            emit q->freeBusyRetrieved(queue->mResultingFreeBusy, email);
        }
        mProvidersRequestsByEmail.remove(email);
    }
}

/// FreeBusyManager::Singleton

namespace Akonadi
{

class FreeBusyManagerStatic
{
public:
    FreeBusyManager instance;
};

}

Q_GLOBAL_STATIC(FreeBusyManagerStatic, sManagerInstance)

FreeBusyManager::FreeBusyManager()
    : d_ptr(new FreeBusyManagerPrivate(this))
{
    setObjectName(QStringLiteral("FreeBusyManager"));
    connect(CalendarSettings::self(), SIGNAL(configChanged()), SLOT(checkFreeBusyUrl()));
}

FreeBusyManager::~FreeBusyManager()
{
    delete d_ptr;
}

FreeBusyManager *FreeBusyManager::self()
{
    return &sManagerInstance->instance;
}

void FreeBusyManager::setCalendar(const Akonadi::ETMCalendar::Ptr &c)
{
    Q_D(FreeBusyManager);

    if (d->mCalendar) {
        disconnect(d->mCalendar.data(), SIGNAL(calendarChanged()));
    }

    d->mCalendar = c;
    if (d->mCalendar) {
        d->mFormat.setTimeZone(d->mCalendar->timeZone());
        connect(d->mCalendar.data(), SIGNAL(calendarChanged()), SLOT(uploadFreeBusy()));
    }

    // Lets see if we need to update our published
    QTimer::singleShot(0, this, SLOT(uploadFreeBusy()));
}

/*!
  This method is called when the user has selected to publish its
  free/busy list or when the delay have passed.
*/
void FreeBusyManager::publishFreeBusy(QWidget *parentWidget)
{
    Q_D(FreeBusyManager);
    // Already uploading? Skip this one then.
    if (d->mUploadingFreeBusy) {
        return;
    }

    // No calendar set yet? Don't upload to prevent losing published information that
    // might still be valid.
    if (!d->mCalendar) {
        return;
    }

    QUrl targetURL(CalendarSettings::self()->freeBusyPublishUrl());
    if (targetURL.isEmpty())  {
        KMessageBox::sorry(
            parentWidget,
            i18n("<qt><p>No URL configured for uploading your free/busy list. "
                 "Please set it in KOrganizer's configuration dialog, on the "
                 "\"Free/Busy\" page.</p>"
                 "<p>Contact your system administrator for the exact URL and the "
                 "account details.</p></qt>"),
            i18n("No Free/Busy Upload URL"));
        return;
    }

    if (d->mBrokenUrl) {
        // Url is invalid, don't try again
        return;
    }
    if (!targetURL.isValid()) {
        KMessageBox::sorry(
            parentWidget,
            i18n("<qt>The target URL '%1' provided is invalid.</qt>", targetURL.toDisplayString()),
            i18n("Invalid URL"));
        d->mBrokenUrl = true;
        return;
    }
    targetURL.setUserName(CalendarSettings::self()->freeBusyPublishUser());
    targetURL.setPassword(CalendarSettings::self()->freeBusyPublishPassword());

    d->mUploadingFreeBusy = true;

    // If we have a timer running, it should be stopped now
    if (d->mTimerID != 0) {
        killTimer(d->mTimerID);
        d->mTimerID = 0;
    }

    // Save the time of the next free/busy uploading
    d->mNextUploadTime = QDateTime::currentDateTime();
    if (CalendarSettings::self()->freeBusyPublishDelay() > 0) {
        d->mNextUploadTime =
            d->mNextUploadTime.addSecs(CalendarSettings::self()->freeBusyPublishDelay() * 60);
    }

    QString messageText = d->ownerFreeBusyAsString();

    // We need to massage the list a bit so that Outlook understands
    // it.
    messageText = messageText.replace(QRegExp(QStringLiteral("ORGANIZER\\s*:MAILTO:")),
                                      QStringLiteral("ORGANIZER:"));

    // Create a local temp file and save the message to it
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    if (tempFile.open()) {
        QTextStream textStream(&tempFile);
        textStream << messageText;
        textStream.flush();

#if 0
        QString defaultEmail = KOCore()
                               ::self()->email();
        QString emailHost = defaultEmail.mid(defaultEmail.indexOf('@') + 1);

        // Put target string together
        QUrl targetURL;
        if (CalendarSettings::self()->publishKolab()) {
            // we use Kolab
            QString server;
            if (CalendarSettings::self()->publishKolabServer() == QLatin1String("%SERVER%") ||
                    CalendarSettings::self()->publishKolabServer().isEmpty()) {
                server = emailHost;
            } else {
                server = CalendarSettings::self()->publishKolabServer();
            }

            targetURL.setScheme("webdavs");
            targetURL.setHost(server);

            QString fbname = CalendarSettings::self()->publishUserName();
            int at = fbname.indexOf('@');
            if (at > 1 && fbname.length() > (uint)at) {
                fbname = fbname.left(at);
            }
            targetURL.setPath("/freebusy/" + fbname + ".ifb");
            targetURL.setUserName(CalendarSettings::self()->publishUserName());
            targetURL.setPassword(CalendarSettings::self()->publishPassword());
        } else {
            // we use something else
            targetURL = CalendarSettings::self()-> +publishAnyURL().replace("%SERVER%", emailHost);
            targetURL.setUserName(CalendarSettings::self()->publishUserName());
            targetURL.setPassword(CalendarSettings::self()->publishPassword());
        }
#endif

        QUrl src;
        src.setPath(tempFile.fileName());

        qCDebug(AKONADICALENDAR_LOG) << targetURL;

        KIO::Job *job = KIO::file_copy(src, targetURL, -1, KIO::Overwrite | KIO::HideProgressInfo);

        KJobWidgets::setWindow(job, parentWidget);

        //FIXME slot doesn't exist
        //connect(job, SIGNAL(result(KJob*)), SLOT(slotUploadFreeBusyResult(KJob*)));
    }
}

void FreeBusyManager::mailFreeBusy(int daysToPublish, QWidget *parentWidget)
{
    Q_D(FreeBusyManager);
    // No calendar set yet?
    if (!d->mCalendar) {
        return;
    }

    QDateTime start = QDateTime::currentDateTimeUtc().toTimeZone(d->mCalendar->timeZone());
    QDateTime end = start.addDays(daysToPublish);

    KCalCore::Event::List events = d->mCalendar->rawEvents(start.date(), end.date());

    FreeBusy::Ptr freebusy(new FreeBusy(events, start, end));
    freebusy->setOrganizer(Person::Ptr(
                               new Person(Akonadi::CalendarUtils::fullName(),
                                          Akonadi::CalendarUtils::email())));

    QPointer<PublishDialog> publishdlg = new PublishDialog();
    if (publishdlg->exec() == QDialog::Accepted) {
        // Send the mail
        MailScheduler *scheduler = new MailScheduler(/*factory=*/nullptr, this);
        connect(scheduler, &Scheduler::transactionFinished
                , d, &FreeBusyManagerPrivate::processMailSchedulerResult);
        d->mParentWidgetForMailling = parentWidget;

        scheduler->publish(freebusy, publishdlg->addresses());
    }
    delete publishdlg;
}

bool FreeBusyManager::retrieveFreeBusy(const QString &email, bool forceDownload,
                                       QWidget *parentWidget)
{
    Q_D(FreeBusyManager);

    qCDebug(AKONADICALENDAR_LOG) << email;
    if (email.isEmpty()) {
        qCDebug(AKONADICALENDAR_LOG) << "Email is empty";
        return false;
    }

    d->mParentWidgetForRetrieval = parentWidget;

    if (Akonadi::CalendarUtils::thatIsMe(email)) {
        // Don't download our own free-busy list from the net
        qCDebug(AKONADICALENDAR_LOG) << "freebusy of owner, not downloading";
        emit freeBusyRetrieved(d->ownerFreeBusy(), email);
        return true;
    }

    // Check for cached copy of free/busy list
    KCalCore::FreeBusy::Ptr fb = loadFreeBusy(email);
    if (fb) {
        qCDebug(AKONADICALENDAR_LOG) << "Found a cached copy for " << email;
        emit freeBusyRetrieved(fb, email);
        return true;
    }

    // Don't download free/busy if the user does not want it.
    if (!CalendarSettings::self()->freeBusyRetrieveAuto() && !forceDownload) {
        qCDebug(AKONADICALENDAR_LOG) << "Not downloading freebusy";
        return false;
    }

    d->mRetrieveQueue.append(email);

    if (d->mRetrieveQueue.count() > 1) {
        // TODO: true should always emit
        qCWarning(AKONADICALENDAR_LOG) << "Returning true without emit, is this correct?";
        return true;
    }

    // queued, because "true" means the download was initiated. So lets
    // return before starting stuff
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
    QMetaObject::invokeMethod(d, [this, d] { d->processRetrieveQueue(); }, Qt::QueuedConnection);
#else
    QMetaObject::invokeMethod(d, "processRetrieveQueue", Qt::QueuedConnection);
#endif

    return true;
}

void FreeBusyManager::cancelRetrieval()
{
    Q_D(FreeBusyManager);
    d->mRetrieveQueue.clear();
}

KCalCore::FreeBusy::Ptr FreeBusyManager::loadFreeBusy(const QString &email)
{
    Q_D(FreeBusyManager);
    const QString fbd = d->freeBusyDir();

    QFile f(fbd + QLatin1Char('/') + email + QStringLiteral(".ifb"));
    if (!f.exists()) {
        qCDebug(AKONADICALENDAR_LOG) << f.fileName() << "doesn't exist.";
        return KCalCore::FreeBusy::Ptr();
    }

    if (!f.open(QIODevice::ReadOnly)) {
        qCDebug(AKONADICALENDAR_LOG) << "Unable to open file" << f.fileName();
        return KCalCore::FreeBusy::Ptr();
    }

    QTextStream ts(&f);
    QString str = ts.readAll();

    return d->iCalToFreeBusy(str.toUtf8());
}

bool FreeBusyManager::saveFreeBusy(const KCalCore::FreeBusy::Ptr &freebusy,
                                   const KCalCore::Person::Ptr &person)
{
    Q_D(FreeBusyManager);
    Q_ASSERT(person);
    qCDebug(AKONADICALENDAR_LOG) << person->fullName();

    QString fbd = d->freeBusyDir();

    QDir freeBusyDirectory(fbd);
    if (!freeBusyDirectory.exists()) {
        qCDebug(AKONADICALENDAR_LOG) << "Directory" << fbd << " does not exist!";
        qCDebug(AKONADICALENDAR_LOG) << "Creating directory:" << fbd;

        if (!freeBusyDirectory.mkpath(fbd)) {
            qCDebug(AKONADICALENDAR_LOG) << "Could not create directory:" << fbd;
            return false;
        }
    }

    QString filename(fbd);
    filename += QLatin1Char('/');
    filename += person->email();
    filename += QStringLiteral(".ifb");
    QFile f(filename);

    qCDebug(AKONADICALENDAR_LOG) << "filename:" << filename;

    freebusy->clearAttendees();
    freebusy->setOrganizer(person);

    QString messageText = d->mFormat.createScheduleMessage(freebusy, KCalCore::iTIPPublish);

    if (!f.open(QIODevice::ReadWrite)) {
        qCDebug(AKONADICALENDAR_LOG) << "acceptFreeBusy: Can't open:" << filename << "for writing";
        return false;
    }
    QTextStream t(&f);
    t << messageText;
    f.close();

    return true;
}

void FreeBusyManager::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event)
    publishFreeBusy();
}

#include "moc_freebusymanager.cpp"
#include "moc_freebusymanager_p.cpp"