mailutil.cpp 14.9 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
31
32
33
34
35
36
37
38
39
/*******************************************************************************
**
** Filename   : util
** Created on : 03 April, 2005
** Copyright  : (c) 2005 Till Adam
** Email      : <adam@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.
**
**   It 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
**
**   In addition, as a special exception, the copyright holders give
**   permission to link the code of this program with any edition of
**   the Qt library by Trolltech AS, Norway (or with modified versions
**   of Qt that use the same license as Qt), and distribute linked
**   combinations including the two.  You must obey the GNU General
**   Public License in all respects for all of the code used other than
**   Qt.  If you modify this file, you may extend this exception to
**   your version of the file, but you are not obligated to do so.  If
**   you do not wish to do so, delete this exception statement from
**   your version.
**
*******************************************************************************/

#include "mailutil.h"
Laurent Montel's avatar
Laurent Montel committed
40
#include "mailutil_p.h"
41
42
43
44

#include "mailcommon_debug.h"
#include "calendarinterface.h"
#include "job/expirejob.h"
45
#include "folder/foldersettings.h"
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
#include "pop3settings.h"
#include "kernel/mailkernel.h"
#include "filter/dialog/filteractionmissingargumentdialog.h"

#include "mailimporter/filterbalsa.h"
#include "mailimporter/filterevolution.h"
#include "mailimporter/filterevolution_v2.h"
#include "mailimporter/filterevolution_v3.h"
#include "mailimporter/filterclawsmail.h"
#include "mailimporter/filtersylpheed.h"
#include "mailimporter/filterthunderbird.h"
#include "mailimporter/filteropera.h"
#include "mailimporter/filtericedove.h"
#include "mailimporter/othermailerutil.h"

#include <MessageCore/StringUtil>

#include <MessageComposer/MessageHelper>

#include <AgentManager>
#include <entitymimetypefiltermodel.h>
#include <EntityTreeModel>
#include <ItemFetchJob>
#include <ItemFetchScope>
#include <Akonadi/KMime/MessageParts>
#include <AkonadiCore/NewMailNotifierAttribute>

#include <KMime/KMimeMessage>

#include <KColorScheme>
#include <KDBusServiceStarter>
#include <KJob>
#include <KIO/JobUiDelegate>
#include <collectionpage/attributes/expirecollectionattribute.h>

OrgKdeAkonadiPOP3SettingsInterface *MailCommon::Util::createPop3SettingsInterface(
    const QString &ident)
{
    return
        new OrgKdeAkonadiPOP3SettingsInterface(
Laurent Montel's avatar
Laurent Montel committed
86
        QLatin1String("org.freedesktop.Akonadi.Resource.") + ident, QStringLiteral("/Settings"), QDBusConnection::sessionBus());
87
88
89
90
91
92
93
94
95
96
97
98
99
100
}

bool MailCommon::Util::isVirtualCollection(const Akonadi::Collection &collection)
{
    return MailCommon::Util::isVirtualCollection(collection.resource());
}

bool MailCommon::Util::isVirtualCollection(const QString &resource)
{
    return resource == QLatin1String("akonadi_search_resource");
}

bool MailCommon::Util::isLocalCollection(const QString &resource)
{
Laurent Montel's avatar
Laurent Montel committed
101
102
103
    return resource.contains(QStringLiteral("akonadi_mbox_resource"))
           || resource.contains(QStringLiteral("akonadi_maildir_resource"))
           || resource.contains(QStringLiteral("akonadi_mixedmaildir_resource"));
104
105
106
107
108
109
}

QString MailCommon::Util::fullCollectionPath(const Akonadi::Collection &collection)
{
    QString fullPath;

Laurent Montel's avatar
Laurent Montel committed
110
111
    QModelIndex idx
        = Akonadi::EntityTreeModel::modelIndexForCollection(KernelIf->collectionModel(), collection);
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    if (!idx.isValid()) {
        return fullPath;
    }

    fullPath = idx.data().toString();
    idx = idx.parent();
    while (idx != QModelIndex()) {
        fullPath = idx.data().toString() + QLatin1Char('/') + fullPath;
        idx = idx.parent();
    }
    return fullPath;
}

