summaryrefslogtreecommitdiff
path: root/lib/kolabaccount.cpp
blob: 5925fc5e6837968aca802df3174c34e2f9b9dbbb (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
/*
 * Copyright (C) 2012  Christian Mollekopf <mollekopf@kolabsys.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "kolabaccount.h"
#include "sessionfactory.h"
#include "jobs/setupkolabfoldersjob.h"
#include "jobs/fetchmessagesjob.h"
#include "jobs/createkolabfolderjob.h"
#include <kimap/session.h>
#include <kimap/logoutjob.h>
#include <kimap/appendjob.h>
#include <kimap/createjob.h>
#include <kimap/deletejob.h>
#include <kimap/listjob.h>
#include <kimap/capabilitiesjob.h>
#include <kimap/namespacejob.h>
#include <kimap/storejob.h>
#include <kimap/selectjob.h>
#include <kimap/expungejob.h>
#include <kimap/setmetadatajob.h>
#include <errorhandler.h>
#include <kolabdefinitions.h>
#include <formathelpers.h>
#include <kolabobject.h>


KolabAccount::KolabAccount(QObject* parent)
:   QObject(parent),
    mSession(0),
    mEncryptionMode(KIMAP::LoginJob::TlsV1),
    mAuthenticationMode(KIMAP::LoginJob::Plain),
    mDryRun(false),
    mWipeTargetFolders(false),
    mVersion(Kolab::KolabV3)
{

}

KolabAccount::~KolabAccount()
{
    if (mSession) {
        mSession->close();
        mSession->deleteLater();
    }
}

void KolabAccount::setVersion(Kolab::Version version)
{
    mVersion = version;
}

void KolabAccount::setHost(const QString& host, qint16 port)
{
    mHost = host;
    mPort = port;
}

void KolabAccount::setCredentials(const QString& username, const QString& pw, const QString &authorizationName)
{
    mUsername = username;
    mPw = pw;
    mAuthorizationName = authorizationName;
}

QString KolabAccount::getUsername() const
{
    return mUsername;
}

void KolabAccount::setEncryptionMode(KIMAP::LoginJob::EncryptionMode encryptionMode)
{
    mEncryptionMode = encryptionMode;
}

void KolabAccount::setAuthenticationMode(KIMAP::LoginJob::AuthenticationMode authMode)
{
    mAuthenticationMode = authMode;
}

void KolabAccount::setDryRun(bool enable)
{
    mDryRun = enable;
}

void KolabAccount::setWipeTargetFolders(bool enable)
{
    mWipeTargetFolders = enable;
}

bool KolabAccount::init()
{
    if (mDryRun) {
        return true;
    }
    if (mSession) {
        return false;
    }
    mSession = createSession( mHost, mPort, this );
    KIMAP::LoginJob *loginJob = new KIMAP::LoginJob( mSession );
    Debug() << mUsername << mAuthorizationName << mPw;
    if (mAuthorizationName != mUsername) {
        loginJob->setAuthorizationName(mAuthorizationName);
    }
    loginJob->setUserName( mUsername );
    loginJob->setPassword( mPw );
    loginJob->setEncryptionMode( mEncryptionMode );
    loginJob->setAuthenticationMode( mAuthenticationMode );
    loginJob->exec();
    
    if ( loginJob->error() ) {
        Error() << "Failed to login: " << loginJob->errorString();
        mSession->close();
        return false;
    }
    Debug() << "authentication successful";
    
    KIMAP::CapabilitiesJob *capabilities = new KIMAP::CapabilitiesJob(mSession);
    capabilities->exec();
    mCapabilities = capabilities->capabilities();
    
    if ( mCapabilities.contains( "NAMESPACE" ) ) {
        KIMAP::NamespaceJob *nsJob = new KIMAP::NamespaceJob( mSession );
        nsJob->exec();
        mPersonalNamespaces = nsJob->personalNamespaces();
        mExcludedNamespaces = nsJob->userNamespaces();
        mExcludedNamespaces.append(nsJob->sharedNamespaces());
//         Debug() << "personal namespaces";
//         foreach (const KIMAP::MailBoxDescriptor &desc, nsJob->personalNamespaces()) {
//             Debug() << desc.name;
//         }
//         foreach (const KIMAP::MailBoxDescriptor &desc, nsJob->userNamespaces()) {
//             Debug() << desc.name;
//         }
//         foreach (const KIMAP::MailBoxDescriptor &desc, nsJob->sharedNamespaces()) {
//             Debug() << desc.name;
//         }
    }
    return true;
}

const char* FlagRecent2 = "\\Recent";



KMime::Message::Ptr KolabAccount::writeObject(const Object &obj)
{
    const QString productId("migration-utility");
    KMime::Message::Ptr msg;
    if (obj.object.canConvert<KMime::Message::Ptr>()) {
        msg = obj.object.value<KMime::Message::Ptr>();
    } else if (obj.object.canConvert<KCalCore::Incidence::Ptr>()) {
        msg = Kolab::KolabObjectWriter::writeIncidence(obj.object.value<KCalCore::Incidence::Ptr>(), mVersion, productId);
    } else if (obj.object.canConvert<KABC::Addressee>()) {
        msg = Kolab::KolabObjectWriter::writeContact(obj.object.value<KABC::Addressee>(), mVersion, productId);
    } else if (obj.object.canConvert<KABC::ContactGroup>()) {
        msg = Kolab::KolabObjectWriter::writeDistlist(obj.object.value<KABC::ContactGroup>(), mVersion, productId);
    } else if (obj.object.canConvert<Note>()) {
        msg = Kolab::KolabObjectWriter::writeNote(obj.object.value<Note>().msg, mVersion, productId);
    } else if (obj.object.canConvert<Dictionary>()) {
        const Dictionary dict = obj.object.value<Dictionary>();
        msg = Kolab::KolabObjectWriter::writeDictionary(dict.dict, dict.lang, mVersion, productId);
    } else {
        Error() << "Type not handled";
    }
    return msg;
}

KJob* KolabAccount::appendObject(Object obj, const QString& folder)
{
    if (mDryRun) {
        Debug() << "append object in folder: " << folder;
        return 0;
    }
    if (!mFolders.contains(folder, Qt::CaseInsensitive)) {
        Error() << "failed to find target folder: " << folder;
        qDebug() << mFolders;
        return 0;
    }

    KMime::Message::Ptr message = writeObject(obj);
    if (!message) {
        Error() << "got empty message";
        return 0;
    }

    Q_ASSERT(mSession);
    KIMAP::AppendJob *job = new KIMAP::AppendJob( mSession );
    job->setMailBox( folder );
    job->setContent( message->encodedContent( true ) );
    //The Recent flag is a special case which is not allowed in the append command
    obj.flags.removeAll(QByteArray(FlagRecent2));
    job->setFlags( obj.flags );
    return job;
}

void KolabAccount::appendObjectSync(Object obj, const QString& folder)
{
    KJob *job = appendObject(obj, folder);
    if (!job) {
        return;
    }
    job->exec();
    Debug() << "appended object in folder: " << folder;
    if (job->error()) {
        Error() << job->errorString();
    }
}

KJob *KolabAccount::logout()
{
    if (!mSession) {
        return 0;
    }
    return new KIMAP::LogoutJob(mSession);
}

const char* FlagDeleted2 = "\\Deleted";

void KolabAccount::cleanAccount()
{
    if (!mWipeTargetFolders) {
        Debug() << "wiping of target folders disabled";
        return;
    }
    if (mDryRun) {
        Debug() << "wiping account";
        return;
    }
    Q_ASSERT(mSession);
    KIMAP::ListJob *listJob = new KIMAP::ListJob(mSession);
    listJob->setOption(KIMAP::ListJob::IncludeUnsubscribed);
    listJob->setQueriedNamespaces(mPersonalNamespaces);
    QObject::connect( listJob, SIGNAL(mailBoxesReceived(QList<KIMAP::MailBoxDescriptor>,QList<QList<QByteArray> >)),
                      this, SLOT(mailBoxesReceived(QList<KIMAP::MailBoxDescriptor>,QList<QList<QByteArray> >)));
    listJob->exec();
    if (listJob->error()) {
        Error() << listJob->errorString();
    }
    foreach (const KIMAP::MailBoxDescriptor &desc, mMailboxes) {
        bool skip = false;
        foreach(const KIMAP::MailBoxDescriptor &excluded, mExcludedNamespaces) {
            if (desc.name.contains(excluded.name)) {
                skip = true;
                break;
            }
        }
        if (skip) {
            continue;
        }

        KIMAP::SelectJob *selectJob = new KIMAP::SelectJob(mSession);
        selectJob->setMailBox(desc.name);
        selectJob->exec();
        if (selectJob->error()) {
            Error() << selectJob->errorString();
        }
        const int messageCount = selectJob->messageCount();
        Debug() << "removing folder: " << desc.name << messageCount;
        if (mDryRun) {
            continue;
        }

        if (messageCount > 0) {
            KIMAP::StoreJob *storeJob = new KIMAP::StoreJob(mSession);
            storeJob->setMode(KIMAP::StoreJob::AppendFlags);
            storeJob->setFlags(KIMAP::MessageFlags() << FlagDeleted2);
            storeJob->setSequenceSet( KIMAP::ImapSet( 1, messageCount ) );
            storeJob->exec();
            if (storeJob->error()) {
                Error() << storeJob->errorString();
            }

            KIMAP::ExpungeJob *expungeJob = new KIMAP::ExpungeJob(mSession);
            expungeJob->exec();
            if (expungeJob->error()) {
                Error() << expungeJob->errorString();
            }
        }
        if (desc.name.contains(QLatin1String("inbox"), Qt::CaseInsensitive)) {
            continue;
        }
        
        KIMAP::DeleteJob *deleteJob = new KIMAP::DeleteJob(mSession);
        Debug() << "deleting: " << desc.name;
        deleteJob->setMailBox(desc.name);
        deleteJob->exec();
        if (deleteJob->error()) {
            Error() << deleteJob->errorString();
        }
    }
    mFolders.clear();
    mFolders.append(QLatin1String("inbox"));

    //logging out and logging in again seems to help with the "NO Mailbox is locked" problem when creating folders afterwards.
    KJob *logoutJob = logout();
    if (logoutJob) {
        logoutJob->exec();
    }
    mSession->close();
    mSession->deleteLater();
    mSession = 0;
    init();
}

void KolabAccount::mailBoxesReceived(const QList<KIMAP::MailBoxDescriptor> &descriptors, const QList< QList< QByteArray > > &/* flags */)
{
    mMailboxes.append(descriptors);
}

