calendarmigrator.cpp 26.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 *  calendarmigrator.cpp  -  migrates or creates KAlarm Akonadi resources
 *  Program:  kalarm
 *  Copyright © 2011 by David Jarvie <djarvie@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "calendarmigrator.h"
22
#include "akonadimodel.h"
23
24
25
#include "kalarmsettings.h"
#include "kalarmdirsettings.h"
#include "collectionattribute.h"
26
27
#include "compatibilityattribute.h"
#include "version.h"
28
29
30
31
32
33
34

#include <akonadi/agentinstancecreatejob.h>
#include <akonadi/agentmanager.h>
#include <akonadi/collectionfetchjob.h>
#include <akonadi/collectionfetchscope.h>
#include <akonadi/collectionmodifyjob.h>
#include <akonadi/entitydisplayattribute.h>
35
#include <akonadi/resourcesynchronizationjob.h>
36
37
38
39
40
41
42

#include <klocale.h>
#include <kconfiggroup.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kdebug.h>

43
44
#include <QTimer>

45
using namespace Akonadi;
46
47
using KAlarm::CollectionAttribute;
using KAlarm::CompatibilityAttribute;
48
49


50
// Creates, or migrates from KResources, a single alarm calendar
51
52
53
54
55
class CalendarCreator : public QObject
{
        Q_OBJECT
    public:
        CalendarCreator(const QString& resourceType, const KConfigGroup&);
56
        CalendarCreator(KAlarm::CalEvent::Type, const QString& file, const QString& name);
57
58
59
60
61
        bool    isValid() const        { return mAlarmType != KAlarm::CalEvent::EMPTY; }
        bool    newCalendar() const    { return mNew; }
        QString resourceName() const   { return mName; }
        QString path() const           { return mPath; }
        QString errorMessage() const   { return mErrorMessage; }
62
        void    createAgent(const QString& agentType, QObject* parent);
63
64
65
66
67

    public slots:
        void agentCreated(KJob*);

    signals:
68
        void creating(const QString& path);
69
70
71
        void finished(CalendarCreator*);

    private slots:
72
        void fetchCollection();
73
        void collectionFetchResult(KJob*);
74
        void resourceSynchronised(KJob*);
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        void modifyCollectionJobDone(KJob*);

    private:
        void finish(bool cleanup);
        bool migrateLocalFile();
        bool migrateLocalDirectory();
        bool migrateRemoteFile();
        template <class Interface> Interface* migrateBasic();

        enum ResourceType { LocalFile, LocalDir, RemoteFile };

        Akonadi::AgentInstance mAgent;
        KAlarm::CalEvent::Type mAlarmType;
        ResourceType           mResourceType;
        QString                mPath;
        QString                mName;
        QColor                 mColour;
        QString                mErrorMessage;
93
        int                    mCollectionFetchRetryCount;
94
95
96
97
98
99
100
        bool                   mReadOnly;
        bool                   mEnabled;
        bool                   mStandard;
        const bool             mNew;
        bool                   mFinished;
};

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Updates the backend calendar format of a single alarm calendar
class CalendarUpdater : public QObject
{
        Q_OBJECT
    public:
        CalendarUpdater(const Collection& collection, bool dirResource,
                        bool ignoreKeepFormat, bool newCollection, QObject* parent);

    public slots:
        bool update();

    private:
        Akonadi::Collection mCollection;
        QObject*            mParent;
        bool                mDirResource;
        bool                mIgnoreKeepFormat;
        bool                mNewCollection;
};


CalendarMigrator* CalendarMigrator::mInstance = 0;
122
123
124
125
126
127

CalendarMigrator::CalendarMigrator(QObject* parent)
    : QObject(parent)
{
}

128
129
130
131
132
CalendarMigrator::~CalendarMigrator()
{
    kDebug();
}