bool MailCommon::Util::showJobErrorMessage(KJob *job)
{
    if (job->error()) {
Laurent Montel's avatar
Laurent Montel committed
128
129
        if (auto uidelegate = static_cast<KIO::Job *>(job)->ui()) {
            uidelegate->showErrorMessage();
130
131
132
133
134
135
136
137
138
139
140
        } else {
            qCDebug(MAILCOMMON_LOG) << " job->errorString() :" << job->errorString();
        }
        return true;
    }
    return false;
}

Akonadi::AgentInstance::List MailCommon::Util::agentInstances(bool excludeMailDispacher)
{
    Akonadi::AgentInstance::List relevantInstances;
Laurent Montel's avatar
Laurent Montel committed
141
142
    const Akonadi::AgentInstance::List agentList = Akonadi::AgentManager::self()->instances();
    for (const Akonadi::AgentInstance &instance : agentList) {
143
144
        const QStringList capabilities(instance.type().capabilities());
        if (instance.type().mimeTypes().contains(KMime::Message::mimeType())) {
Laurent Montel's avatar
Laurent Montel committed
145
146
147
            if (capabilities.contains(QStringLiteral("Resource"))
                && !capabilities.contains(QStringLiteral("Virtual"))
                && !capabilities.contains(QStringLiteral("MailTransport"))) {
148
                relevantInstances << instance;
Laurent Montel's avatar
Laurent Montel committed
149
150
            } else if (!excludeMailDispacher
                       && instance.identifier() == QLatin1String("akonadi_maildispatcher_agent")) {
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
                relevantInstances << instance;
            }
        }
    }
    return relevantInstances;
}

uint MailCommon::Util::folderIdentity(const Akonadi::Item &item)
{
    uint id = 0;
    if (item.isValid() && item.parentCollection().isValid()) {
        Akonadi::Collection col = item.parentCollection();
        if (col.resource().isEmpty()) {
            col = parentCollectionFromItem(item);
        }
Laurent Montel's avatar
Laurent Montel committed
166
167
        const QSharedPointer<FolderSettings> fd
            = FolderSettings::forCollection(col, false);
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

        id = fd->identity();
    }
    return id;
}

static QModelIndex indexBelow(QAbstractItemModel *model, const QModelIndex &current)
{
    // if we have children, return first child
    if (model->rowCount(current) > 0) {
        return model->index(0, 0, current);
    }

    // if we have siblings, return next sibling
    const QModelIndex parent = model->parent(current);
    const QModelIndex sibling = model->index(current.row() + 1, 0, parent);

    if (sibling.isValid()) {   // found valid sibling
        return sibling;
    }

    if (!parent.isValid()) {   // our parent is the tree root and we have no siblings
        return QModelIndex(); // we reached the bottom of the tree
    }

    // We are the last child, the next index to check is our uncle, parent's first sibling
    const QModelIndex parentsSibling = parent.sibling(parent.row() + 1, 0);
    if (parentsSibling.isValid()) {
        return parentsSibling;
    }

    // iterate over our parents back to root until we find a parent with a valid sibling
    QModelIndex currentParent = parent;
    QModelIndex grandParent = model->parent(currentParent);
    while (currentParent.isValid()) {
        // check if the parent has children except from us
        if (model->rowCount(grandParent) > currentParent.row() + 1) {
Laurent Montel's avatar
Laurent Montel committed
205
206
            const QModelIndex index
                = indexBelow(model, model->index(currentParent.row() + 1, 0, grandParent));
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
            if (index.isValid()) {
                return index;
            }
        }

        currentParent = grandParent;
        grandParent = model->parent(currentParent);
    }

    return QModelIndex(); // nothing found -> end of tree
}

static QModelIndex lastChildOfModel(QAbstractItemModel *model, const QModelIndex &current)
{
    if (model->rowCount(current) == 0) {
        return current;
    }

    return lastChildOfModel(model, model->index(model->rowCount(current) - 1, 0, current));
}

