File indexing completed on 2024-11-17 04:51:14

0001 /*
0002   SPDX-FileCopyrightText: 2015-2024 Laurent Montel <montel@kde.org>
0003 
0004   SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "searchruledate.h"
0008 
0009 #include "filter/filterlog.h"
0010 using MailCommon::FilterLog;
0011 
0012 #include <KLocalizedString>
0013 #include <KMime/KMimeMessage>
0014 using namespace MailCommon;
0015 
0016 SearchRuleDate::SearchRuleDate(const QByteArray &field, Function func, const QString &contents)
0017     : SearchRule(field, func, contents)
0018 {
0019 }
0020 
0021 QString SearchRuleDate::informationAboutNotValidRules() const
0022 {
0023     return i18n("Date is not valid.");
0024 }
0025 
0026 bool SearchRuleDate::isEmpty() const
0027 {
0028     return !QDate::fromString(contents(), Qt::ISODate).isValid();
0029 }
0030 
0031 bool SearchRuleDate::matches(const Akonadi::Item &item) const
0032 {
0033     if (!item.hasPayload<KMime::Message::Ptr>()) {
0034         return false;
0035     }
0036     const auto msg = item.payload<KMime::Message::Ptr>();
0037 
0038     const QDate msgDate = msg->date()->dateTime().date();
0039     const QDate dateValue = QDate::fromString(contents(), Qt::ISODate);
0040     bool rc = matchesInternal(dateValue, msgDate);
0041     if (FilterLog::instance()->isLogging()) {
0042         QString msg = (rc ? QStringLiteral("<font color=#00FF00>1 = </font>") : QStringLiteral("<font color=#FF0000>0 = </font>"));
0043         msg += FilterLog::recode(asString());
0044         msg += QLatin1StringView(" ( <i>") + contents() + QLatin1StringView("</i> )"); // TODO change with locale?
0045         FilterLog::instance()->add(msg, FilterLog::RuleResult);
0046     }
0047     return rc;
0048 }
0049 
0050 bool SearchRuleDate::matchesInternal(QDate dateValue, QDate msgDate) const
0051 {
0052     switch (function()) {
0053     case SearchRule::FuncEquals:
0054         return dateValue == msgDate;
0055 
0056     case SearchRule::FuncNotEqual:
0057         return dateValue != msgDate;
0058 
0059     case FuncIsGreater:
0060         return msgDate > dateValue;
0061 
0062     case FuncIsLessOrEqual:
0063         return msgDate <= dateValue;
0064 
0065     case FuncIsLess:
0066         return msgDate < dateValue;
0067 
0068     case FuncIsGreaterOrEqual:
0069         return msgDate >= dateValue;
0070 
0071     default:;
0072     }
0073     return false;
0074 }
0075 
0076 SearchRule::RequiredPart SearchRuleDate::requiredPart() const
0077 {
0078     return SearchRule::Envelope;
0079 }
0080 
0081 void SearchRuleDate::addQueryTerms(Akonadi::SearchTerm &groupTerm, bool &emptyIsNotAnError) const
0082 {
0083     using namespace Akonadi;
0084     emptyIsNotAnError = false;
0085 
0086     const QDate date = QDate::fromString(contents(), Qt::ISODate);
0087     EmailSearchTerm term(EmailSearchTerm::HeaderOnlyDate, date, akonadiComparator());
0088     term.setIsNegated(isNegated());
0089     groupTerm.addSubTerm(term);
0090 }