filtermanager.cpp 24.6 KB
Newer Older
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
//
/* Copyright: before 2012: missing, see KMail copyrights
 * Copyright (C) 2012 Andras Mantia <amantia@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 "filtermanager.h"

#include <AkonadiCore/agentmanager.h>
#include <AkonadiCore/changerecorder.h>
#include <AkonadiCore/collectionfetchjob.h>
#include <AkonadiCore/collectionfetchscope.h>
#include <AkonadiCore/itemfetchjob.h>
#include <AkonadiCore/itemfetchscope.h>
#include <AkonadiCore/itemmodifyjob.h>
#include <AkonadiCore/itemmovejob.h>
#include <AkonadiCore/itemdeletejob.h>
31
32
#include <AkonadiCore/EntityTreeModel>
#include <AkonadiCore/EntityMimeTypeFilterModel>
33
34
35
36
37
38
39
40
41
42
43
#include <Akonadi/KMime/MessageParts>
#include <kconfig.h>
#include <kconfiggroup.h>
#include "mailfilteragent_debug.h"
#include <KLocalizedString>
#include <KNotification>
#include <QIcon>
#include <kmime/kmime_message.h>
#include <MailCommon/FilterImporterExporter>
#include <MailCommon/FilterLog>
#include <MailCommon/MailFilter>
44
#include <MailCommon/MailKernel>
45
46
47
48
49
50

// other headers
#include <algorithm>
#include <errno.h>
#include <KSharedConfig>
#include <QLocale>
51

52
53
54
55
56
57
using namespace MailCommon;

class FilterManager::Private
{
public:
    Private(FilterManager *qq)
Laurent Montel's avatar
Laurent Montel committed
58
59
60
61
        : q(qq)
        , mRequiredPartsBasedOnAll(SearchRule::Envelope)
        , mTotalProgressCount(0)
        , mCurrentProgressCount(0)
Laurent Montel's avatar
Laurent Montel committed
62
        , mInboundFiltersExist(false)
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    {
    }

    void itemsFetchJobForFilterDone(KJob *job);
    void itemFetchJobForFilterDone(KJob *job);
    void moveJobResult(KJob *);
    void modifyJobResult(KJob *);
    void deleteJobResult(KJob *);
    void slotItemsFetchedForFilter(const Akonadi::Item::List &items);
    void showNotification(const QString &errorMsg, const QString &jobErrorString);

    bool isMatching(const Akonadi::Item &item, const MailCommon::MailFilter *filter);
    void beginFiltering(const Akonadi::Item &item) const;
    void endFiltering(const Akonadi::Item &item) const;
    bool atLeastOneFilterAppliesTo(const QString &accountId) const;
    bool atLeastOneIncomingFilterAppliesTo(const QString &accountId) const;
    FilterManager *q;
Laurent Montel's avatar
Laurent Montel committed
80
    QVector<MailCommon::MailFilter *> mFilters;
81
    QMap<QString, SearchRule::RequiredPart> mRequiredParts;
Laurent Montel's avatar
Laurent Montel committed
82
    SearchRule::RequiredPart mRequiredPartsBasedOnAll;
Laurent Montel's avatar
Laurent Montel committed
83
84
    int mTotalProgressCount = 0;
    int mCurrentProgressCount = 0;
Laurent Montel's avatar
Laurent Montel committed
85
86
    bool mInboundFiltersExist = false;
    bool mAllFoldersFiltersExist = false;
87
88
89
90
91
92
93
94
95
};

void FilterManager::Private::slotItemsFetchedForFilter(const Akonadi::Item::List &items)
{
    FilterManager::FilterSet filterSet = FilterManager::Inbound;
    if (q->sender()->property("filterSet").isValid()) {
        filterSet = static_cast<FilterManager::FilterSet>(q->sender()->property("filterSet").toInt());
    }

Laurent Montel's avatar
Laurent Montel committed
96
    QVector<MailFilter *> listMailFilters;
97
98
99
    if (q->sender()->property("listFilters").isValid()) {
        const QStringList listFilters = q->sender()->property("listFilters").toStringList();
        //TODO improve it
Laurent Montel's avatar
Laurent Montel committed
100
        for (const QString &filterId : listFilters) {
Laurent Montel's avatar
Laurent Montel committed
101
            for (MailCommon::MailFilter *filter : qAsConst(mFilters)) {
102
103
104
105
106
107
108
109
110
111
112
113
114
115
                if (filter->identifier() == filterId) {
                    listMailFilters << filter;
                    break;
                }
            }
        }
    }

    if (listMailFilters.isEmpty()) {
        listMailFilters = mFilters;
    }

    bool needsFullPayload = q->sender()->property("needsFullPayload").toBool();

Laurent Montel's avatar
Laurent Montel committed
116
    for (const Akonadi::Item &item : qAsConst(items)) {
117
118
119
        ++mCurrentProgressCount;

        if ((mTotalProgressCount > 0) && (mCurrentProgressCount != mTotalProgressCount)) {
Laurent Montel's avatar
Laurent Montel committed
120
121
            const QString statusMsg
                = i18n("Filtering message %1 of %2", mCurrentProgressCount, mTotalProgressCount);
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
            Q_EMIT q->progressMessage(statusMsg);
            Q_EMIT q->percent(mCurrentProgressCount * 100 / mTotalProgressCount);
        } else {
            Q_EMIT q->percent(0);
        }

        const bool filterResult = q->process(listMailFilters, item, needsFullPayload, filterSet);

        if (mCurrentProgressCount == mTotalProgressCount) {
            mTotalProgressCount = 0;
            mCurrentProgressCount = 0;
        }

        if (!filterResult) {
            Q_EMIT q->filteringFailed(item);
            // something went horribly wrong (out of space?)
            //CommonKernel->emergencyExit( i18n( "Unable to process messages: " ) + QString::fromLocal8Bit( strerror( errno ) ) );
        }
    }
}

void FilterManager::Private::itemsFetchJobForFilterDone(KJob *job)
{
    if (job->error()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Error while fetching items. " << job->error() << job->errorString();
    }
}

void FilterManager::Private::itemFetchJobForFilterDone(KJob *job)
{
    if (job->error()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Error while fetching item. " << job->error() << job->errorString();
        return;
    }

    const Akonadi::ItemFetchJob *fetchJob = qobject_cast<Akonadi::ItemFetchJob *>(job);

    const Akonadi::Item::List items = fetchJob->items();
    if (items.isEmpty()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Error while fetching item: item not found";
        return;
    }

    const QString resourceId = fetchJob->property("resourceId").toString();
    bool needsFullPayload = q->requiredPart(resourceId) != SearchRule::Envelope;

    if (job->property("filterId").isValid()) {
        const QString filterId = job->property("filterId").toString();

        // find correct filter object
Laurent Montel's avatar
Laurent Montel committed
172
        MailCommon::MailFilter *wantedFilter = nullptr;
Laurent Montel's avatar
Laurent Montel committed
173
        for (MailCommon::MailFilter *filter : qAsConst(mFilters)) {
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
            if (filter->identifier() == filterId) {
                wantedFilter = filter;
                break;
            }
        }

        if (!wantedFilter) {
            qCCritical(MAILFILTERAGENT_LOG) << "Cannot find filter object with id" << filterId;
            return;
        }

        if (!q->process(items.first(), needsFullPayload, wantedFilter)) {
            Q_EMIT q->filteringFailed(items.first());
        }
    } else {
        const FilterManager::FilterSet set = static_cast<FilterManager::FilterSet>(job->property("filterSet").toInt());

        if (!q->process(items.first(), needsFullPayload, set, !resourceId.isEmpty(), resourceId)) {
            Q_EMIT q->filteringFailed(items.first());
        }
    }
}

void FilterManager::Private::moveJobResult(KJob *job)
{
    if (job->error()) {
        const Akonadi::ItemMoveJob *movejob = qobject_cast<Akonadi::ItemMoveJob *>(job);
        if (movejob) {
            qCCritical(MAILFILTERAGENT_LOG) << "Error while moving items. " << job->error() << job->errorString()
                                            << " to destinationCollection.id() :" << movejob->destinationCollection().id();
        } else {
            qCCritical(MAILFILTERAGENT_LOG) << "Error while moving items. " << job->error() << job->errorString();
        }
        //Laurent: not real info and when we have 200 errors it's very long to click all the time on ok.
        showNotification(i18n("Error applying mail filter move"), job->errorString());
    }
}

void FilterManager::Private::deleteJobResult(KJob *job)
{
    if (job->error()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Error while delete items. " << job->error() << job->errorString();
        showNotification(i18n("Error applying mail filter delete"), job->errorString());
    }
}

void FilterManager::Private::modifyJobResult(KJob *job)
{
    if (job->error()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Error while modifying items. " << job->error() << job->errorString();
        showNotification(i18n("Error applying mail filter modifications"), job->errorString());
    }
}

void FilterManager::Private::showNotification(const QString &errorMsg, const QString &jobErrorString)
{
    KNotification *notify = new KNotification(QStringLiteral("mailfilterjoberror"));
    notify->setComponentName(QStringLiteral("akonadi_mailfilter_agent"));
232
    notify->setIconName(QStringLiteral("view-filter"));
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
    notify->setText(errorMsg + QLatin1Char('\n') + jobErrorString);
    notify->sendEvent();
}

bool FilterManager::Private::isMatching(const Akonadi::Item &item, const MailCommon::MailFilter *filter)
{
    bool result = false;
    if (FilterLog::instance()->isLogging()) {
        QString logText(i18n("<b>Evaluating filter rules:</b> "));
        logText.append(filter->pattern()->asString());
        FilterLog::instance()->add(logText, FilterLog::PatternDescription);
    }

    if (filter->pattern()->matches(item)) {
        if (FilterLog::instance()->isLogging()) {
            FilterLog::instance()->add(i18n("<b>Filter rules have matched.</b>"),
                                       FilterLog::PatternResult);
        }

        result = true;
    }

    return result;
}

void FilterManager::Private::beginFiltering(const Akonadi::Item &item) const
{
    if (FilterLog::instance()->isLogging()) {
        FilterLog::instance()->addSeparator();
Laurent Montel's avatar
Laurent Montel committed
262
263
264
265
266
267
268
269
270
271
        if (item.hasPayload<KMime::Message::Ptr>()) {
            KMime::Message::Ptr msg = item.payload<KMime::Message::Ptr>();
            const QString subject = msg->subject()->asUnicodeString();
            const QString from = msg->from()->asUnicodeString();
            const QDateTime dateTime = msg->date()->dateTime();
            const QString date = QLocale().toString(dateTime, QLocale::LongFormat);
            const QString logText(i18n("<b>Begin filtering on message \"%1\" from \"%2\" at \"%3\" :</b>",
                                       subject, from, date));
            FilterLog::instance()->add(logText, FilterLog::PatternDescription);
        }
272
273
274
    }
}

Laurent Montel's avatar
Laurent Montel committed
275
void FilterManager::Private::endFiltering(const Akonadi::Item & /*item*/) const
276
277
278
279
280
{
}