static QModelIndex indexAbove(QAbstractItemModel *model, const QModelIndex &current)
{
    const QModelIndex parent = model->parent(current);

    if (current.row() == 0) {
        // we have no previous siblings -> our parent is the next item above us
        return parent;
    }

    // find previous sibling
    const QModelIndex previousSibling = model->index(current.row() - 1, 0, parent);

    // the item above us is the last child (or grandchild, or grandgrandchild... etc)
    // of our previous sibling
    return lastChildOfModel(model, previousSibling);
}

Laurent Montel's avatar
Laurent Montel committed
245
246
QModelIndex MailCommon::Util::nextUnreadCollection(QAbstractItemModel *model, const QModelIndex &current, SearchDirection direction, bool (*ignoreCollectionCallback)(
                                                       const Akonadi::Collection &collection))
247
248
249
250
251
252
253
254
255
256
257
258
259
260
{
    QModelIndex index = current;
    while (true) {
        if (direction == MailCommon::Util::ForwardSearch) {
            index = indexBelow(model, index);
        } else if (direction == MailCommon::Util::BackwardSearch) {
            index = indexAbove(model, index);
        }

        if (!index.isValid()) {   // reach end or top of the model
            return QModelIndex();
        }

        // check if the index is a collection
Laurent Montel's avatar
Laurent Montel committed
261
262
        const Akonadi::Collection collection
            = index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
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

        if (collection.isValid()) {
            // check if it is unread
            if (collection.statistics().unreadCount() > 0) {
                if (ignoreCollectionCallback && ignoreCollectionCallback(collection)) {
                    continue;
                }
                if (!ignoreNewMailInFolder(collection)) {
                    return index; // we found the next unread collection
                }
            }
        }
    }

    return QModelIndex(); // no unread collection found
}

bool MailCommon::Util::ignoreNewMailInFolder(const Akonadi::Collection &collection)
{
    if (collection.hasAttribute<Akonadi::NewMailNotifierAttribute>()) {
        if (collection.attribute<Akonadi::NewMailNotifierAttribute>()->ignoreNewMail()) {
            return true;
        }
    }
    return false;
}

Akonadi::Collection MailCommon::Util::parentCollectionFromItem(const Akonadi::Item &item)
{
    return updatedCollection(item.parentCollection());
}

QString MailCommon::Util::realFolderPath(const QString &path)
{
    QString realPath(path);
    realPath.remove(QStringLiteral(".directory"));
    realPath.replace(QLatin1String("/."), QStringLiteral("/"));
    if (!realPath.isEmpty() && (realPath.at(0) == QLatin1Char('.'))) {
        realPath.remove(0, 1);   //remove first "."
    }
    return realPath;
}

QColor MailCommon::Util::defaultQuotaColor()
{
    KColorScheme scheme(QPalette::Active, KColorScheme::View);
    return scheme.foreground(KColorScheme::NegativeText).color();
}

void MailCommon::Util::expireOldMessages(const Akonadi::Collection &collection, bool immediate)
{
    ScheduledExpireTask *task = new ScheduledExpireTask(collection, immediate);
    KernelIf->jobScheduler()->registerTask(task);
}

Akonadi::Collection MailCommon::Util::updatedCollection(const Akonadi::Collection &col)
{
    const QModelIndex idx = Akonadi::EntityTreeModel::modelIndexForCollection(KernelIf->collectionModel(), col);
    const Akonadi::Collection collection = idx.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
    return collection;
}

Akonadi::Collection::Id MailCommon::Util::convertFolderPathToCollectionId(const QString &folder)
{
    Akonadi::Collection::Id newFolderId = -1;
    bool exactPath = false;
    Akonadi::Collection::List lst = FilterActionMissingCollectionDialog::potentialCorrectFolders(folder, exactPath);
    if (lst.count() == 1 && exactPath) {
        newFolderId = lst.at(0).id();
    } else {
        QPointer<FilterActionMissingCollectionDialog> dlg = new FilterActionMissingCollectionDialog(lst, QString(), folder);
        if (dlg->exec()) {
            newFolderId = dlg->selectedCollection().id();
        }
        delete dlg;
    }
    return newFolderId;
}