133
134
135
136
137
138
139
140
141
142
/******************************************************************************
* Create and return the unique CalendarMigrator instance.
*/
CalendarMigrator* CalendarMigrator::instance()
{
    if (!mInstance)
        mInstance = new CalendarMigrator;
    return mInstance;
}

143
144
145
146
147
/******************************************************************************
* Migrate old KResource calendars, or if none, create default Akonadi resources.
*/
void CalendarMigrator::execute()
{
148
    instance()->migrateOrCreate();
149
150
151
152
153
154
155
156
157
158
159
160
161
162
}

/******************************************************************************
* Migrate old KResource calendars, or if none, create default Akonadi resources.
*/
void CalendarMigrator::migrateOrCreate()
{
    kDebug();
    CalendarCreator* creator;

    // First migrate any KResources alarm calendars from pre-Akonadi versions of KAlarm.
    bool haveResources = false;
    const QString configFile = KStandardDirs::locateLocal("config", QLatin1String("kresources/alarms/stdrc"));
    KConfig config(configFile, KConfig::SimpleConfig);
163
164
165
166
167
168
169
170

    // Fetch all the resource identifiers which are actually in use
    KConfigGroup group = config.group("General");
    QStringList keys = group.readEntry("ResourceKeys", QStringList())
                     + group.readEntry("PassiveResourceKeys", QStringList());

    // Create an Akonadi resource for each resource id
    foreach (const QString& id, keys)
171
    {
172
        KConfigGroup configGroup = config.group(QLatin1String("Resource_") + id);
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        QString resourceType = configGroup.readEntry("ResourceType", QString());
        QString agentType;
        if (resourceType == QLatin1String("file"))
            agentType = QLatin1String("akonadi_kalarm_resource");
        else if (resourceType == QLatin1String("dir"))
            agentType = QLatin1String("akonadi_kalarm_dir_resource");
        else if (resourceType == QLatin1String("remote"))
            agentType = QLatin1String("akonadi_kalarm_resource");
        else
            continue;   // unknown resource type - can't convert

        haveResources = true;
        creator = new CalendarCreator(resourceType, configGroup);
        if (!creator->isValid())
            delete creator;
        else
        {
            connect(creator, SIGNAL(finished(CalendarCreator*)), SLOT(calendarCreated(CalendarCreator*)));
Laurent Montel's avatar
Laurent Montel committed
191
            connect(creator, SIGNAL(creating(QString)), SLOT(creatingCalendar(QString)));
192
            mCalendarsPending << creator;
193
            creator->createAgent(agentType, this);
194
195
196
197
198
        }
    }

    if (!haveResources)
    {
199
        // There were no KResources calendars to migrate, so create default ones.
200
        // Normally this occurs on first installation of KAlarm.
201
202
        // If the default files already exist, they will be used; otherwise they
        // will be created.
203
204
        creator = new CalendarCreator(KAlarm::CalEvent::ACTIVE, QLatin1String("calendar.ics"), i18nc("@info/plain", "Active Alarms"));
        connect(creator, SIGNAL(finished(CalendarCreator*)), SLOT(calendarCreated(CalendarCreator*)));
Laurent Montel's avatar
Laurent Montel committed
205
        connect(creator, SIGNAL(creating(QString)), SLOT(creatingCalendar(QString)));
206
        mCalendarsPending << creator;
207
        creator->createAgent(QLatin1String("akonadi_kalarm_resource"), this);
208
209
210

        creator = new CalendarCreator(KAlarm::CalEvent::ARCHIVED, QLatin1String("expired.ics"), i18nc("@info/plain", "Archived Alarms"));
        connect(creator, SIGNAL(finished(CalendarCreator*)), SLOT(calendarCreated(CalendarCreator*)));
Laurent Montel's avatar
Laurent Montel committed
211
        connect(creator, SIGNAL(creating(QString)), SLOT(creatingCalendar(QString)));
212
        mCalendarsPending << creator;
213
        creator->createAgent(QLatin1String("akonadi_kalarm_resource"), this);
214
215
216

        creator = new CalendarCreator(KAlarm::CalEvent::TEMPLATE, QLatin1String("template.ics"), i18nc("@info/plain", "Alarm Templates"));
        connect(creator, SIGNAL(finished(CalendarCreator*)), SLOT(calendarCreated(CalendarCreator*)));
Laurent Montel's avatar
Laurent Montel committed
217
        connect(creator, SIGNAL(creating(QString)), SLOT(creatingCalendar(QString)));
218
        mCalendarsPending << creator;
219
        creator->createAgent(QLatin1String("akonadi_kalarm_resource"), this);
220
221
222
223
224
225
    }

    if (mCalendarsPending.isEmpty())
        deleteLater();
}