bool FilterManager::Private::atLeastOneFilterAppliesTo(const QString &accountId) const
{
Laurent Montel's avatar
Laurent Montel committed
281
    for (const MailCommon::MailFilter *filter : qAsConst(mFilters)) {
282
283
284
285
286
287
288
289
290
291
        if (filter->applyOnAccount(accountId)) {
            return true;
        }
    }

    return false;
}

bool FilterManager::Private::atLeastOneIncomingFilterAppliesTo(const QString &accountId) const
{
Laurent Montel's avatar
Laurent Montel committed
292
    for (const MailCommon::MailFilter *filter : qAsConst(mFilters)) {
293
294
295
296
297
298
299
300
301
        if (filter->applyOnInbound() && filter->applyOnAccount(accountId)) {
            return true;
        }
    }

    return false;
}

FilterManager::FilterManager(QObject *parent)
Laurent Montel's avatar
Laurent Montel committed
302
303
    : QObject(parent)
    , d(new Private(this))
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
{
    readConfig();
}

FilterManager::~FilterManager()
{
    clear();

    delete d;
}

void FilterManager::clear()
{
    qDeleteAll(d->mFilters);
    d->mFilters.clear();
}

void FilterManager::readConfig()
{
    KSharedConfig::Ptr config = KSharedConfig::openConfig(); // use akonadi_mailfilter_agentrc
    config->reparseConfiguration();
    clear();

    QStringList emptyFilters;
    d->mFilters = FilterImporterExporter::readFiltersFromConfig(config, emptyFilters);
    d->mRequiredParts.clear();

    d->mRequiredPartsBasedOnAll = SearchRule::Envelope;
    if (!d->mFilters.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
333
334
        const Akonadi::AgentInstance::List agents = Akonadi::AgentManager::self()->instances();
        for (const Akonadi::AgentInstance &agent : agents) {
335
336
            const QString id = agent.identifier();

337
            auto it = std::max_element(d->mFilters.constBegin(), d->mFilters.constEnd(),
Laurent Montel's avatar
Laurent Montel committed
338
                                       [id](MailCommon::MailFilter *lhs, MailCommon::MailFilter *rhs) {
Laurent Montel's avatar
Laurent Montel committed
339
340
                return lhs->requiredPart(id) < rhs->requiredPart(id);
            });
341
342
343
344
345
            d->mRequiredParts[id] = (*it)->requiredPart(id);
            d->mRequiredPartsBasedOnAll = qMax(d->mRequiredPartsBasedOnAll, d->mRequiredParts[id]);
        }
    }
    // check if at least one filter is to be applied on inbound mail
346
347
348

    for (auto i = d->mFilters.cbegin(), e = d->mFilters.cend();
         i != e && (!d->mInboundFiltersExist || !d->mAllFoldersFiltersExist);
Laurent Montel's avatar
Laurent Montel committed
349
         ++i) {
350
351
352
353
354
355
356
        if ((*i)->applyOnInbound()) {
            d->mInboundFiltersExist = true;
        }
        if ((*i)->applyOnAllFoldersInbound()) {
            d->mAllFoldersFiltersExist = true;
        }
    }
357
358
359
360
361
362

    Q_EMIT filterListUpdated();
}