QString MailCommon::Util::convertFolderPathToCollectionStr(const QString &folder)
{
    Akonadi::Collection::Id newFolderId = MailCommon::Util::convertFolderPathToCollectionId(folder);
    if (newFolderId == -1) {
        return QString();
    }
    return QString::number(newFolderId);
}

bool MailCommon::Util::foundMailer()
{
Laurent Montel's avatar
Laurent Montel committed
353
354
355
356
357
358
359
360
361
362
363
364
365
    const QStringList lst = {
        MailImporter::FilterEvolution::defaultSettingsPath(),
        MailImporter::FilterEvolution_v2::defaultSettingsPath(),
        MailImporter::FilterEvolution_v3::defaultSettingsPath(),
        MailImporter::FilterBalsa::defaultSettingsPath(),
        MailImporter::FilterClawsMail::defaultSettingsPath(),
        MailImporter::FilterOpera::defaultSettingsPath(),
        MailImporter::FilterSylpheed::defaultSettingsPath(),
        MailImporter::FilterThunderbird::defaultSettingsPath(),
        MailImporter::OtherMailerUtil::trojitaDefaultPath(),
        MailImporter::FilterIcedove::defaultSettingsPath(),
        MailImporter::OtherMailerUtil::gearyDefaultPath()
    };
Laurent Montel's avatar
Laurent Montel committed
366
367

    for (const QString &path : lst) {
368
369
370
371
372
373
374
375
376
377
        QDir directory(path);
        if (directory.exists()) {
            return true;
        }
    }
    return false;
}

MailCommon::ExpireCollectionAttribute *MailCommon::Util::expirationCollectionAttribute(const Akonadi::Collection &collection, bool &mustDeleteExpirationAttribute)
{
Laurent Montel's avatar
Laurent Montel committed
378
    MailCommon::ExpireCollectionAttribute *attr = nullptr;
379
380
381
382
383
384
    if (collection.hasAttribute<MailCommon::ExpireCollectionAttribute>()) {
        attr = collection.attribute<MailCommon::ExpireCollectionAttribute>();
        mustDeleteExpirationAttribute = false;
    } else {
        attr = new MailCommon::ExpireCollectionAttribute();
        KConfigGroup configGroup(KernelIf->config(),
385
                                 MailCommon::FolderSettings::configGroupName(collection));
386
387
388
389
390
391
392

        if (configGroup.hasKey("ExpireMessages")) {
            attr->setAutoExpire(configGroup.readEntry("ExpireMessages", false));
            attr->setReadExpireAge(configGroup.readEntry("ReadExpireAge", 3));
            attr->setReadExpireUnits((MailCommon::ExpireCollectionAttribute::ExpireUnits)configGroup.readEntry("ReadExpireUnits", (int)MailCommon::ExpireCollectionAttribute::ExpireMonths));
            attr->setUnreadExpireAge(configGroup.readEntry("UnreadExpireAge", 12));
            attr->setUnreadExpireUnits((MailCommon::ExpireCollectionAttribute::ExpireUnits)configGroup.readEntry("UnreadExpireUnits", (int)MailCommon::ExpireCollectionAttribute::ExpireNever));
Laurent Montel's avatar
Laurent Montel committed
393
394
395
            attr->setExpireAction(configGroup.readEntry("ExpireAction", "Delete") == QLatin1String("Move")
                                  ? MailCommon::ExpireCollectionAttribute::ExpireMove
                                  : MailCommon::ExpireCollectionAttribute::ExpireDelete);
396
397
398
399
400
401
402
            attr->setExpireToFolderId(configGroup.readEntry("ExpireToFolder", -1));
        }

        mustDeleteExpirationAttribute = true;
    }
    return attr;
}