226
227
228
229
/******************************************************************************
* Called when a calendar resource is about to be created.
* Emits the 'creating' signal.
*/
230
void CalendarMigrator::creatingCalendar(const QString& path)
231
{
232
    emit creating(path, false);
233
234
}

235
236
237
238
239
240
241
242
243
244
/******************************************************************************
* Called when creation of a migrated or new default calendar resource has
* completed or failed.
*/
void CalendarMigrator::calendarCreated(CalendarCreator* creator)
{
    int i = mCalendarsPending.indexOf(creator);
    if (i < 0)
        return;    // calendar already finished

245
246
    emit creating(creator->path(), true);

247
248
249
250
    if (!creator->errorMessage().isEmpty())
    {
        QString errmsg = creator->newCalendar()
                       ? i18nc("@info/plain", "Failed to create default calendar <resource>%1</resource>", creator->resourceName())
251
252
253
                       : i18nc("@info/plain 'Import Alarms' is the name of a menu option",
                               "Failed to convert old configuration for calendar <resource>%1</resource>. "
                               "Please use Import Alarms to load its alarms into a new or existing calendar.", creator->resourceName());
254
        QString locn = i18nc("@info/plain File path or URL", "Location: %1", creator->path());
255
256
257
258
259
        if (creator->errorMessage().isEmpty())
            errmsg = i18nc("@info", "<para>%1</para><para>%2</para>", errmsg, locn);
        else
            errmsg = i18nc("@info", "<para>%1</para><para>%2<nl/>(%3)</para>", errmsg, locn, creator->errorMessage());
        KMessageBox::error(0, errmsg);
260
261
262
    }
    creator->deleteLater();

263
    mCalendarsPending.removeAt(i);    // remove it from the pending list
264
265
266
267
    if (mCalendarsPending.isEmpty())
        deleteLater();
}

268
269
270
271
272
273
274
275
276
277
/******************************************************************************
* If an existing Akonadi resource calendar can be converted to the current
* KAlarm format, prompt the user whether to convert it, and if yes, tell the
* Akonadi resource to update the backend storage to the current format.
* The CollectionAttribute's KeepFormat property will be updated if the user
* chooses not to update the calendar.
*
* Note: the collection should be up to date: use AkonadiModel::refresh() before
*       calling this function.
*/
278
void CalendarMigrator::updateToCurrentFormat(const Collection& collection, bool ignoreKeepFormat, QWidget* parent)
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
{
    kDebug() << collection.id();
    AgentInstance agent = AgentManager::self()->instance(collection.resource());
    const QString id = agent.type().identifier();
    bool dirResource;
    if (id == QLatin1String("akonadi_kalarm_resource"))
        dirResource = false;
    else if (id == QLatin1String("akonadi_kalarm_dir_resource"))
        dirResource = true;
    else
    {
        kError() << "Invalid agent type" << id;
        return;
    }
    CalendarUpdater* updater = new CalendarUpdater(collection, dirResource, ignoreKeepFormat, false, parent);
    QTimer::singleShot(0, updater, SLOT(update()));
}