void FilterManager::mailCollectionRemoved(const Akonadi::Collection &collection)
{
Laurent Montel's avatar
Laurent Montel committed
363
364
    QVector<MailCommon::MailFilter *>::const_iterator end(d->mFilters.constEnd());
    for (QVector<MailCommon::MailFilter *>::const_iterator it = d->mFilters.constBegin();
Laurent Montel's avatar
Laurent Montel committed
365
         it != end; ++it) {
366
367
368
369
        (*it)->folderRemoved(collection, Akonadi::Collection());
    }
}

370
371
void FilterManager::agentRemoved(const QString &identifier)
{
Laurent Montel's avatar
Laurent Montel committed
372
373
    QVector<MailCommon::MailFilter *>::const_iterator end(d->mFilters.constEnd());
    for (QVector<MailCommon::MailFilter *>::const_iterator it = d->mFilters.constBegin();
Laurent Montel's avatar
Laurent Montel committed
374
         it != end; ++it) {
Laurent Montel's avatar
Laurent Montel committed
375
        (*it)->agentRemoved(identifier);
376
377
378
    }
}

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
void FilterManager::filter(const Akonadi::Item &item, FilterManager::FilterSet set, const QString &resourceId)
{
    Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(item, this);
    job->setProperty("filterSet", static_cast<int>(set));
    job->setProperty("resourceId", resourceId);
    SearchRule::RequiredPart requestedPart = requiredPart(resourceId);
    if (requestedPart == SearchRule::CompleteMessage) {
        job->fetchScope().fetchFullPayload(true);
    } else if (requestedPart == SearchRule::Header) {
        job->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Header, true);
    } else {
        job->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Envelope, true);
    }
    job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);