/*
 * This can fail with "NO Mailbox is locked" if the we deleted a selected folder before:
 * http://lists.andrew.cmu.edu/pipermail/info-cyrus/2011-June/035049.html
 */
void KolabAccount::createFolder(const QString &name, const QByteArray &annotation)
{
    if (mFolders.contains(name, Qt::CaseInsensitive)) {
        Warning() << "folder already exists: " << name;
        return;
    }
    if (mDryRun) {
        Debug() << "creating folder: " << name << annotation;
        return;
    }
    CreateKolabFolderJob *createJob = new CreateKolabFolderJob(name, annotation, QByteArray(), CreateKolabFolderJob::capablitiesFromString(mCapabilities), mSession, this);
    createJob->exec();
    if (createJob->error()) {
        Error() << createJob->errorString();
        return;
    }
    Debug() << "created folder: " << name;
    mFolders.append(name);
}

void KolabAccount::createFolder(const QString& name, Kolab::FolderType folderType)
{
    createFolder(name, QString::fromStdString(Kolab::folderAnnotation(folderType)).toLatin1());
}

void KolabAccount::setupFolders()
{
    if (mDryRun) {
        Debug() << "setup default folders";
        return;
    }
    Q_ASSERT(mSession);
    SetupKolabFoldersJob *setupJob = new SetupKolabFoldersJob(mCapabilities, QString(), mSession, this);
    setupJob->setKolabFolders(QStringList() << KOLAB_FOLDER_TYPE_CONTACT << KOLAB_FOLDER_TYPE_EVENT << KOLAB_FOLDER_TYPE_TASK << KOLAB_FOLDER_TYPE_JOURNAL << KOLAB_FOLDER_TYPE_NOTE << KOLAB_FOLDER_TYPE_CONFIGURATION);
    setupJob->exec();
    if (setupJob->error()) {
        Error() << setupJob->errorString();
    }
    mFolders.append("inbox");
    foreach (const QString &folder, setupJob->createdFolders().values()) {
        mFolders.append(folder);
    }
    KIMAP::SelectJob *selectJob = new KIMAP::SelectJob(mSession);
    selectJob->setMailBox(QString());
    //TODO internationalize folder names
    //TODO the suffixes should go in the private namespace
    createFolder("Drafts", KOLAB_FOLDER_TYPE_MAIL KOLAB_FOLDER_TYPE_DRAFT_SUFFIX);
    createFolder("Sent", KOLAB_FOLDER_TYPE_MAIL KOLAB_FOLDER_TYPE_SENT_SUFFIX);
    createFolder("Trash", KOLAB_FOLDER_TYPE_MAIL KOLAB_FOLDER_TYPE_TRASH_SUFFIX);
}

