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
|
/*
Copyright (c) 2016 Michael Bohlender <michael.bohlender@kdemail.net>
Copyright (c) 2016 Christian Mollekopf <mollekopf@kolabsys.com>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "composercontroller.h"
#include <settings/settings.h>
#include <KMime/Message>
#include <QVariant>
#include <QList>
#include <QDebug>
#include <QMimeDatabase>
#include <QUrlQuery>
#include <QFileInfo>
#include <QFile>
#include <sink/store.h>
#include <sink/log.h>
#include "identitiesmodel.h"
#include "recepientautocompletionmodel.h"
#include "mime/mailtemplates.h"
#include "mime/mailcrypto.h"
#include "async.h"
std::vector<GpgME::Key> &operator+=(std::vector<GpgME::Key> &list, const std::vector<GpgME::Key> &add)
{
list.insert(std::end(list), std::begin(add), std::end(add));
return list;
}
class IdentitySelector : public Selector {
public:
IdentitySelector(ComposerController &controller) : Selector(new IdentitiesModel), mController(controller)
{
}
void setCurrent(const QModelIndex &index) Q_DECL_OVERRIDE
{
if (index.isValid()) {
auto currentAccountId = index.data(IdentitiesModel::AccountId).toByteArray();
KMime::Types::Mailbox mb;
mb.setName(index.data(IdentitiesModel::Username).toString());
mb.setAddress(index.data(IdentitiesModel::Address).toString().toUtf8());
SinkLog() << "Setting current identity: " << mb.prettyAddress() << "Account: " << currentAccountId;
mController.setIdentity(mb);
mController.setAccountId(currentAccountId);
} else {
SinkWarning() << "No valid identity for index: " << index;
mController.clearIdentity();
mController.clearAccountId();
}
}
QVector<QByteArray> getAllAddresses()
{
QVector<QByteArray> list;
for (int i = 0; i < model()->rowCount(); i++) {
list << model()->data(model()->index(i, 0), IdentitiesModel::Address).toString().toUtf8();
}
return list;
}
private:
ComposerController &mController;
};
class RecipientCompleter : public Completer {
public:
RecipientCompleter() : Completer(new RecipientAutocompletionModel)
{
}
void setSearchString(const QString &s) {
static_cast<RecipientAutocompletionModel*>(model())->setFilter(s);
Completer::setSearchString(s);
}
};
class AddresseeController : public Kube::ListPropertyController
{
public:
QSet<QByteArray> mMissingKeys;
AddresseeController()
: Kube::ListPropertyController{{"name", "keyFound", "key"}}
{
QObject::connect(this, &Kube::ListPropertyController::added, this, [this] (const QByteArray &id, const QVariantMap &map) {
findKey(id, map.value("name").toString());
});
}
void findKey(const QByteArray &id, const QString &addressee)
{
mMissingKeys << id;
KMime::Types::Mailbox mb;
mb.fromUnicodeString(addressee);
SinkLog() << "Searching key for: " << mb.address();
asyncRun<std::vector<GpgME::Key>>(this, [mb] {
return MailCrypto::findKeys(QStringList{} << mb.address(), false, false, MailCrypto::OPENPGP);
},
[this, addressee, id](const std::vector<GpgME::Key> &keys) {
if (!keys.empty()) {
if (keys.size() > 1 ) {
SinkWarning() << "Found more than one key, encrypting to all of them.";
}
SinkLog() << "Found key: " << keys.front().primaryFingerprint();
setValue(id, "keyFound", true);
setValue(id, "key", QVariant::fromValue(keys));
mMissingKeys.remove(id);
setProperty("foundAllKeys", mMissingKeys.isEmpty());
} else {
SinkWarning() << "Failed to find key for recipient.";
}
});
}
void set(const QStringList &list)
{
for (const auto &email: list) {
add({{"name", email}});
}
}
};
class AttachmentController : public Kube::ListPropertyController
{
public:
AttachmentController()
: Kube::ListPropertyController{{"name", "filename", "content", "mimetype", "description", "iconname", "url", "inline"}}
{
QObject::connect(this, &Kube::ListPropertyController::added, this, [this] (const QByteArray &id, const QVariantMap &map) {
auto url = map.value("url").toUrl();
setAttachmentProperties(id, url);
});
}
void setAttachmentProperties(const QByteArray &id, const QUrl &url)
{
QMimeDatabase db;
auto mimeType = db.mimeTypeForUrl(url);
if (mimeType.name() == QLatin1String("inode/directory")) {
qWarning() << "Can't deal with directories yet.";
} else {
if (!url.isLocalFile()) {
qWarning() << "Cannot attach remote file: " << url;
return;
}
QFileInfo fileInfo(url.toLocalFile());
if (!fileInfo.exists()) {
qWarning() << "The file doesn't exist: " << url;
}
QFile file{fileInfo.filePath()};
file.open(QIODevice::ReadOnly);
const auto data = file.readAll();
QVariantMap map;
map.insert("filename", fileInfo.fileName());
map.insert("mimetype", mimeType.name().toLatin1());
map.insert("filename", fileInfo.fileName().toLatin1());
map.insert("inline", false);
map.insert("iconname", mimeType.iconName());
map.insert("url", url);
map.insert("content", data);
setValues(id, map);
}
}
};
ComposerController::ComposerController()
: Kube::Controller(),
controller_to{new AddresseeController},
controller_cc{new AddresseeController},
controller_bcc{new AddresseeController},
controller_attachments{new AttachmentController},
action_send{new Kube::ControllerAction{this, &ComposerController::send}},
action_saveAsDraft{new Kube::ControllerAction{this, &ComposerController::saveAsDraft}},
mRecipientCompleter{new RecipientCompleter},
mIdentitySelector{new IdentitySelector{*this}}
{
QObject::connect(this, &ComposerController::identityChanged, &ComposerController::findPersonalKey);
}
void ComposerController::findPersonalKey()
{
auto identity = getIdentity();
SinkLog() << "Looking for personal key for: " << identity.address();
asyncRun<std::vector<GpgME::Key>>(this, [=] {
return MailCrypto::findKeys(QStringList{} << identity.address(), true);
},
[this](const std::vector<GpgME::Key> &keys) {
if (keys.empty()) {
SinkWarning() << "Failed to find a personal key.";
} else if (keys.size() > 1) {
SinkWarning() << "Found multiple keys, using all of them.";
}
setPersonalKeys(QVariant::fromValue(keys));
setFoundPersonalKeys(!keys.empty());
});
}
void ComposerController::clear()
{
Controller::clear();
//Reapply account and identity from selection
mIdentitySelector->reapplyCurrentIndex();
//FIXME implement in Controller::clear instead
toController()->clear();
ccController()->clear();
bccController()->clear();
}
Completer *ComposerController::recipientCompleter() const
{
return mRecipientCompleter.data();
}
Selector *ComposerController::identitySelector() const
{
return mIdentitySelector.data();
}
static void applyAddresses(const KMime::Types::Mailbox::List &list, std::function<void(const QByteArray &, const QByteArray &)> callback)
{
for (const auto &to : list) {
callback(to.address(), to.name().toUtf8());
}
}
static void applyAddresses(const QStringList &list, std::function<void(const QByteArray &, const QByteArray &)> callback)
{
KMime::Types::Mailbox::List mailboxes;
for (const auto &s : list) {
KMime::Types::Mailbox mb;
mb.fromUnicodeString(s);
mailboxes << mb;
}
applyAddresses(mailboxes, callback);
}
static QStringList getStringListFromAddresses(const KMime::Types::Mailbox::List &s)
{
QStringList list;
applyAddresses(s, [&](const QByteArray &addrSpec, const QByteArray &displayName) {
if (displayName.isEmpty()) {
list << QString{addrSpec};
} else {
list << QString("%1 <%2>").arg(QString{displayName}).arg(QString{addrSpec});
}
});
return list;
}
void ComposerController::addAttachmentPart(KMime::Content *partToAttach)
{
QVariantMap map;
if (partToAttach->contentType()->mimeType() == "multipart/digest" ||
partToAttach->contentType()->mimeType() == "message/rfc822") {
// if it is a digest or a full message, use the encodedContent() of the attachment,
// which already has the proper headers
map.insert("content", partToAttach->encodedContent());
} else {
map.insert("content", partToAttach->decodedContent());
}
map.insert("mimetype", partToAttach->contentType()->mimeType());
QMimeDatabase db;
auto mimeType = db.mimeTypeForName(partToAttach->contentType()->mimeType());
map.insert("iconname", mimeType.iconName());
if (partToAttach->contentDescription(false)) {
map.insert("description", partToAttach->contentDescription()->asUnicodeString());
}
QString name;
QString filename;
if (partToAttach->contentType(false)) {
if (partToAttach->contentType()->hasParameter(QStringLiteral("name"))) {
name = partToAttach->contentType()->parameter(QStringLiteral("name"));
}
}
if (partToAttach->contentDisposition(false)) {
filename = partToAttach->contentDisposition()->filename();
map.insert("inline", partToAttach->contentDisposition()->disposition() == KMime::Headers::CDinline);
}
if (name.isEmpty() && !filename.isEmpty()) {
name = filename;
}
if (filename.isEmpty() && !name.isEmpty()) {
filename = name;
}
if (!filename.isEmpty()) {
map.insert("filename", filename);
}
if (!name.isEmpty()) {
map.insert("name", name);
}
attachmentsController()->add(map);
}
void ComposerController::setMessage(const KMime::Message::Ptr &msg)
{
static_cast<AddresseeController*>(toController())->set(getStringListFromAddresses(msg->to(true)->mailboxes()));
static_cast<AddresseeController*>(ccController())->set(getStringListFromAddresses(msg->cc(true)->mailboxes()));
static_cast<AddresseeController*>(bccController())->set(getStringListFromAddresses(msg->bcc(true)->mailboxes()));
setSubject(msg->subject(true)->asUnicodeString());
bool isHtml = false;
const auto body = MailTemplates::body(msg, isHtml);
setHtmlBody(isHtml);
setBody(body);
//TODO use ObjecTreeParser to get encrypted attachments as well
foreach (const auto &att, msg->attachments()) {
addAttachmentPart(att);
}
setExistingMessage(msg);
}
void ComposerController::loadMessage(const QVariant &message, bool loadAsDraft)
{
using namespace Sink;
using namespace Sink::ApplicationDomain;
Query query(*message.value<Mail::Ptr>());
query.request<Mail::MimeMessage>();
Store::fetchOne<Mail>(query).then([this, loadAsDraft](const Mail &mail) {
setExistingMail(mail);
const auto mailData = KMime::CRLFtoLF(mail.getMimeMessage());
if (!mailData.isEmpty()) {
KMime::Message::Ptr mail(new KMime::Message);
mail->setContent(mailData);
mail->parse();
if (loadAsDraft) {
setMessage(mail);
} else {
//Find all personal email addresses to exclude from reply
KMime::Types::AddrSpecList me;
auto list = static_cast<IdentitySelector*>(mIdentitySelector.data())->getAllAddresses();
for (const auto &a : list) {
KMime::Types::Mailbox mb;
mb.setAddress(a);
me << mb.addrSpec();
}
MailTemplates::reply(mail, [this] (const KMime::Message::Ptr &reply) {
//We assume reply
setMessage(reply);
}, me);
}
} else {
qWarning() << "Retrieved empty message";
}
}).exec();
}
void ComposerController::recordForAutocompletion(const QByteArray &addrSpec, const QByteArray &displayName)
{
if (auto model = static_cast<RecipientAutocompletionModel*>(recipientCompleter()->model())) {
model->addEntry(addrSpec, displayName);
}
}
std::vector<GpgME::Key> ComposerController::getRecipientKeys()
{
std::vector<GpgME::Key> keys;
{
const auto list = toController()->getList<std::vector<GpgME::Key>>("key");
for (const auto &l: list) {
keys.insert(std::end(keys), std::begin(l), std::end(l));
}
}
{
const auto list = ccController()->getList<std::vector<GpgME::Key>>("key");
for (const auto &l: list) {
keys.insert(std::end(keys), std::begin(l), std::end(l));
}
}
{
const auto list = bccController()->getList<std::vector<GpgME::Key>>("key");
for (const auto &l: list) {
keys.insert(std::end(keys), std::begin(l), std::end(l));
}
}
return keys;
}
KMime::Message::Ptr ComposerController::assembleMessage()
{
auto toAddresses = toController()->getList<QString>("name");
auto ccAddresses = ccController()->getList<QString>("name");
auto bccAddresses = bccController()->getList<QString>("name");
applyAddresses(toAddresses + ccAddresses + bccAddresses, [&](const QByteArray &addrSpec, const QByteArray &displayName) {
recordForAutocompletion(addrSpec, displayName);
});
QList<Attachment> attachments;
attachmentsController()->traverse([&](const QVariantMap &value) {
attachments << Attachment{
value["name"].toString(),
value["filename"].toString(),
value["mimetype"].toByteArray(),
value["inline"].toBool(),
value["content"].toByteArray()
};
});
std::vector<GpgME::Key> signingKeys;
if (getSign()) {
signingKeys = getPersonalKeys().value<std::vector<GpgME::Key>>();
}
std::vector<GpgME::Key> encryptionKeys;
if (getEncrypt()) {
//Encrypt to self so we can read the sent message
encryptionKeys += getPersonalKeys().value<std::vector<GpgME::Key>>();
encryptionKeys += getRecipientKeys();
}
return MailTemplates::createMessage(mExistingMessage, toAddresses, ccAddresses, bccAddresses, getIdentity(), getSubject(), getBody(), getHtmlBody(), attachments, signingKeys, encryptionKeys);
}
void ComposerController::send()
{
auto message = assembleMessage();
if (!message) {
SinkWarning() << "Failed to assemble the message.";
return;
}
auto accountId = getAccountId();
//SinkLog() << "Sending a mail: " << *this;
using namespace Sink;
using namespace Sink::ApplicationDomain;
Q_ASSERT(!accountId.isEmpty());
Query query;
query.containsFilter<SinkResource::Capabilities>(ResourceCapabilities::Mail::transport);
query.filter<SinkResource::Account>(accountId);
auto job = Store::fetchAll<SinkResource>(query)
.then([=](const QList<SinkResource::Ptr> &resources) {
if (!resources.isEmpty()) {
auto resourceId = resources[0]->identifier();
SinkLog() << "Sending message via resource: " << resourceId;
Mail mail(resourceId);
mail.setMimeMessage(message->encodedContent(true));
return Store::create(mail)
.then<void>([=] {
//Trigger a sync, but don't wait for it.
Store::synchronize(Sink::SyncScope{}.resourceFilter(resourceId)).exec();
});
}
SinkWarning() << "Failed to find a mailtransport resource";
return KAsync::error<void>(0, "Failed to find a MailTransport resource.");
})
.then([&] (const KAsync::Error &) {
SinkLog() << "Message was sent: ";
emit done();
});
run(job);
}
void ComposerController::saveAsDraft()
{
SinkLog() << "Save as draft";
const auto accountId = getAccountId();
auto existingMail = getExistingMail();
auto message = assembleMessage();
if (!message) {
SinkWarning() << "Failed to assemble the message.";
return;
}
using namespace Sink;
using namespace Sink::ApplicationDomain;
auto job = [&] {
if (existingMail.identifier().isEmpty()) {
SinkLog() << "Creating a new draft" << existingMail.identifier();
Query query;
query.containsFilter<SinkResource::Capabilities>(ResourceCapabilities::Mail::drafts);
query.filter<SinkResource::Account>(accountId);
return Store::fetchOne<SinkResource>(query)
.then([=](const SinkResource &resource) {
Mail mail(resource.identifier());
mail.setDraft(true);
mail.setMimeMessage(message->encodedContent(true));
return Store::create(mail);
})
.onError([] (const KAsync::Error &error) {
SinkWarning() << "Error while creating draft: " << error.errorMessage;
});
} else {
SinkLog() << "Modifying an existing mail" << existingMail.identifier();
existingMail.setDraft(true);
existingMail.setMimeMessage(message->encodedContent(true));
return Store::modify(existingMail);
}
}();
job = job.then([&] (const KAsync::Error &) {
emit done();
});
run(job);
}
|