Laurent Montel's avatar
Laurent Montel committed
394
395
396
    connect(job, &Akonadi::ItemFetchJob::result, this, [this](KJob *job) {
        d->itemFetchJobForFilterDone(job);
    });
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
}

void FilterManager::filter(const Akonadi::Item &item, const QString &filterId, const QString &resourceId)
{
    Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(item, this);
    job->setProperty("filterId", filterId);

    SearchRule::RequiredPart requestedPart = requiredPart(resourceId);
    if (requestedPart == SearchRule::CompleteMessage) {
        job->fetchScope().fetchFullPayload(true);
    } else if (requestedPart == SearchRule::Header) {
        job->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Header, true);
    } else {
        job->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Envelope, true);
    }

    job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);

Laurent Montel's avatar
Laurent Montel committed
415
416
417
    connect(job, &Akonadi::ItemFetchJob::result, this, [this](KJob *job) {
        d->itemFetchJobForFilterDone(job);
    });
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
}

bool FilterManager::process(const Akonadi::Item &item, bool needsFullPayload, const MailFilter *filter)
{
    if (!filter) {
        return false;
    }

    if (!filter->isEnabled()) {
        return true;
    }

    if (!item.hasPayload<KMime::Message::Ptr>()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Filter is null or item doesn't have correct payload.";
        return false;
    }

    if (d->isMatching(item, filter)) {
        // do the actual filtering stuff
        d->beginFiltering(item);

        ItemContext context(item, needsFullPayload);

Laurent Montel's avatar
Laurent Montel committed
441
442
        bool stopIt = false;
        bool applyOnOutbound = false;
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
        if (filter->execActions(context, stopIt, applyOnOutbound) == MailCommon::MailFilter::CriticalError) {
            return false;
        }

        d->endFiltering(item);

        if (!processContextItem(context)) {
            return false;
        }
    }

    return true;
}