CalendarUpdater::CalendarUpdater(const Collection& collection, bool dirResource,
                                 bool ignoreKeepFormat, bool newCollection, QObject* parent)
    : mCollection(collection),
      mParent(parent),
      mDirResource(dirResource),
      mIgnoreKeepFormat(ignoreKeepFormat),
      mNewCollection(newCollection)
{
}

bool CalendarUpdater::update()
{
    kDebug() << mCollection.id() << (mDirResource ? "directory" : "file");
    bool result = true;
    if (mCollection.hasAttribute<CompatibilityAttribute>())
    {
        const CompatibilityAttribute* compatAttr = mCollection.attribute<CompatibilityAttribute>();
        KAlarm::Calendar::Compat compatibility = compatAttr->compatibility();
        if ((compatibility & ~KAlarm::Calendar::Converted)
        // The calendar isn't in the current KAlarm format
        &&  !(compatibility & ~(KAlarm::Calendar::Convertible | KAlarm::Calendar::Converted))
        // The calendar format is convertible to the current KAlarm format
        &&  (mIgnoreKeepFormat
            || !mCollection.hasAttribute<CollectionAttribute>()
            || !mCollection.attribute<CollectionAttribute>()->keepFormat()))
        {
            // The user hasn't previously said not to convert it
            QString versionString = KAlarm::getVersionString(compatAttr->version());
            QString msg = KAlarm::Calendar::conversionPrompt(mCollection.name(), versionString, false);
327
            kDebug() << "Version" << versionString;
328
            if (KMessageBox::warningYesNo(qobject_cast<QWidget*>(mParent), msg) == KMessageBox::Yes)
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
            {
                // Tell the resource to update the backend storage format
                QString errmsg;
                if (!mNewCollection)
                {
                    // Refetch the collection's details because anything could
                    // have happened since the prompt was first displayed.
                    if (!AkonadiModel::instance()->refresh(mCollection))
                        errmsg = i18nc("@info/plain", "Invalid collection");
                }
                if (errmsg.isEmpty())
                {
                    AgentInstance agent = AgentManager::self()->instance(mCollection.resource());
                    if (mDirResource)
                        CalendarMigrator::updateStorageFormat<OrgKdeAkonadiKAlarmDirSettingsInterface>(agent, errmsg, mParent);
                    else
                        CalendarMigrator::updateStorageFormat<OrgKdeAkonadiKAlarmSettingsInterface>(agent, errmsg, mParent);
                }
                if (!errmsg.isEmpty())
                {
                    KMessageBox::error(0, i18nc("@info", "%1<nl/>(%2)",
                                                i18nc("@info/plain", "Failed to update format of calendar <resource>%1</resource>", mCollection.name()),
                                                errmsg));
                }
            }
            else
            {
                // The user chose not to update the calendar
                result = false;
                if (!mNewCollection)
                {
                    QModelIndex ix = AkonadiModel::instance()->collectionIndex(mCollection);
                    AkonadiModel::instance()->setData(ix, true, AkonadiModel::KeepFormatRole);
                }
            }
        }
    }
    deleteLater();
    return result;
}

/******************************************************************************
* Tell an Akonadi resource to update the backend storage format to the current
* KAlarm format.
* Reply = true if success; if false, 'errorMessage' contains the error message.
*/
template <class Interface> bool CalendarMigrator::updateStorageFormat(const AgentInstance& agent, QString& errorMessage, QObject* parent)
{
    kDebug();
    Interface* iface = getAgentInterface<Interface>(agent, errorMessage, parent);
    if (!iface)
    {
        kDebug() << errorMessage;
        return false;
    }
    iface->setUpdateStorageFormat(true);
    iface->writeConfig();
    delete iface;
    kDebug() << "true";
    return true;
}