QList<Object> KolabAccount::getObjects(const QString& folder)
{
//     Debug() << folder;
    Q_ASSERT(mSession);
    FetchMessagesJob *fetchJob = new FetchMessagesJob(folder, mSession, this);
    fetchJob->exec();
    Debug() << fetchJob->getMessages().size();
    QList<Object> messages;
    foreach (const KMime::Message::Ptr &msg, fetchJob->getMessages()) {
        Object obj;
        obj.object = QVariant::fromValue(msg);
        obj.flags = fetchJob->getFlags(msg);
        messages.append(obj);
    }
    return messages;
}

QStringList KolabAccount::lookupFolderList()
{
//     Debug() << "lookupFolderList" << mHost << mPort << mUsername << mPw;
    init();
    mMailboxes.clear();
    
    Q_ASSERT(mSession);
    KIMAP::ListJob *listJob = new KIMAP::ListJob(mSession);
    listJob->setOption(KIMAP::ListJob::IncludeUnsubscribed);
    listJob->setQueriedNamespaces(mPersonalNamespaces);
    QObject::connect( listJob, SIGNAL(mailBoxesReceived(QList<KIMAP::MailBoxDescriptor>,QList<QList<QByteArray> >)),
                      this, SLOT(mailBoxesReceived(QList<KIMAP::MailBoxDescriptor>,QList<QList<QByteArray> >)));
    listJob->exec();
    Debug() << "found " << mMailboxes.size();
    
    QStringList mailboxes;
    foreach (const KIMAP::MailBoxDescriptor &descriptor, mMailboxes) {
        mailboxes.append(descriptor.name);
    }
    return mailboxes;
}

void KolabAccount::setRegextrans(const QStringList &regextrans)
{
    foreach (const QString &transformation, regextrans) {
        if (!transformation.startsWith("s/") || !transformation.endsWith("/")) {
            Warning() << "invalid transformation: " << transformation;
            continue;
        }
        QString trans = transformation.mid(2, transformation.length() - 3);
        const int separator = trans.indexOf("/");
        const QString searchString = trans.left(separator);
        const QString replaceString = trans.right(separator+1);
        Debug() << "s/" << searchString << "/" << replaceString;
        mRegextrans.insert(searchString, replaceString);
    }
}

QString KolabAccount::applyTargetFolderTransformations(const QString &folder) const
{
    QString newName(folder);
    foreach (const QString &searchString, mRegextrans.keys()) {
        if (folder.contains(searchString)) {
            return mRegextrans.value(searchString);
        }
    }
    return newName;
}