bool FilterManager::processContextItem(ItemContext context)
{
    const KMime::Message::Ptr msg = context.item().payload<KMime::Message::Ptr>();
    msg->assemble();

462
463
464
    auto col = Akonadi::EntityTreeModel::updatedCollection(MailCommon::Kernel::self()->kernelIf()->collectionModel(),
                                                           context.item().parentCollection());
    const bool itemCanDelete = (col.rights() & Akonadi::Collection::CanDeleteItem);
465
466
467
    if (context.deleteItem()) {
        if (itemCanDelete) {
            Akonadi::ItemDeleteJob *deleteJob = new Akonadi::ItemDeleteJob(context.item(), this);
Laurent Montel's avatar
Laurent Montel committed
468
469
470
            connect(deleteJob, &Akonadi::ItemDeleteJob::result, this, [this](KJob *job) {
                d->deleteJobResult(job);
            });
471
472
473
474
475
476
477
        } else {
            return false;
        }
    } else {
        if (context.moveTargetCollection().isValid() && context.item().storageCollectionId() != context.moveTargetCollection().id()) {
            if (itemCanDelete) {
                Akonadi::ItemMoveJob *moveJob = new Akonadi::ItemMoveJob(context.item(), context.moveTargetCollection(), this);
Laurent Montel's avatar
Laurent Montel committed
478
479
480
                connect(moveJob, &Akonadi::ItemMoveJob::result, this, [this](KJob *job) {
                    d->moveJobResult(job);
                });
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
            } else {
                return false;
            }
        }
        if (context.needsPayloadStore() || context.needsFlagStore()) {
            Akonadi::Item item = context.item();
            //the item might be in a new collection with a different remote id, so don't try to force on it
            //the previous remote id. Example: move to another collection on another resource => new remoteId, but our context.item()
            //remoteid still holds the old one. Without clearing it, we try to enforce that on the new location, which is
            //anything but good (and the server replies with "NO Only resources can modify remote identifiers"
            item.setRemoteId(QString());
            Akonadi::ItemModifyJob *modifyJob = new Akonadi::ItemModifyJob(item, this);
            modifyJob->disableRevisionCheck(); //no conflict handling for mails as no other process could change the mail body and we don't care about flag conflicts
            //The below is a safety check to ignore modifying payloads if it was not requested,
            //as in that case we might change the payload to an invalid one
            modifyJob->setIgnorePayload(!context.needsFullPayload());
Laurent Montel's avatar
Laurent Montel committed
497
498
499
            connect(modifyJob, &Akonadi::ItemModifyJob::result, this, [this](KJob *job) {
                d->modifyJobResult(job);
            });
500
501
502
503
504
505
        }
    }

    return true;
}