/******************************************************************************
* Create a D-Bus interface to an Akonadi resource.
* Reply = interface if success
*       = 0 if error: 'errorMessage' contains the error message.
*/
template <class Interface> Interface* CalendarMigrator::getAgentInterface(const AgentInstance& agent, QString& errorMessage, QObject* parent)
{
    Interface* iface = new Interface("org.freedesktop.Akonadi.Resource." + agent.identifier(),
              "/Settings", QDBusConnection::sessionBus(), parent);
    if (!iface->isValid())
    {
        errorMessage = iface->lastError().message();
        kDebug() << "D-Bus error accessing resource:" << errorMessage;
        delete iface;
        return 0;
    }
    return iface;
}

410

411
412
413
/******************************************************************************
* Constructor to migrate a KResources calendar, using its parameters.
*/
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
CalendarCreator::CalendarCreator(const QString& resourceType, const KConfigGroup& config)
    : mAlarmType(KAlarm::CalEvent::EMPTY),
      mNew(false),
      mFinished(false)
{
    // Read the resource configuration parameters from the config
    const char* pathKey = 0;
    if (resourceType == QLatin1String("file"))
    {
        mResourceType = LocalFile;
        pathKey = "CalendarURL";
    }
    else if (resourceType == QLatin1String("dir"))
    {
        mResourceType = LocalDir;
        pathKey = "CalendarURL";
    }
    else if (resourceType == QLatin1String("remote"))
    {
        mResourceType = RemoteFile;
        pathKey = "DownloadUrl";
    }
    else
    {
        kError() << "Invalid resource type:" << resourceType;
        return;
    }
    mPath = config.readPathEntry(pathKey, "");
    switch (config.readEntry("AlarmType", (int)0))
    {
        case 1:  mAlarmType = KAlarm::CalEvent::ACTIVE;  break;
        case 2:  mAlarmType = KAlarm::CalEvent::ARCHIVED;  break;
        case 4:  mAlarmType = KAlarm::CalEvent::TEMPLATE;  break;
        default:
            kError() << "Invalid alarm type for resource";
            return;
    }
    mName     = config.readEntry("ResourceName", QString());
    mColour   = config.readEntry("Color", QColor());
    mReadOnly = config.readEntry("ResourceIsReadOnly", true);
    mEnabled  = config.readEntry("ResourceIsActive", false);
    mStandard = config.readEntry("Standard", false);
    kDebug() << "Migrating:" << mName << ", type=" << mAlarmType << ", path=" << mPath;
}

/******************************************************************************
* Constructor to create a new default local file resource.
* This is created as enabled, read-write, and standard for its alarm type.
*/
463
CalendarCreator::CalendarCreator(KAlarm::CalEvent::Type alarmType, const QString& file, const QString& name)
464
465
466
467
468
469
470
471
472
473
    : mAlarmType(alarmType),
      mResourceType(LocalFile),
      mName(name),
      mColour(),
      mReadOnly(false),
      mEnabled(true),
      mStandard(true),
      mNew(true),
      mFinished(false)
{
474
    mPath = KStandardDirs::locateLocal("appdata", file);
475
    kDebug() << "New:" << mName << ", type=" << mAlarmType << ", path=" << mPath;
476
477
}

