summaryrefslogtreecommitdiffstats
path: root/examples/maildirresource/maildirresource.cpp
blob: e1e4d9570f9de986532e1458c56e0a3b0ea5c64c (plain)
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
/*
 *   Copyright (C) 2015 Christian Mollekopf <chrigi_1@fastmail.fm>
 *
 *   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 "maildirresource.h"
#include "facade.h"
#include "entitybuffer.h"
#include "pipeline.h"
#include "mail_generated.h"
#include "createentity_generated.h"
#include "modifyentity_generated.h"
#include "deleteentity_generated.h"
#include "domainadaptor.h"
#include "resourceconfig.h"
#include "commands.h"
#include "index.h"
#include "log.h"
#include "domain/mail.h"
#include "definitions.h"
#include "facadefactory.h"
#include "indexupdater.h"
#include "libmaildir/maildir.h"
#include "inspection.h"
#include <QDate>
#include <QUuid>
#include <QDir>
#include <QDirIterator>
#include <KMime/KMime/KMimeMessage>

//This is the resources entity type, and not the domain type
#define ENTITY_TYPE_MAIL "mail"
#define ENTITY_TYPE_FOLDER "folder"

#undef DEBUG_AREA
#define DEBUG_AREA "resource.maildir"

static QString getFilePathFromMimeMessagePath(const QString &mimeMessagePath)
{
    auto parts = mimeMessagePath.split('/');
    const auto key = parts.takeLast();
    const auto path = parts.join("/") + "/cur/";

    QDir dir(path);
    const QFileInfoList list = dir.entryInfoList(QStringList() << (key+"*"), QDir::Files);
    if (list.size() != 1) {
        Warning() << "Failed to find message " << mimeMessagePath;
        Warning() << "Failed to find message " << path;
        return QString();
    }
    return list.first().filePath();
}

class FolderUpdater : public Sink::Preprocessor
{
public:
    FolderUpdater(const QByteArray &drafts) : mDraftsFolder(drafts) {}

    QString getPath(const QByteArray &folderIdentifier, Sink::Storage::Transaction &transaction)
    {
        if (folderIdentifier.isEmpty()) {
            return mMaildirPath;
        }
        QString folderPath;
        auto db = Sink::Storage::mainDatabase(transaction, ENTITY_TYPE_FOLDER);
        db.findLatest(folderIdentifier, [&](const QByteArray &, const QByteArray &value) {
            Sink::EntityBuffer buffer(value);
            const Sink::Entity &entity = buffer.entity();
            const auto adaptor = mFolderAdaptorFactory->createAdaptor(entity);
            auto parentFolder = adaptor->getProperty("parent").toString();
            if (mMaildirPath.endsWith(adaptor->getProperty("name").toString())) {
                folderPath = mMaildirPath;
            } else {
                auto folderName = adaptor->getProperty("name").toString();
                //TODO handle non toplevel folders
                folderPath = mMaildirPath + "/" + folderName;
            }
        });
        return folderPath;
    }

    QString moveMessage(const QString &oldPath, const QByteArray &folder, Sink::Storage::Transaction &transaction)
    {
        if (oldPath.startsWith(Sink::temporaryFileLocation())) {
            const auto path = getPath(folder, transaction);
            KPIM::Maildir maildir(path, false);
            if (!maildir.isValid(true)) {
                qWarning() << "Maildir is not existing: " << path;
            }
            auto identifier = maildir.addEntryFromPath(oldPath);
            return path + "/" + identifier;
        }
        return oldPath;
    }

    void updatedIndexedProperties(Sink::ApplicationDomain::BufferAdaptor &newEntity)
    {
        const auto filePath = getFilePathFromMimeMessagePath(newEntity.getProperty("mimeMessage").toString());

        KMime::Message *msg = new KMime::Message;
        msg->setHead(KMime::CRLFtoLF(KPIM::Maildir::readEntryHeadersFromFile(filePath)));
        msg->parse();

        newEntity.setProperty("subject", msg->subject(true)->asUnicodeString());
        newEntity.setProperty("sender", msg->from(true)->asUnicodeString());
        newEntity.setProperty("senderName", msg->from(true)->asUnicodeString());
        newEntity.setProperty("date", msg->date(true)->dateTime());
    }

    void newEntity(const QByteArray &uid, qint64 revision, Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE
    {
        if (newEntity.getProperty("draft").toBool()) {
            newEntity.setProperty("folder", mDraftsFolder);
        }
        const auto mimeMessage = newEntity.getProperty("mimeMessage");
        if (mimeMessage.isValid()) {
            newEntity.setProperty("mimeMessage", moveMessage(mimeMessage.toString(), newEntity.getProperty("folder").toByteArray(), transaction));
        }
        updatedIndexedProperties(newEntity);
    }

    void modifiedEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, Sink::ApplicationDomain::BufferAdaptor &newEntity,
        Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE
    {
        //TODO deal with moves
        const auto mimeMessage = newEntity.getProperty("mimeMessage");
        if (mimeMessage.isValid()) {
            newEntity.setProperty("mimeMessage", moveMessage(mimeMessage.toString(), newEntity.getProperty("folder").toByteArray(), transaction));
        }
        updatedIndexedProperties(newEntity);
    }

    void deletedEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE
    {
    }
    QByteArray mDraftsFolder;
    QByteArray mResourceInstanceIdentifier;
    QString mMaildirPath;
    QSharedPointer<MaildirFolderAdaptorFactory> mFolderAdaptorFactory;
};

class FolderPreprocessor : public Sink::Preprocessor
{
public:
    FolderPreprocessor() {}

    void newEntity(const QByteArray &uid, qint64 revision, Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE
    {
        auto folderName = newEntity.getProperty("name").toString();
        const auto path = mMaildirPath + "/" + folderName;
        KPIM::Maildir maildir(path, false);
        maildir.create();
    }

    void modifiedEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, Sink::ApplicationDomain::BufferAdaptor &newEntity,
        Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE
    {
    }

    void deletedEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE
    {
    }
    QString mMaildirPath;
};

MaildirResource::MaildirResource(const QByteArray &instanceIdentifier, const QSharedPointer<Sink::Pipeline> &pipeline)
    : Sink::GenericResource(instanceIdentifier, pipeline),
    mMailAdaptorFactory(QSharedPointer<MaildirMailAdaptorFactory>::create()),
    mFolderAdaptorFactory(QSharedPointer<MaildirFolderAdaptorFactory>::create())
{
    auto config = ResourceConfig::getConfiguration(instanceIdentifier);
    mMaildirPath = QDir::cleanPath(QDir::fromNativeSeparators(config.value("path").toString()));
    //Chop a trailing slash if necessary
    if (mMaildirPath.endsWith("/")) {
        mMaildirPath.chop(1);
    }

    auto folderUpdater = new FolderUpdater(QByteArray());
    addType(ENTITY_TYPE_MAIL, mMailAdaptorFactory,
            QVector<Sink::Preprocessor*>() << folderUpdater << new DefaultIndexUpdater<Sink::ApplicationDomain::Mail>);
    auto folderPreprocessor = new FolderPreprocessor;
    addType(ENTITY_TYPE_FOLDER, mFolderAdaptorFactory,
            QVector<Sink::Preprocessor*>() << folderPreprocessor << new DefaultIndexUpdater<Sink::ApplicationDomain::Folder>);

    KPIM::Maildir dir(mMaildirPath, true);
    mDraftsFolder = dir.addSubFolder("drafts");
    Trace() << "Started maildir resource for maildir: " << mMaildirPath;
    auto mainStore = QSharedPointer<Sink::Storage>::create(Sink::storageLocation(), mResourceInstanceIdentifier, Sink::Storage::ReadOnly);
    auto syncStore = QSharedPointer<Sink::Storage>::create(Sink::storageLocation(), mResourceInstanceIdentifier + ".synchronization", Sink::Storage::ReadWrite);
    auto transaction = mainStore->createTransaction(Sink::Storage::ReadOnly);
    auto synchronizationTransaction = syncStore->createTransaction(Sink::Storage::ReadWrite);

    auto remoteId = createFolder(mDraftsFolder, "folder", transaction, synchronizationTransaction);
    auto draftsFolderLocalId = resolveRemoteId(ENTITY_TYPE_FOLDER, remoteId, synchronizationTransaction);
    synchronizationTransaction.commit();

    folderUpdater->mDraftsFolder = draftsFolderLocalId;
    folderUpdater->mResourceInstanceIdentifier = mResourceInstanceIdentifier;
    folderUpdater->mFolderAdaptorFactory = mFolderAdaptorFactory;
    folderUpdater->mMaildirPath = mMaildirPath;
    folderPreprocessor->mMaildirPath = mMaildirPath;
}

static QStringList listRecursive( const QString &root, const KPIM::Maildir &dir )
{
    QStringList list;
    foreach (const QString &sub, dir.subFolderList()) {
        const KPIM::Maildir md = dir.subFolder(sub);
        if (!md.isValid()) {
            continue;
        }
        QString path = root + "/" + sub;
        list << path;
        list += listRecursive(path, md );
    }
    return list;
}

QByteArray MaildirResource::createFolder(const QString &folderPath, const QByteArray &icon, Sink::Storage::Transaction &transaction, Sink::Storage::Transaction &synchronizationTransaction)
{
    auto remoteId = folderPath.toUtf8();
    auto bufferType = ENTITY_TYPE_FOLDER;
    KPIM::Maildir md(folderPath, folderPath == mMaildirPath);
    Sink::ApplicationDomain::Folder folder;
    folder.setProperty("name", md.name());
    folder.setProperty("icon", icon);

    if (!md.isRoot()) {
        folder.setProperty("parent", resolveRemoteId(ENTITY_TYPE_FOLDER, md.parent().path().toUtf8(), synchronizationTransaction));
    }
    createOrModify(transaction, synchronizationTransaction, *mFolderAdaptorFactory, bufferType, remoteId, folder);
    return remoteId;
}

QStringList MaildirResource::listAvailableFolders()
{
    KPIM::Maildir dir(mMaildirPath, true);
    if (!dir.isValid()) {
        return QStringList();
    }
    QStringList folderList;
    folderList << mMaildirPath;
    folderList += listRecursive(mMaildirPath, dir);
    return folderList;
}

void MaildirResource::synchronizeFolders(Sink::Storage::Transaction &transaction, Sink::Storage::Transaction &synchronizationTransaction)
{
    const QByteArray bufferType = ENTITY_TYPE_FOLDER;
    QStringList folderList = listAvailableFolders();
    Trace() << "Found folders " << folderList;

    scanForRemovals(transaction, synchronizationTransaction, bufferType,
        [&bufferType, &transaction](const std::function<void(const QByteArray &)> &callback) {
            //TODO Instead of iterating over all entries in the database, which can also pick up the same item multiple times,
            //we should rather iterate over an index that contains every uid exactly once. The remoteId index would be such an index,
            //but we currently fail to iterate over all entries in an index it seems.
            // auto remoteIds = synchronizationTransaction.openDatabase("rid.mapping." + bufferType, std::function<void(const Sink::Storage::Error &)>(), true);
            auto mainDatabase = Sink::Storage::mainDatabase(transaction, bufferType);
            mainDatabase.scan("", [&](const QByteArray &key, const QByteArray &) {
                callback(key);
                return true;
            });
        },
        [&folderList](const QByteArray &remoteId) -> bool {
            return folderList.contains(remoteId);
        }
    );

    for (const auto folderPath : folderList) {
        createFolder(folderPath, "folder", transaction, synchronizationTransaction);
    }
}

void MaildirResource::synchronizeMails(Sink::Storage::Transaction &transaction, Sink::Storage::Transaction &synchronizationTransaction, const QString &path)
{
    Trace() << "Synchronizing mails" << path;
    auto time = QSharedPointer<QTime>::create();
    time->start();
    const QByteArray bufferType = ENTITY_TYPE_MAIL;

    KPIM::Maildir maildir(path, true);
    if (!maildir.isValid()) {
        Warning() << "Failed to sync folder " << maildir.lastError();
        return;
    }

    Trace() << "Importing new mail.";
    maildir.importNewMails();

    auto listingPath = maildir.pathToCurrent();
    auto entryIterator = QSharedPointer<QDirIterator>::create(listingPath, QDir::Files);
    Trace() << "Looking into " << listingPath;

    const auto folderLocalId = resolveRemoteId(ENTITY_TYPE_FOLDER, path.toUtf8(), synchronizationTransaction);

    auto property = "folder";
    scanForRemovals(transaction, synchronizationTransaction, bufferType,
        [&](const std::function<void(const QByteArray &)> &callback) {
            Index index(bufferType + ".index." + property, transaction);
            index.lookup(folderLocalId, [&](const QByteArray &sinkId) {
                callback(sinkId);
            },
            [&](const Index::Error &error) {
                Warning() << "Error in index: " <<  error.message << property;
            });
        },
        [](const QByteArray &remoteId) -> bool {
            return QFile(remoteId).exists();
        }
    );

    mSynchronizerQueue.startTransaction();
    int count = 0;
    while (entryIterator->hasNext()) {
        count++;
        const QString filePath = QDir::fromNativeSeparators(entryIterator->next());
        const QString fileName = entryIterator->fileName();
        const auto remoteId = filePath.toUtf8();

        const auto flags = maildir.readEntryFlags(fileName);
        const auto maildirKey = maildir.getKeyFromFile(fileName);

        Trace() << "Found a mail " << filePath << " : " << fileName;

        Sink::ApplicationDomain::Mail mail;
        mail.setProperty("folder", folderLocalId);
        //We only store the directory path + key, so we facade can add the changing bits (flags)
        mail.setProperty("mimeMessage", KPIM::Maildir::getDirectoryFromFile(filePath) + maildirKey);
        mail.setProperty("unread", !flags.testFlag(KPIM::Maildir::Seen));
        mail.setProperty("important", flags.testFlag(KPIM::Maildir::Flagged));

        createOrModify(transaction, synchronizationTransaction, *mMailAdaptorFactory, bufferType, remoteId, mail);
    }
    mSynchronizerQueue.commit();
    const auto elapsed = time->elapsed();
    Log() << "Synchronized " << count << " mails in " << listingPath << Sink::Log::TraceTime(elapsed) << " " << elapsed/qMax(count, 1) << " [ms/mail]";

}

KAsync::Job<void> MaildirResource::synchronizeWithSource(Sink::Storage &mainStore, Sink::Storage &synchronizationStore)
{
    Log() << " Synchronizing";
    return KAsync::start<void>([this, &mainStore, &synchronizationStore]() {
        auto transaction = mainStore.createTransaction(Sink::Storage::ReadOnly);
        {
            auto synchronizationTransaction = synchronizationStore.createTransaction(Sink::Storage::ReadWrite);
            synchronizeFolders(transaction, synchronizationTransaction);
            //The next sync needs the folders available
            synchronizationTransaction.commit();
        }
        for (const auto &folder : listAvailableFolders()) {
            auto synchronizationTransaction = synchronizationStore.createTransaction(Sink::Storage::ReadWrite);
            synchronizeMails(transaction, synchronizationTransaction, folder);
            //Don't let the transaction grow too much
            synchronizationTransaction.commit();
        }
        Log() << "Done Synchronizing";
    });
}

KAsync::Job<void> MaildirResource::replay(Sink::Storage &synchronizationStore, const QByteArray &type, const QByteArray &key, const QByteArray &value)
{
    auto synchronizationTransaction = synchronizationStore.createTransaction(Sink::Storage::ReadWrite);

    Sink::EntityBuffer buffer(value);
    const Sink::Entity &entity = buffer.entity();
    const auto metadataBuffer = Sink::EntityBuffer::readBuffer<Sink::Metadata>(entity.metadata());
    Q_ASSERT(metadataBuffer);
    if (!metadataBuffer->replayToSource()) {
        Trace() << "Change is coming from the source";
        return KAsync::null<void>();
    }
    const qint64 revision = metadataBuffer ? metadataBuffer->revision() : -1;
    const auto operation = metadataBuffer ? metadataBuffer->operation() : Sink::Operation_Creation;

    Trace() << "Replaying " << key << type;
    if (type == ENTITY_TYPE_FOLDER) {
        if (operation == Sink::Operation_Creation) {
            const Sink::ApplicationDomain::Folder folder(mResourceInstanceIdentifier, Sink::Storage::uidFromKey(key), revision, mFolderAdaptorFactory->createAdaptor(entity));
            auto folderName = folder.getProperty("name").toString();
            //TODO handle non toplevel folders
            auto path = mMaildirPath + "/" + folderName;
            Trace() << "Creating a new folder: " << path;
            KPIM::Maildir maildir(path, false);
            maildir.create();
            recordRemoteId(ENTITY_TYPE_FOLDER, folder.identifier(), path.toUtf8(), synchronizationTransaction);
        } else if (operation == Sink::Operation_Removal) {
            const auto uid = Sink::Storage::uidFromKey(key);
            const auto remoteId = resolveLocalId(ENTITY_TYPE_FOLDER, uid, synchronizationTransaction);
            const auto path = remoteId;
            Trace() << "Removing a folder: " << path;
            KPIM::Maildir maildir(path, false);
            maildir.remove();
            removeRemoteId(ENTITY_TYPE_FOLDER, uid, remoteId, synchronizationTransaction);
        } else if (operation == Sink::Operation_Modification) {
            Warning() << "Folder modifications are not implemented";
        } else {
            Warning() << "Unkown operation" << operation;
        }
    } else if (type == ENTITY_TYPE_MAIL) {
        if (operation == Sink::Operation_Creation) {
            const Sink::ApplicationDomain::Mail mail(mResourceInstanceIdentifier, Sink::Storage::uidFromKey(key), revision, mMailAdaptorFactory->createAdaptor(entity));
            const auto remoteId = getFilePathFromMimeMessagePath(mail.getMimeMessagePath());
            Trace() << "Creating a new mail." << remoteId;
            if (remoteId.isEmpty()) {
                Warning() << "Failed to create mail: " << remoteId;
                return KAsync::error<void>(1, "Failed to create mail.");
            } else {
                Trace() << "Mail created: " << remoteId;
                recordRemoteId(ENTITY_TYPE_MAIL, mail.identifier(), remoteId.toUtf8(), synchronizationTransaction);
            }
        } else if (operation == Sink::Operation_Removal) {
            const auto uid = Sink::Storage::uidFromKey(key);
            const auto remoteId = resolveLocalId(ENTITY_TYPE_MAIL, uid, synchronizationTransaction);
            Trace() << "Removing a mail: " << remoteId;
            QFile::remove(remoteId);
            removeRemoteId(ENTITY_TYPE_MAIL, uid, remoteId, synchronizationTransaction);
        } else if (operation == Sink::Operation_Modification) {
            const auto uid = Sink::Storage::uidFromKey(key);
            const auto remoteId = resolveLocalId(ENTITY_TYPE_MAIL, uid, synchronizationTransaction);
            Trace() << "Modifying a mail: " << remoteId;

            const Sink::ApplicationDomain::Mail mail(mResourceInstanceIdentifier, Sink::Storage::uidFromKey(key), revision, mMailAdaptorFactory->createAdaptor(entity));

            const auto filePath = getFilePathFromMimeMessagePath(mail.getMimeMessagePath());
            const auto maildirPath = KPIM::Maildir::getDirectoryFromFile(filePath);
            KPIM::Maildir maildir(maildirPath, false);

            const auto messagePathParts = filePath.split("/");
            if (messagePathParts.isEmpty()) {
                Warning() << "No message path available: " << remoteId;
                return KAsync::error<void>(1, "No message path available.");
            }
            const auto newIdentifier = messagePathParts.last();
            QString identifier;
            if (newIdentifier != KPIM::Maildir::getKeyFromFile(remoteId)) {
                //Remove the old mime message if it changed
                Trace() << "Removing old mime message: " << remoteId;
                QFile(remoteId).remove();
                identifier = newIdentifier;
            } else {
                //The identifier needs to contain the flags for changeEntryFlags to work
                Q_ASSERT(!remoteId.split('/').isEmpty());
                identifier = remoteId.split('/').last();
            }

            //get flags from
            KPIM::Maildir::Flags flags;
            if (!mail.getUnread()) {
                flags |= KPIM::Maildir::Seen;
            }
            if (mail.getImportant()) {
                flags |= KPIM::Maildir::Flagged;
            }

            const auto newRemoteId = maildir.changeEntryFlags(identifier, flags);
            updateRemoteId(ENTITY_TYPE_MAIL, uid, QString(maildirPath + "/cur/" + newRemoteId).toUtf8(), synchronizationTransaction);
        } else {
            Warning() << "Unkown operation" << operation;
        }
    }
    return KAsync::null<void>();
}

void MaildirResource::removeFromDisk(const QByteArray &instanceIdentifier)
{
    GenericResource::removeFromDisk(instanceIdentifier);
    Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".synchronization", Sink::Storage::ReadWrite).removeFromDisk();
}

KAsync::Job<void> MaildirResource::inspect(int inspectionType, const QByteArray &inspectionId, const QByteArray &domainType, const QByteArray &entityId, const QByteArray &property, const QVariant &expectedValue)
{
    auto synchronizationStore = QSharedPointer<Sink::Storage>::create(Sink::storageLocation(), mResourceInstanceIdentifier + ".synchronization", Sink::Storage::ReadOnly);
    auto synchronizationTransaction = synchronizationStore->createTransaction(Sink::Storage::ReadOnly);

    auto mainStore = QSharedPointer<Sink::Storage>::create(Sink::storageLocation(), mResourceInstanceIdentifier, Sink::Storage::ReadOnly);
    auto transaction = mainStore->createTransaction(Sink::Storage::ReadOnly);

    Trace() << "Inspecting " << inspectionType << domainType << entityId << property << expectedValue;

    if (domainType == ENTITY_TYPE_MAIL) {
        auto mainDatabase = Sink::Storage::mainDatabase(transaction, ENTITY_TYPE_MAIL);
        auto bufferAdaptor = getLatest(mainDatabase, entityId, *mMailAdaptorFactory);
        Q_ASSERT(bufferAdaptor);

        const Sink::ApplicationDomain::Mail mail(mResourceInstanceIdentifier, entityId, 0, bufferAdaptor);
        const auto filePath = getFilePathFromMimeMessagePath(mail.getMimeMessagePath());

        if (inspectionType == Sink::ResourceControl::Inspection::PropertyInspectionType) {
            if (property == "unread") {
                const auto flags = KPIM::Maildir::readEntryFlags(filePath.split('/').last());
                if (expectedValue.toBool() && (flags & KPIM::Maildir::Seen)) {
                    return KAsync::error<void>(1, "Expected unread but couldn't find it.");
                }
                if (!expectedValue.toBool() && !(flags & KPIM::Maildir::Seen)) {
                    return KAsync::error<void>(1, "Expected read but couldn't find it.");
                }
                return KAsync::null<void>();
            }
            if (property == "subject") {
                KMime::Message *msg = new KMime::Message;
                msg->setHead(KMime::CRLFtoLF(KPIM::Maildir::readEntryHeadersFromFile(filePath)));
                msg->parse();

                if (msg->subject(true)->asUnicodeString() != expectedValue.toString()) {
                    return KAsync::error<void>(1, "Subject not as expected: " + msg->subject(true)->asUnicodeString());
                }
                return KAsync::null<void>();
            }
        }
        if (inspectionType == Sink::ResourceControl::Inspection::ExistenceInspectionType) {
            if (QFileInfo(filePath).exists() != expectedValue.toBool()) {
                return KAsync::error<void>(1, "Wrong file existence: " + filePath);
            }
        }
    }
    if (domainType == ENTITY_TYPE_FOLDER) {
        const auto remoteId = resolveLocalId(ENTITY_TYPE_FOLDER, entityId, synchronizationTransaction);
        auto mainDatabase = Sink::Storage::mainDatabase(transaction, ENTITY_TYPE_FOLDER);
        auto bufferAdaptor = getLatest(mainDatabase, entityId, *mMailAdaptorFactory);
        Q_ASSERT(bufferAdaptor);

        const Sink::ApplicationDomain::Folder folder(mResourceInstanceIdentifier, entityId, 0, bufferAdaptor);
        if (inspectionType == Sink::ResourceControl::Inspection::CacheIntegrityInspectionType) {
            if (!QDir(remoteId).exists()) {
                return KAsync::error<void>(1, "The directory is not existing: " + remoteId);
            }

            int expectedCount = 0;
            Index index("mail.index.folder", transaction);
            index.lookup(entityId, [&](const QByteArray &sinkId) {
                    expectedCount++;
            },
            [&](const Index::Error &error) {
                Warning() << "Error in index: " <<  error.message << property;
            });

            QDir dir(remoteId + "/cur");
            const QFileInfoList list = dir.entryInfoList(QDir::Files);
            if (list.size() != expectedCount) {
                return KAsync::error<void>(1, QString("Wrong number of files; found %1 instead of %2.").arg(list.size()).arg(expectedCount));
            }
            if (inspectionType == Sink::ResourceControl::Inspection::ExistenceInspectionType) {
                if (!remoteId.endsWith(folder.getName().toUtf8())) {
                    return KAsync::error<void>(1, "Wrong folder name: " + remoteId);
                }
                if (QDir(remoteId).exists() != expectedValue.toBool()) {
                    return KAsync::error<void>(1, "Wrong folder existence: " + remoteId);
                }
            }
        }
    }
    return KAsync::null<void>();
}

MaildirResourceFactory::MaildirResourceFactory(QObject *parent)
    : Sink::ResourceFactory(parent)
{

}

Sink::Resource *MaildirResourceFactory::createResource(const QByteArray &instanceIdentifier)
{
    return new MaildirResource(instanceIdentifier);
}

void MaildirResourceFactory::registerFacades(Sink::FacadeFactory &factory)
{
    factory.registerFacade<Sink::ApplicationDomain::Mail, MaildirResourceMailFacade>(PLUGIN_NAME);
    factory.registerFacade<Sink::ApplicationDomain::Folder, MaildirResourceFolderFacade>(PLUGIN_NAME);
}