Laurent Montel's avatar
Laurent Montel committed
506
bool FilterManager::process(const QVector< MailFilter * > &mailFilters, const Akonadi::Item &item, bool needsFullPayload, FilterManager::FilterSet set, bool account, const QString &accountId)
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
{
    if (set == NoSet) {
        qCDebug(MAILFILTERAGENT_LOG) << "FilterManager: process() called with not filter set selected";
        return false;
    }

    if (!item.hasPayload<KMime::Message::Ptr>()) {
        qCCritical(MAILFILTERAGENT_LOG) << "Filter is null or item doesn't have correct payload.";
        return false;
    }

    bool stopIt = false;

    d->beginFiltering(item);

    ItemContext context(item, needsFullPayload);
Laurent Montel's avatar
Laurent Montel committed
523
    QVector<MailCommon::MailFilter *>::const_iterator end(mailFilters.constEnd());
524
525
526

    const bool applyOnOutbound = ((set & Outbound) || (set & BeforeOutbound));

Laurent Montel's avatar
Laurent Montel committed
527
    for (QVector<MailCommon::MailFilter *>::const_iterator it = mailFilters.constBegin();
Laurent Montel's avatar
Laurent Montel committed
528
         !stopIt && it != end; ++it) {
529
530
531
532
533
        if ((*it)->isEnabled()) {
            const bool inboundOk = ((set & Inbound) && (*it)->applyOnInbound());
            const bool outboundOk = ((set & Outbound) && (*it)->applyOnOutbound());
            const bool beforeOutboundOk = ((set & BeforeOutbound) && (*it)->applyBeforeOutbound());
            const bool explicitOk = ((set & Explicit) && (*it)->applyOnExplicit());
534
            const bool allFoldersOk = ((set & AllFolders) && (*it)->applyOnAllFoldersInbound());
Laurent Montel's avatar
Laurent Montel committed
535
            const bool accountOk = (!account || (*it)->applyOnAccount(accountId));
536

537
            if ((inboundOk && accountOk) || (allFoldersOk && accountOk) || outboundOk || beforeOutboundOk || explicitOk) {
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
                // filter is applicable

                if (d->isMatching(context.item(), *it)) {
                    // execute actions:
                    if ((*it)->execActions(context, stopIt, applyOnOutbound) == MailCommon::MailFilter::CriticalError) {
                        return false;
                    }
                }
            }
        }
    }

    d->endFiltering(item);
    if (!processContextItem(context)) {
        return false;
    }

    return true;
}

Laurent Montel's avatar
Laurent Montel committed
558
bool FilterManager::process(const Akonadi::Item &item, bool needsFullPayload, FilterSet set, bool account, const QString &accountId)
559
{
Laurent Montel's avatar
Laurent Montel committed
560
    return process(d->mFilters, item, needsFullPayload, set, account, accountId);
561
562
563
564
565
566
567
568
569
570
571
}

QString FilterManager::createUniqueName(const QString &name) const
{
    QString uniqueName = name;

    int counter = 0;
    bool found = true;

    while (found) {
        found = false;
572
        for (const MailCommon::MailFilter *filter : qAsConst(d->mFilters)) {
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
            if (!filter->name().compare(uniqueName)) {
                found = true;
                ++counter;
                uniqueName = name;
                uniqueName += QLatin1String(" (") + QString::number(counter)
                              + QLatin1String(")");
                break;
            }
        }
    }

    return uniqueName;
}