478
479
480
481
482
483
484
485
486
487
488
/******************************************************************************
* Create the Akonadi agent for this calendar.
*/
void CalendarCreator::createAgent(const QString& agentType, QObject* parent)
{
    emit creating(mPath);
    AgentInstanceCreateJob* job = new AgentInstanceCreateJob(agentType, parent);
    connect(job, SIGNAL(result(KJob*)), SLOT(agentCreated(KJob*)));
    job->start();
}

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
/******************************************************************************
* Called when the agent creation job for this resource has completed.
* Applies the calendar resource configuration to the Akonadi agent.
*/
void CalendarCreator::agentCreated(KJob* j)
{
    if (j->error())
    {
        mErrorMessage = j->errorString();
        kError() << "AgentInstanceCreateJob error:" << mErrorMessage;
        finish(false);
        return;
    }

    // Configure the Akonadi Agent
    kDebug() << mName;
    AgentInstanceCreateJob* job = static_cast<AgentInstanceCreateJob*>(j);
    mAgent = job->instance();
    mAgent.setName(mName);
    bool ok = false;
    switch (mResourceType)
    {
        case LocalFile:
            ok = migrateLocalFile();
            break;
        case LocalDir:
            ok = migrateLocalDirectory();
            break;
        case RemoteFile:
            ok = migrateRemoteFile();
            break;
        default:
            kError() << "Invalid resource type";
            break;
    }
    if (!ok)
    {
        finish(true);
        return;
    }
    mAgent.reconfigure();   // notify the agent that its configuration has been changed

531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
    // Wait for the resource to create its collection.
    ResourceSynchronizationJob* sjob = new ResourceSynchronizationJob(mAgent);
    connect(sjob, SIGNAL(result(KJob*)), SLOT(resourceSynchronised(KJob*)));
    sjob->start();   // this is required (not an Akonadi::Job)
}

/******************************************************************************
* Called when a resource synchronisation job has completed.
* Fetches the collection which this agent manages.
*/
void CalendarCreator::resourceSynchronised(KJob* j)
{
    kDebug() << mName;
    if (j->error())
    {
        // Don't give up on error - we can still try to fetch the collection
        kError() << "ResourceSynchronizationJob error: " << j->errorString();
    }
    mCollectionFetchRetryCount = 0;
    fetchCollection();
551
552
553
554
555
556
557
}

/******************************************************************************
* Find the collection which this agent manages.
*/
void CalendarCreator::fetchCollection()
{
558
559
560
561
    CollectionFetchJob* job = new CollectionFetchJob(Collection::root(), CollectionFetchJob::FirstLevel);
    job->fetchScope().setResource(mAgent.identifier());
    connect(job, SIGNAL(result(KJob*)), SLOT(collectionFetchResult(KJob*)));
    job->start();
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
}

bool CalendarCreator::migrateLocalFile()
{
    OrgKdeAkonadiKAlarmSettingsInterface* iface = migrateBasic<OrgKdeAkonadiKAlarmSettingsInterface>();
    if (!iface)
        return false;
    iface->setMonitorFile(true);
    iface->writeConfig();   // save the Agent config changes
    delete iface;
    return true;
}

bool CalendarCreator::migrateLocalDirectory()
{
    OrgKdeAkonadiKAlarmDirSettingsInterface* iface = migrateBasic<OrgKdeAkonadiKAlarmDirSettingsInterface>();
    if (!iface)
        return false;
    iface->setMonitorFiles(true);
    iface->writeConfig();   // save the Agent config changes
    delete iface;
    return true;
}

bool CalendarCreator::migrateRemoteFile()
{
    OrgKdeAkonadiKAlarmSettingsInterface* iface = migrateBasic<OrgKdeAkonadiKAlarmSettingsInterface>();
    if (!iface)
        return false;
    iface->setMonitorFile(true);
    iface->writeConfig();   // save the Agent config changes
    delete iface;
    return true;
}

template <class Interface> Interface* CalendarCreator::migrateBasic()
{
599
600
    Interface* iface = CalendarMigrator::getAgentInterface<Interface>(mAgent, mErrorMessage, this);
    if (iface)
601
    {
602
603
604
605
606
        iface->setReadOnly(mReadOnly);
        iface->setDisplayName(mName);
        iface->setPath(mPath);
        iface->setAlarmTypes(KAlarm::CalEvent::mimeTypes(mAlarmType));
        iface->setUpdateStorageFormat(false);
607
608
609
610
611
    }
    return iface;
}

