File: exportmailjobinterface.cpp

package info (click to toggle)
pim-data-exporter 4%3A22.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,780 kB
  • sloc: cpp: 14,067; xml: 197; makefile: 6; sh: 3
file content (691 lines) | stat: -rw-r--r-- 32,414 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
/*
   SPDX-FileCopyrightText: 2012-2022 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "exportmailjobinterface.h"
#include "importexportmailutil.h"

#include <MailCommon/FilterImporterExporter>

#include <MailTransport/TransportManager>

#include <KLocalizedString>
#include <KZip>
#include <QTemporaryFile>

#include "pimdataexportcore_debug.h"
#include <KMime/Message>
#include <QDir>
#include <QFile>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QTimer>
#include <resourceconverterimpl.h>

#include <KIdentityManagement/Identity>

ExportMailJobInterface::ExportMailJobInterface(QObject *parent, Utils::StoredTypes typeSelected, ArchiveStorage *archiveStorage, int numberOfStep)
    : AbstractImportExportJob(parent, archiveStorage, typeSelected, numberOfStep)
{
}

ExportMailJobInterface::~ExportMailJobInterface() = default;

bool ExportMailJobInterface::checkBackupType(Utils::StoredType type) const
{
    return mTypeSelected & type;
}

void ExportMailJobInterface::start()
{
    Q_EMIT title(i18n("Start export KMail settings..."));
    createProgressDialog(i18n("Export KMail settings"));
    if (checkBackupType(Utils::Identity)) {
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupIdentity);
    } else if (checkBackupType(Utils::MailTransport)) {
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupMailTransport);
    } else if (checkBackupType(Utils::Config)) {
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupConfig);
    } else if (checkBackupType(Utils::Mails)) {
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupMails);
    } else if (checkBackupType(Utils::Resources)) {
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupResources);
    } else {
        Q_EMIT jobFinished();
    }
}

void ExportMailJobInterface::slotCheckBackupIdentity()
{
    if (checkBackupType(Utils::Identity)) {
        backupIdentity();
        increaseProgressDialog();
        if (wasCanceled()) {
            Q_EMIT jobFinished();
            return;
        }
    }
    QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupMailTransport);
}

void ExportMailJobInterface::slotCheckBackupMailTransport()
{
    if (checkBackupType(Utils::MailTransport)) {
        backupTransports();
        increaseProgressDialog();
        if (wasCanceled()) {
            Q_EMIT jobFinished();
            return;
        }
    }
    QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupConfig);
}

void ExportMailJobInterface::slotCheckBackupConfig()
{
    if (checkBackupType(Utils::Config)) {
        backupConfig();
        increaseProgressDialog();
        if (wasCanceled()) {
            Q_EMIT jobFinished();
            return;
        }
    }
    QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupMails);
}

void ExportMailJobInterface::slotCheckBackupMails()
{
    mAkonadiInstanceInfo = listOfResource();
    if (checkBackupType(Utils::Mails)) {
        increaseProgressDialog();
        backupFolderAttributes();
        return;
    }
    QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupResources);
}

void ExportMailJobInterface::backupFolderAttributes()
{
    setProgressDialogLabel(i18n("Backing up Folder Attributes..."));
    connect(this, &ExportMailJobInterface::exportAttributeDone, this, [this]() {
        setProgressDialogLabel(i18n("Backing up Mails..."));
        emitInfo(i18n("Start export resource..."));
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotWriteNextArchiveResource);
    });
    exportFolderAttributes();
}

void ExportMailJobInterface::backupTransports()
{
    setProgressDialogLabel(i18n("Backing up transports..."));

    const QString mailtransportsStr(QStringLiteral("mailtransports"));
    const QString maitransportsrc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + mailtransportsStr;
    if (!QFileInfo::exists(maitransportsrc)) {
        emitInfo(i18n("Transports backup done."));
    } else {
        KSharedConfigPtr mailtransportsConfig = KSharedConfig::openConfig(mailtransportsStr);

        QTemporaryFile tmp;
        tmp.open();
        KConfig *config = mailtransportsConfig->copyTo(tmp.fileName());

        config->sync();
        const bool fileAdded = archive()->addLocalFile(tmp.fileName(), Utils::transportsPath() + QStringLiteral("mailtransports"));
        delete config;
        if (fileAdded) {
            emitInfo(i18n("Transports backup done."));
        } else {
            emitError(i18n("Transport file cannot be added to backup file."));
        }
    }
}

void ExportMailJobInterface::slotCheckBackupResources()
{
    if (checkBackupType(Utils::Resources)) {
        backupResources();
        increaseProgressDialog();
        if (wasCanceled()) {
            Q_EMIT jobFinished();
            return;
        }
    }
    Q_EMIT jobFinished();
}

QString ExportMailJobInterface::applicationName() const
{
    return QStringLiteral("[KMail]");
}

void ExportMailJobInterface::backupConfig()
{
    setProgressDialogLabel(i18n("Backing up config..."));

    exportFilters();

    backupUiRcFile(QStringLiteral("sieveeditorui.rc"), QStringLiteral("sieveeditor"));
    backupUiRcFile(QStringLiteral("kmreadermainwin.rc"), QStringLiteral("kmail2"));
    backupUiRcFile(QStringLiteral("kmcomposerui.rc"), QStringLiteral("kmail2"));
    backupUiRcFile(QStringLiteral("kmmainwin.rc"), QStringLiteral("kmail2"));
    backupUiRcFile(QStringLiteral("kmail_part.rc"), QStringLiteral("kmail2"));
    backupUiRcFile(QStringLiteral("kontactsummary_part.rc"), QStringLiteral("kontactsummary"));
    backupUiRcFile(QStringLiteral("kontactui.rc"), QStringLiteral("kontact"));
    backupUiRcFile(QStringLiteral("kleopatra.rc"), QStringLiteral("kleopatra"));
    backupUiRcFile(QStringLiteral("headerthemeeditorui.rc"), QStringLiteral("headerthemeeditor"));
    backupUiRcFile(QStringLiteral("contactthemeeditorui.rc"), QStringLiteral("contactthemeeditor"));
    backupUiRcFile(QStringLiteral("contactprintthemeeditorui.rc"), QStringLiteral("contactprintthemeeditor"));
    backupUiRcFile(QStringLiteral("kwatchgnupgui.rc"), QStringLiteral("kwatchgnupg"));
    backupUiRcFile(QStringLiteral("akonadiconsoleui.rc"), QStringLiteral("akonadiconsole"));

    backupConfigFile(QStringLiteral("kabldaprc"));
    backupConfigFile(QStringLiteral("kmailsnippetrc"));
    backupConfigFile(QStringLiteral("sievetemplaterc"));
    backupConfigFile(QStringLiteral("customtemplatesrc"));
    backupConfigFile(QStringLiteral("kontactrc"));
    backupConfigFile(QStringLiteral("kontact_summaryrc"));
    backupConfigFile(QStringLiteral("storageservicerc"));
    backupConfigFile(QStringLiteral("kpimbalooblacklist"));
    backupConfigFile(QStringLiteral("kleopatrarc"));
    backupConfigFile(QStringLiteral("sieveeditorrc"));
    backupConfigFile(QStringLiteral("kwatchgnupgrc"));
    backupConfigFile(QStringLiteral("pimpluginsrc"));
    backupConfigFile(QStringLiteral("texttospeechrc"));
    backupConfigFile(QStringLiteral("kleopatracertificateselectiondialogrc"));
    backupConfigFile(QStringLiteral("dkimsettingsrc"));
    backupConfigFile(QStringLiteral("confirmbeforedeletingrc"));

    // Notify file config
    backupConfigFile(QStringLiteral("akonadi_mailfilter_agent.notifyrc"));
    backupConfigFile(QStringLiteral("akonadi_sendlater_agent.notifyrc"));
    backupConfigFile(QStringLiteral("akonadi_archivemail_agent.notifyrc"));
    backupConfigFile(QStringLiteral("kmail2.notifyrc"));
    backupConfigFile(QStringLiteral("akonadi_newmailnotifier_agent.notifyrc"));
    backupConfigFile(QStringLiteral("akonadi_maildispatcher_agent.notifyrc"));
    backupConfigFile(QStringLiteral("akonadi_followupreminder_agent.notifyrc"));
    backupConfigFile(QStringLiteral("messagevieweradblockrc"));
    backupConfigFile(QStringLiteral("messageviewer.notifyrc"));
    backupConfigFile(QStringLiteral("akonadi_newmailnotifier_agentrc"));

    const QString folderMailArchiveStr(QStringLiteral("foldermailarchiverc"));
    const QString folderMailArchiverc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + folderMailArchiveStr;
    if (QFileInfo::exists(folderMailArchiverc)) {
        KSharedConfigPtr archivemailrc = KSharedConfig::openConfig(folderMailArchiveStr);

        QTemporaryFile tmp;
        tmp.open();

        KConfig *archiveConfig = archivemailrc->copyTo(tmp.fileName());
        const QStringList archiveList = archiveConfig->groupList().filter(QRegularExpression(QStringLiteral("FolderArchiveAccount")));

        for (const QString &str : archiveList) {
            KConfigGroup oldGroup = archiveConfig->group(str);
            const qint64 id = oldGroup.readEntry("topLevelCollectionId", -1);
            if (id != -1) {
                const QString realPath = convertToFullCollectionPath(id);
                if (!realPath.isEmpty()) {
                    oldGroup.writeEntry(QStringLiteral("topLevelCollectionId"), realPath);
                }
            }
        }
        archiveConfig->sync();

        backupFile(tmp.fileName(), Utils::configsPath(), folderMailArchiveStr);
        delete archiveConfig;
    }
    const QString unifiedMailBoxStr(QStringLiteral("akonadi_unifiedmailbox_agentrc"));
    const QString unifiedMailBoxrc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + unifiedMailBoxStr;
    if (QFileInfo::exists(unifiedMailBoxrc)) {
        KSharedConfigPtr mboxrc = KSharedConfig::openConfig(unifiedMailBoxrc);

        QTemporaryFile tmp;
        tmp.open();

        KConfig *archiveConfig = mboxrc->copyTo(tmp.fileName());
        auto group = archiveConfig->group("UnifiedMailboxes");
        const auto boxGroups = group.groupList();
        for (const auto &str : boxGroups) {
            KConfigGroup oldGroup = group.group(str);

            const qint64 id = oldGroup.readEntry("collectionId", -1);
            if (id != -1) {
                const QString realPath = convertToFullCollectionPath(id);
                if (!realPath.isEmpty()) {
                    oldGroup.writeEntry(QStringLiteral("collectionId"), realPath);
                }
            }
            const QString sourceKey(QStringLiteral("sources"));
            convertCollectionListToRealPath(oldGroup, sourceKey);
        }
        archiveConfig->sync();

        backupFile(tmp.fileName(), Utils::configsPath(), unifiedMailBoxStr);
        delete archiveConfig;
    }

    const QString archiveMailAgentConfigurationStr(QStringLiteral("akonadi_archivemail_agentrc"));
    const QString archiveMailAgentconfigurationrc =
        QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + archiveMailAgentConfigurationStr;
    if (QFileInfo::exists(archiveMailAgentconfigurationrc)) {
        KSharedConfigPtr archivemailrc = KSharedConfig::openConfig(archiveMailAgentConfigurationStr);

        QTemporaryFile tmp;
        tmp.open();

        KConfig *archiveConfig = archivemailrc->copyTo(tmp.fileName());
        const QStringList archiveList = archiveConfig->groupList().filter(QRegularExpression(QStringLiteral("ArchiveMailCollection \\d+")));
        const QString archiveGroupPattern = QStringLiteral("ArchiveMailCollection ");

        for (const QString &str : archiveList) {
            bool found = false;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
            const int collectionId = str.rightRef(str.length() - archiveGroupPattern.length()).toInt(&found);
#else
            const int collectionId = QStringView(str).right(str.length() - archiveGroupPattern.length()).toInt(&found);
#endif
            if (found) {
                KConfigGroup oldGroup = archiveConfig->group(str);
                const QString realPath = convertToFullCollectionPath(collectionId);
                if (!realPath.isEmpty()) {
                    const QString collectionPath(archiveGroupPattern + realPath);
                    KConfigGroup newGroup(archiveConfig, collectionPath);
                    oldGroup.copyTo(&newGroup);
                    newGroup.writeEntry(QStringLiteral("saveCollectionId"), realPath);
                }
                oldGroup.deleteGroup();
            }
        }
        archiveConfig->sync();

        backupFile(tmp.fileName(), Utils::configsPath(), archiveMailAgentConfigurationStr);
        delete archiveConfig;
    }

    const QString templatesconfigurationrcStr(QStringLiteral("templatesconfigurationrc"));
    const QString templatesconfigurationrc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + templatesconfigurationrcStr;
    if (QFileInfo::exists(templatesconfigurationrc)) {
        KSharedConfigPtr templaterc = KSharedConfig::openConfig(templatesconfigurationrcStr);

        QTemporaryFile tmp;
        tmp.open();

        KConfig *templateConfig = templaterc->copyTo(tmp.fileName());
        const QString templateGroupPattern = QStringLiteral("Templates #");
        const QStringList templateList = templateConfig->groupList().filter(QRegularExpression(QStringLiteral("Templates #\\d+")));
        for (const QString &str : templateList) {
            bool found = false;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
            const int collectionId = str.rightRef(str.length() - templateGroupPattern.length()).toInt(&found);
#else
            const int collectionId = QStringView(str).right(str.length() - templateGroupPattern.length()).toInt(&found);
#endif
            if (found) {
                KConfigGroup oldGroup = templateConfig->group(str);
                const QString realPath = convertToFullCollectionPath(collectionId);
                if (!realPath.isEmpty()) {
                    KConfigGroup newGroup(templateConfig, templateGroupPattern + realPath);
                    oldGroup.copyTo(&newGroup);
                }
                oldGroup.deleteGroup();
            }
        }
        templateConfig->sync();

        backupFile(tmp.fileName(), Utils::configsPath(), templatesconfigurationrcStr);
        delete templateConfig;
    }

    storeDirectory(QStringLiteral("/messageviewerplugins/"));
    storeDirectory(QStringLiteral("/messageviewer/themes/"));

    const QDir gravatarDirectory(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/gravatar/"));
    if (gravatarDirectory.exists()) {
        const QFileInfoList listFileInfo = gravatarDirectory.entryInfoList(QStringList() << QStringLiteral("*.png"), QDir::Files);
        const int listSize(listFileInfo.size());
        for (int i = 0; i < listSize; ++i) {
            backupFile(listFileInfo.at(i).absoluteFilePath(), Utils::dataPath() + QStringLiteral("gravatar/"), listFileInfo.at(i).fileName());
        }
    }

    const QDir autocorrectDirectory(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/autocorrect/"));
    if (autocorrectDirectory.exists()) {
        const QFileInfoList listFileInfo = autocorrectDirectory.entryInfoList(QStringList() << QStringLiteral("*.xml"), QDir::Files);
        const int listSize(listFileInfo.size());
        for (int i = 0; i < listSize; ++i) {
            backupFile(listFileInfo.at(i).absoluteFilePath(), Utils::dataPath() + QStringLiteral("autocorrect/"), listFileInfo.at(i).fileName());
        }
    }
    const QString adblockFilePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/kmail2/adblockrules_local");
    if (QFileInfo::exists(adblockFilePath)) {
        backupFile(adblockFilePath, Utils::dataPath() + QStringLiteral("kmail2/"), QStringLiteral("adblockrules_local"));
    }

    const QString kmailStr(QStringLiteral("kmail2rc"));
    const QString kmail2rc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + kmailStr;
    if (QFileInfo::exists(kmail2rc)) {
        KSharedConfigPtr kmailrc = KSharedConfig::openConfig(kmail2rc);

        QTemporaryFile tmp;
        tmp.open();

        KConfig *kmailConfig = kmailrc->copyTo(tmp.fileName());
        const QString folderGroupPattern = QStringLiteral("Folder-");
        const QStringList folderList = kmailConfig->groupList().filter(QRegularExpression(QStringLiteral("Folder-\\d+")));
        for (const QString &str : folderList) {
            bool found = false;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
            const int collectionId = str.rightRef(str.length() - folderGroupPattern.length()).toInt(&found);
#else
            const int collectionId = QStringView(str).right(str.length() - folderGroupPattern.length()).toInt(&found);
#endif
            if (found) {
                KConfigGroup oldGroup = kmailConfig->group(str);
                ImportExportMailUtil::cleanupFolderSettings(oldGroup);
                const QString realPath = convertToFullCollectionPath(collectionId);
                if (!realPath.isEmpty()) {
                    KConfigGroup newGroup(kmailConfig, folderGroupPattern + realPath);
                    oldGroup.copyTo(&newGroup);
                }
                oldGroup.deleteGroup();
            }
        }
        const QString composerStr(QStringLiteral("Composer"));
        if (kmailConfig->hasGroup(composerStr)) {
            KConfigGroup composerGroup = kmailConfig->group(composerStr);
            const QString previousStr(QStringLiteral("previous-fcc"));
            if (composerGroup.hasKey(previousStr)) {
                const int collectionId = composerGroup.readEntry(previousStr, -1);
                if (collectionId != -1) {
                    const QString realPath = convertToFullCollectionPath(collectionId);
                    composerGroup.writeEntry(previousStr, realPath);
                }
            }
        }

        const QString generalStr(QStringLiteral("General"));
        if (kmailConfig->hasGroup(generalStr)) {
            KConfigGroup generalGroup = kmailConfig->group(generalStr);
            const QString startupFolderStr(QStringLiteral("startupFolder"));
            if (generalGroup.hasKey(startupFolderStr)) {
                const int collectionId = generalGroup.readEntry(startupFolderStr, -1);
                if (collectionId != -1) {
                    const QString realPath = convertToFullCollectionPath(collectionId);
                    generalGroup.writeEntry(startupFolderStr, realPath);
                }
            }
        }

        const QString storageModelSelectedMessageStr(QStringLiteral("MessageListView::StorageModelSelectedMessages"));
        if (kmailConfig->hasGroup(storageModelSelectedMessageStr)) {
            KConfigGroup storageGroup = kmailConfig->group(storageModelSelectedMessageStr);
            const QString storageModelSelectedPattern(QStringLiteral("MessageUniqueIdForStorageModel"));
            const QStringList storageList = storageGroup.keyList().filter(QRegularExpression(QStringLiteral("MessageUniqueIdForStorageModel\\d+")));
            for (const QString &str : storageList) {
                bool found = false;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
                const int collectionId = str.rightRef(str.length() - storageModelSelectedPattern.length()).toInt(&found);
#else
                const int collectionId = QStringView(str).right(str.length() - storageModelSelectedPattern.length()).toInt(&found);
#endif
                const QString oldValue = storageGroup.readEntry(str);
                if (found) {
                    const QString realPath = convertToFullCollectionPath(collectionId);
                    if (!realPath.isEmpty()) {
                        storageGroup.writeEntry(QStringLiteral("%1%2").arg(storageModelSelectedPattern, realPath), oldValue);
                        storageGroup.deleteEntry(str);
                    } else {
                        storageGroup.deleteEntry(str);
                    }
                }
            }
        }

        const QString collectionFolderViewStr(QStringLiteral("CollectionFolderView"));
        if (kmailConfig->hasGroup(collectionFolderViewStr)) {
            KConfigGroup favoriteGroup = kmailConfig->group(collectionFolderViewStr);

            const QString currentKey(QStringLiteral("Current"));
            convertCollectionToRealPath(favoriteGroup, currentKey);

            const QString expensionKey(QStringLiteral("Expansion"));
            convertCollectionListToRealPath(favoriteGroup, expensionKey);
        }

        const QString favoriteCollectionStr(QStringLiteral("FavoriteCollections"));
        if (kmailConfig->hasGroup(favoriteCollectionStr)) {
            KConfigGroup favoriteGroup = kmailConfig->group(favoriteCollectionStr);

            const QString favoriteCollectionIdsStr(QStringLiteral("FavoriteCollectionIds"));
            convertCollectionIdsToRealPath(favoriteGroup, favoriteCollectionIdsStr);
        }

        const QString favoriteCollectionOrderStr(QStringLiteral("FavoriteCollectionsOrder"));
        if (kmailConfig->hasGroup(favoriteCollectionOrderStr)) {
            KConfigGroup favoriteGroup = kmailConfig->group(favoriteCollectionOrderStr);
            // For favorite id for root collection == 0 and we store only folder => c
            const QString favoriteCollectionIdsStr(QStringLiteral("0"));
            const QString prefixCollection(QStringLiteral("c"));
            convertCollectionIdsToRealPath(favoriteGroup, favoriteCollectionIdsStr, prefixCollection);
        }

        // Event collection
        const QString eventCollectionStr(QStringLiteral("Event"));
        if (kmailConfig->hasGroup(eventCollectionStr)) {
            KConfigGroup eventGroup = kmailConfig->group(eventCollectionStr);
            const QString eventLastEventSelectedFolder(QStringLiteral("LastEventSelectedFolder"));
            convertCollectionIdsToRealPath(eventGroup, eventLastEventSelectedFolder);
        }

        // Todo collection
        const QString todoCollectionStr(QStringLiteral("Todo"));
        if (kmailConfig->hasGroup(todoCollectionStr)) {
            KConfigGroup todoGroup = kmailConfig->group(todoCollectionStr);
            const QString todoLastEventSelectedFolder(QStringLiteral("LastSelectedFolder"));
            convertCollectionIdsToRealPath(todoGroup, todoLastEventSelectedFolder);
        }
        // FolderSelectionDialog collection
        const QString folderSelectionCollectionStr(QStringLiteral("FolderSelectionDialog"));
        if (kmailConfig->hasGroup(folderSelectionCollectionStr)) {
            KConfigGroup folderSelectionGroup = kmailConfig->group(folderSelectionCollectionStr);
            const QString folderSelectionSelectedFolder(QStringLiteral("LastSelectedFolder"));
            convertCollectionIdsToRealPath(folderSelectionGroup, folderSelectionSelectedFolder);
        }

        // Note collection
        const QString noteCollectionStr(QStringLiteral("Note"));
        if (kmailConfig->hasGroup(noteCollectionStr)) {
            KConfigGroup noteGroup = kmailConfig->group(noteCollectionStr);
            const QString noteLastEventSelectedFolder(QStringLiteral("LastNoteSelectedFolder"));
            convertCollectionIdsToRealPath(noteGroup, noteLastEventSelectedFolder);
        }

        // Convert MessageListTab collection id
        const QString messageListPaneStr(QStringLiteral("MessageListPane"));
        if (kmailConfig->hasGroup(messageListPaneStr)) {
            KConfigGroup messageListPaneGroup = kmailConfig->group(messageListPaneStr);
            const int numberOfTab = messageListPaneGroup.readEntry(QStringLiteral("tabNumber"), 0);
            for (int i = 0; i < numberOfTab; ++i) {
                KConfigGroup messageListPaneTabGroup = kmailConfig->group(QStringLiteral("MessageListTab%1").arg(i));
                const QString messageListPaneTabFolderStr(QStringLiteral("collectionId"));
                convertCollectionIdsToRealPath(messageListPaneTabGroup, messageListPaneTabFolderStr);
            }
        }

        // Automatic Add Contacts
        const QVector<uint> listIdentities = listIdentityUoid();
        for (uint identity : listIdentities) {
            const QString groupId = QStringLiteral("Automatic Add Contacts %1").arg(identity);
            if (kmailConfig->hasGroup(groupId)) {
                KConfigGroup identityGroup = kmailConfig->group(groupId);
                const QString automaticAddContactStr(QStringLiteral("Collection"));
                convertCollectionIdsToRealPath(identityGroup, automaticAddContactStr);
            }
        }

        // TODO add confirm address too

        // Clean up kmail2rc
        const QString tipOfDaysStr(QStringLiteral("TipOfDay"));
        if (kmailConfig->hasGroup(tipOfDaysStr)) {
            kmailConfig->deleteGroup(tipOfDaysStr);
        }
        const QString startupStr(QStringLiteral("Startup"));
        if (kmailConfig->hasGroup(startupStr)) {
            kmailConfig->deleteGroup(startupStr);
        }

        const QString search(QStringLiteral("Search"));
        if (kmailConfig->hasGroup(search)) {
            KConfigGroup searchGroup = kmailConfig->group(search);
            searchGroup.deleteGroup();
        }

        kmailConfig->sync();
        backupFile(tmp.fileName(), Utils::configsPath(), kmailStr);
        delete kmailConfig;
    }

    emitInfo(i18n("Config backup done."));
}

void ExportMailJobInterface::backupIdentity()
{
    setProgressDialogLabel(i18n("Backing up identity..."));

    const QString emailidentitiesStr(QStringLiteral("emailidentities"));
    const QString emailidentitiesrc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QLatin1Char('/') + emailidentitiesStr;
    if (QFileInfo::exists(emailidentitiesrc)) {
        KSharedConfigPtr identity = KSharedConfig::openConfig(emailidentitiesrc);

        QTemporaryFile tmp;
        tmp.open();

        KConfig *identityConfig = identity->copyTo(tmp.fileName());
        const QStringList accountList = identityConfig->groupList().filter(QRegularExpression(QStringLiteral("Identity #\\d+")));
        for (const QString &account : accountList) {
            KConfigGroup group = identityConfig->group(account);
            const QString fcc = QStringLiteral("Fcc");
            if (group.hasKey(fcc)) {
                const QString realPath = convertToFullCollectionPath(group.readEntry(fcc).toLongLong());
                group.writeEntry(fcc, realPath);
            }
            const QString draft = QStringLiteral("Drafts");
            if (group.hasKey(draft)) {
                const QString realPath = convertToFullCollectionPath(group.readEntry(draft).toLongLong());
                group.writeEntry(draft, realPath);
            }
            const QString templates = QStringLiteral("Templates");
            if (group.hasKey(templates)) {
                const QString realPath = convertToFullCollectionPath(group.readEntry(templates).toLongLong());
                group.writeEntry(templates, realPath);
            }
            const QString vcard = QStringLiteral("VCardFile");
            if (group.hasKey(vcard)) {
                const QString vcardFileName = group.readEntry(vcard);
                if (!vcardFileName.isEmpty()) {
                    const int uoid = group.readEntry(QStringLiteral("uoid"), -1);
                    QFile file(vcardFileName);
                    if (file.exists()) {
                        const bool fileAdded =
                            archive()->addLocalFile(vcardFileName, Utils::identitiesPath() + QString::number(uoid) + QLatin1Char('/') + file.fileName());
                        if (!fileAdded) {
                            emitError(i18n("vCard file \"%1\" cannot be saved.", file.fileName()));
                        }
                    } else {
                        group.deleteEntry(vcard);
                    }
                }
            }
        }

        identityConfig->sync();
        const bool fileAdded = archive()->addLocalFile(tmp.fileName(), Utils::identitiesPath() + QStringLiteral("emailidentities"));
        delete identityConfig;
        if (fileAdded) {
            emitInfo(i18n("Identity backup done."));
        } else {
            emitError(i18n("Identity file cannot be added to backup file."));
        }
    }
}

void ExportMailJobInterface::slotMailsJobTerminated()
{
    if (wasCanceled()) {
        Q_EMIT jobFinished();
        return;
    }
    mIndexIdentifier++;
    QTimer::singleShot(0, this, &ExportMailJobInterface::slotWriteNextArchiveResource);
}

void ExportMailJobInterface::slotWriteNextArchiveResource()
{
    if (mIndexIdentifier < mAkonadiInstanceInfo.count()) {
        const Utils::AkonadiInstanceInfo agent = mAkonadiInstanceInfo.at(mIndexIdentifier);
        const QStringList capabilities(agent.capabilities);
        if (agent.mimeTypes.contains(KMime::Message::mimeType())) {
            if (capabilities.contains(QLatin1String("Resource")) && !capabilities.contains(QLatin1String("Virtual"))
                && !capabilities.contains(QLatin1String("MailTransport"))) {
                const QString identifier = agent.identifier;
                if (identifier.contains(QLatin1String("akonadi_maildir_resource_")) || identifier.contains(QLatin1String("akonadi_mixedmaildir_resource_"))) {
                    const QString archivePath = Utils::mailsPath() + identifier + QLatin1Char('/');
                    const QString url = resourcePath(identifier);
                    if (!mAgentPaths.contains(url)) {
                        if (!url.isEmpty()) {
                            mAgentPaths << url;
                            exportResourceToArchive(archivePath, url, identifier);
                        } else {
                            qCDebug(PIMDATAEXPORTERCORE_LOG) << "Url is empty for " << identifier;
                            QTimer::singleShot(0, this, &ExportMailJobInterface::slotMailsJobTerminated);
                        }
                    } else {
                        QTimer::singleShot(0, this, &ExportMailJobInterface::slotMailsJobTerminated);
                    }
                } else if (identifier.contains(QLatin1String("akonadi_mbox_resource_"))) {
                    backupMailResourceFile(identifier, Utils::mailsPath()); // FIXME addressbookPath or MailPAth ???
                    QTimer::singleShot(0, this, &ExportMailJobInterface::slotMailsJobTerminated);
                } else {
                    QTimer::singleShot(0, this, &ExportMailJobInterface::slotMailsJobTerminated);
                }
            } else {
                QTimer::singleShot(0, this, &ExportMailJobInterface::slotMailsJobTerminated);
            }
        } else {
            QTimer::singleShot(0, this, &ExportMailJobInterface::slotMailsJobTerminated);
        }
    } else {
        QTimer::singleShot(0, this, &ExportMailJobInterface::slotCheckBackupResources);
    }
}

void ExportMailJobInterface::backupResources()
{
    setProgressDialogLabel(i18n("Backing up resources..."));

    for (const Utils::AkonadiInstanceInfo &agent : std::as_const(mAkonadiInstanceInfo)) {
        const QStringList capabilities = agent.capabilities;
        if (agent.mimeTypes.contains(KMime::Message::mimeType())) {
            if (capabilities.contains(QLatin1String("Resource")) && !capabilities.contains(QLatin1String("Virtual"))
                && !capabilities.contains(QLatin1String("MailTransport"))) {
                const QString identifier = agent.identifier;
                // Store just pop3/imap/kolab/gmail account. Store other config when we copy data.
                if (identifier.contains(QLatin1String("pop3")) || identifier.contains(QLatin1String("imap")) || identifier.contains(QLatin1String("_kolab_"))
                    || identifier.contains(QLatin1String("_gmail_"))) {
                    const QString errorStr = storeResources(archive(), identifier, Utils::resourcesPath());
                    if (!errorStr.isEmpty()) {
                        emitError(errorStr);
                    }
                } else {
                    qCDebug(PIMDATAEXPORTERCORE_LOG) << " resource \"" << identifier << "\" will not store";
                }
            }
        }
    }

    emitInfo(i18n("Resources backup done."));
}