MailCommon::SearchRule::RequiredPart FilterManager::requiredPart(const QString &id) const
{
    if (id.isEmpty()) {
        return d->mRequiredPartsBasedOnAll;
    }
    return d->mRequiredParts.contains(id) ? d->mRequiredParts[id] : SearchRule::Envelope;
}

void FilterManager::dump() const
{
Laurent Montel's avatar
Laurent Montel committed
597
    for (const MailCommon::MailFilter *filter : qAsConst(d->mFilters)) {
598
599
600
        qCDebug(MAILFILTERAGENT_LOG) << filter->asString();
    }
}
Laurent Montel's avatar
Laurent Montel committed
601

Laurent Montel's avatar
Laurent Montel committed
602
void FilterManager::applySpecificFilters(const Akonadi::Item::List &selectedMessages, SearchRule::RequiredPart requiredPart, const QStringList &listFilters, FilterSet filterSet)
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
{
    Q_EMIT progressMessage(i18n("Filtering messages"));
    d->mTotalProgressCount = selectedMessages.size();
    d->mCurrentProgressCount = 0;

    Akonadi::ItemFetchJob *itemFetchJob = new Akonadi::ItemFetchJob(selectedMessages, this);
    if (requiredPart == SearchRule::CompleteMessage) {
        itemFetchJob->fetchScope().fetchFullPayload(true);
    } else if (requiredPart == SearchRule::Header) {
        itemFetchJob->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Header, true);
    } else {
        itemFetchJob->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Envelope, true);
    }

    itemFetchJob->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);
    itemFetchJob->setProperty("listFilters", QVariant::fromValue(listFilters));
619
    itemFetchJob->setProperty("filterSet", QVariant::fromValue(static_cast<int>(filterSet)));
620
621
    itemFetchJob->setProperty("needsFullPayload", requiredPart != SearchRule::Envelope);

Laurent Montel's avatar
Laurent Montel committed
622
623
624
625
626
627
    connect(itemFetchJob, &Akonadi::ItemFetchJob::itemsReceived, this, [this](const Akonadi::Item::List &lst) {
        d->slotItemsFetchedForFilter(lst);
    });
    connect(itemFetchJob, &Akonadi::ItemFetchJob::result, this, [this](KJob *job) {
        d->itemsFetchJobForFilterDone(job);
    });
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
}

void FilterManager::applyFilters(const Akonadi::Item::List &selectedMessages, FilterSet filterSet)
{
    Q_EMIT progressMessage(i18n("Filtering messages"));
    d->mTotalProgressCount = selectedMessages.size();
    d->mCurrentProgressCount = 0;

    Akonadi::ItemFetchJob *itemFetchJob = new Akonadi::ItemFetchJob(selectedMessages, this);
    SearchRule::RequiredPart requiredParts = requiredPart(QString());
    if (requiredParts == SearchRule::CompleteMessage) {
        itemFetchJob->fetchScope().fetchFullPayload(true);
    } else if (requiredParts == SearchRule::Header) {
        itemFetchJob->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Header, true);
    } else {
        itemFetchJob->fetchScope().fetchPayloadPart(Akonadi::MessagePart::Envelope, true);
    }

    itemFetchJob->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);
    itemFetchJob->setProperty("filterSet", QVariant::fromValue(static_cast<int>(filterSet)));
    itemFetchJob->setProperty("needsFullPayload", requiredParts != SearchRule::Envelope);

Laurent Montel's avatar
Laurent Montel committed
650
651
652
653
654
655
    connect(itemFetchJob, &Akonadi::ItemFetchJob::itemsReceived, this, [this](const Akonadi::Item::List &lst) {
        d->slotItemsFetchedForFilter(lst);
    });
    connect(itemFetchJob, &Akonadi::ItemFetchJob::result, this, [this](KJob *job) {
        d->itemsFetchJobForFilterDone(job);
    });
656
657
}

658
659
660
661
662
bool FilterManager::hasAllFoldersFilter() const
{
    return d->mAllFoldersFiltersExist;
}

663
#include "moc_filtermanager.cpp"