/******************************************************************************
612
* Called when a collection fetch job has completed.
613
614
* Obtains the collection handled by the agent, and configures it.
*/
615
void CalendarCreator::collectionFetchResult(KJob* j)
616
{
617
618
    kDebug() << mName;
    if (j->error())
619
    {
620
621
        mErrorMessage = j->errorString();
        kError() << "CollectionFetchJob error: " << mErrorMessage;
622
        finish(true);
623
        return;
624
    }
625
626
627
    CollectionFetchJob* job = static_cast<CollectionFetchJob*>(j);
    Collection::List collections = job->collections();
    if (collections.isEmpty())
628
    {
629
630
631
632
633
634
635
        if (++mCollectionFetchRetryCount >= 10)
        {
            mErrorMessage = i18nc("@info/plain", "New configuration timed out");
            kError() << "Timeout fetching collection for resource";
            finish(true);
            return;
        }
636
637
638
639
640
        // Need to wait a bit longer until the resource has initialised and
        // created its collection. Retry after 200ms.
        kDebug() << "Retrying";
        QTimer::singleShot(200, this, SLOT(fetchCollection()));
        return;
641
    }
642
    if (collections.count() > 1)
643
    {
644
645
        mErrorMessage = i18nc("@info/plain", "New configuration was corrupt");
        kError() << "Wrong number of collections for this resource:" << collections.count();
646
        finish(true);
647
        return;
648
    }
649
650
651
652
653
654

    // Set Akonadi Collection attributes
    Collection collection = collections[0];
    collection.setContentMimeTypes(KAlarm::CalEvent::mimeTypes(mAlarmType));
    EntityDisplayAttribute* dattr = collection.attribute<EntityDisplayAttribute>(Collection::AddIfMissing);
    dattr->setIconName("kalarm");
655
    CollectionAttribute* attr = collection.attribute<CollectionAttribute>(Entity::AddIfMissing);
656
657
658
659
660
    attr->setEnabled(mEnabled ? mAlarmType : KAlarm::CalEvent::EMPTY);
    if (mStandard)
        attr->setStandard(mAlarmType);
    if (mColour.isValid())
        attr->setBackgroundColor(mColour);
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684

    // Update the calendar to the current KAlarm format if necessary,
    // and if the user agrees.
    bool dirResource = false;
    switch (mResourceType)
    {
        case LocalFile:
        case RemoteFile:
            break;
        case LocalDir:
            dirResource = true;
            break;
        default:
            Q_ASSERT(0); // Invalid resource type
            break;
    }
    CalendarUpdater* updater = new CalendarUpdater(collection, dirResource, false, true, this);
    if (!updater->update())   // note that 'updater' will auto-delete when finished
    {
        // Record that the user chose not to update the calendar
        attr->setKeepFormat(true);
    }

    // Update the collection's attributes in the Akonadi database
685
686
    CollectionModifyJob* cmjob = new CollectionModifyJob(collection, this);
    connect(cmjob, SIGNAL(result(KJob*)), this, SLOT(modifyCollectionJobDone(KJob*)));
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
}

/******************************************************************************
* Called when a collection modification job has completed.
* Checks for any error.
*/
void CalendarCreator::modifyCollectionJobDone(KJob* j)
{
    Collection collection = static_cast<CollectionModifyJob*>(j)->collection();
    if (j->error())
    {
        mErrorMessage = j->errorString();
        kError() << "CollectionFetchJob error: " << mErrorMessage;
        finish(true);
    }
    else
    {
        kDebug() << "Completed:" << mName;
        finish(false);
    }
}

/******************************************************************************
* Emit the finished() signal. If 'cleanup' is true, delete the newly created
* but incomplete Agent.
*/
void CalendarCreator::finish(bool cleanup)
{
    if (!mFinished)
    {
        if (cleanup)
            AgentManager::self()->removeInstance(mAgent);
        mFinished = true;
        emit finished(this);
    }
}

#include "calendarmigrator.moc"
#include "moc_calendarmigrator.cpp"

// vim: et sw=4: