Debian Codegraph @

Dekko/backend/mail/MessageBuilder.cpp

raw symbols SCIP
1 /* Copyright (C) 2016 - 2017 Dan Chapman <[email protected]>
2
3 This file is part of Dekko email client for Ubuntu devices
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of
8 the License or (at your option) version 3
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include "MessageBuilder.h"
19 #include <AccountConfiguration.h>
20 #include <QFileInfo>
21 #include <QDebug>
22 #include <QMimeType>
23 #include <QMimeDatabase>
24 #include <QStringBuilder>
25 #include <QUrlQuery>
26 #include <emailvalidator.h>
27 #include <Formatting.h>
28 #include <PolicyManager.h>
29 #include <SettingsPolicies.h>
30
31 MessageBuilder::MessageBuilder(QObject *parent) : QObject(parent),
32 m_to(Q_NULLPTR),m_cc(Q_NULLPTR), m_bcc(Q_NULLPTR), m_attachments(Q_NULLPTR), m_subject(Q_NULLPTR), m_internalSubject(Q_NULLPTR),
33 m_body(Q_NULLPTR), m_internalBody(Q_NULLPTR), m_identities(Q_NULLPTR), m_sourceStatus(QMailMessage::LocalOnly), m_mode(Mode::New),
34 m_replyType(ReplyType::Reply)
35 {
36 m_to = new QQmlObjectListModel<MailAddress>(this);
37 m_cc = new QQmlObjectListModel<MailAddress>(this);
38 m_bcc = new QQmlObjectListModel<MailAddress>(this);
39 m_attachments = new QQmlObjectListModel<Attachment>(this);
40 m_internalSubject = new QTextDocument(this);
41 m_internalBody = new QTextDocument(this);
42 emit modelsChanged();
43 }
44
45 QQuickTextDocument *MessageBuilder::subject() const
46 {
47 return m_subject;
48 }
49
50 QQuickTextDocument *MessageBuilder::body() const
51 {
52 return m_body;
53 }
54
55 QMailMessage MessageBuilder::message()
56 {
57 QMailMessage mail;
58 // TODO:
59 // http://code.qt.io/cgit/qt-labs/messagingframework.git/tree/examples/qtmail/emailcomposer.cpp#n752
60
61 if (m_lastDraftId.isValid()) {
62 mail.setId(m_lastDraftId);
63 }
64
65 IdentityWrapper *w = static_cast<IdentityWrapper *>(m_identities->selectedAccount());
66 Account *sender = static_cast<Account *>(w->get_account());
67 Identity *identity = static_cast<Identity *>(w->get_identity());
68 mail.setParentAccountId(sender->accountId());
69 mail.setDate(QMailTimeStamp::currentDateTime());
70 mail.setFrom(identity->fromAddress());
71 // If there is a replyTo for the identity add that now
72 if (!identity->get_replyTo().isEmpty()) {
73 mail.setReplyTo(QMailAddress(identity->get_name(), identity->get_replyTo()));
74 }
75
76 auto createAddressList = [](const QQmlObjectListModel<MailAddress> *model) -> QList<QMailAddress> {
77 QList<QMailAddress> addrList;
78 foreach(MailAddress *addr, model->toList()) {
79 addrList << addr->qMailAddress();
80 }
81 return addrList;
82 };
83
84 // append cc/bcc includes
85 // MailPolicy *policy = PolicyManager::instance()->mailPolicy(sender->accountId().toULongLong());
86 // if (policy) {
87 // QStringList ccInc = policy->ccIncludes().split(",");
88 // if (!ccInc.isEmpty()) {
89 // for( const QString &cc : ccInc) {
90 // if (EmailValidator::instance()->validate(cc.trimmed())) {
91 // addRecipient(Cc, cc.trimmed());
92 // }
93 // }
94 // }
95 // QStringList bccInc = policy->bccIncludes().split(",");
96 // if (!bccInc.isEmpty()) {
97 // for( const QString &bcc : ccInc) {
98 // if (EmailValidator::instance()->validate(bcc.trimmed())) {
99 // addRecipient(Bcc, bcc.trimmed());
100 // }
101 // }
102 // }
103 // }
104 mail.setTo(createAddressList(m_to));
105 if (!m_cc->isEmpty()) {
106 mail.setCc(createAddressList(m_cc));
107 }
108 if (!m_bcc->isEmpty()) {
109 mail.setBcc(createAddressList(m_bcc));
110 }
111 mail.setSubject(m_internalSubject->toPlainText());
112 QString plainTextBody = m_internalBody->toPlainText();
113 plainTextBody.append(QStringLiteral("\n\n-- \n%1").arg(identity->get_signature()));
114 QMailMessageContentType type(QByteArrayLiteral("text/plain; charset=UTF-8"));
115 // TODO: Do we want to always encode as QuotedPrintable it's efficient for ASCII text but becomes inefficient
116 // for non-ascii chars i.e QChar::unicode() > 127. SHould we iterate over all chars and decide based on that as QString
117 // doesn't provide an isAscii??
118 if (m_attachments->isEmpty()) {
119 mail.setBody(QMailMessageBody::fromData(plainTextBody, type, QMailMessageBody::QuotedPrintable));
120 } else {
121 QMailMessagePart bodyPart;
122 bodyPart.setBody(QMailMessageBody::fromData(plainTextBody, type, QMailMessageBody::QuotedPrintable));
123 mail.setMultipartType(QMailMessagePartContainer::MultipartMixed);
124 mail.appendPart(bodyPart);
125 foreach(Attachment *attachment, m_attachments->toList()) {
126 attachment->addToMessage(mail);
127 }
128 }
129 mail.setMessageType(QMailMessage::Email);
130
131 mail.setSize(mail.indicativeSize() * 1024);
132 mail.setStatus(QMailMessage::HasAttachments, false);
133
134 if (m_sourceStatus & QMailMessage::LocalOnly) {
135 mail.setStatus(QMailMessage::LocalOnly, true);
136 }
137 // Initial local storage location
138 mail.setParentFolderId(QMailFolder::LocalStorageFolderId);
139 // mark it as outgoing
140 mail.setStatus(QMailMessage::Outgoing, true);
141 // mark it as read
142 // mail.setStatus(QMailMessage::Read, true); hmm we actually want to show the count in the nav list
143 // In case we want to edit it or view it again inform the store
144 // that all the content is available
145 mail.setStatus(QMailMessage::ContentAvailable, true);
146 mail.setStatus(QMailMessage::PartialContentAvailable, true);
147
148 switch(m_mode) {
149 case New:
150 {
151 mail.setResponseType(QMailMessage::NoResponse);
152 break;
153 }
154 case Rply:
155 {
156 switch(m_replyType) {
157 case Reply:
158 case ReplyList:
159 {
160 mail.setResponseType(QMailMessage::Reply);
161 break;
162 }
163 case ReplyAll:
164 {
165 mail.setResponseType(QMailMessage::ReplyToAll);
166 break;
167 }
168 }
169 break;
170 }
171 case Fwd:
172 {
173 mail.setResponseType(QMailMessage::Forward);
174 break;
175 }
176 }
177
178 if (mail.responseType() == QMailMessage::Reply || mail.responseType() == QMailMessage::ReplyToAll) {
179 if (m_srcMessageId.isValid()) {
180 mail.setInResponseTo(m_srcMessageId);
181 QMailMessage srcMsg(m_srcMessageId);
182 QString refs = srcMsg.headerFieldText(QStringLiteral("References"));
183 if (refs.isEmpty()) {
184 // use In-Reply-To
185 refs = srcMsg.headerFieldText(QStringLiteral("In-Reply-To"));
186 }
187 QString precursorId(srcMsg.headerFieldText("Message-ID"));
188 if (!precursorId.isEmpty()) {
189 mail.setInReplyTo(precursorId);
190
191 if (!refs.isEmpty()) {
192 refs.append(' ');
193 }
194 refs.append(precursorId);
195 }
196 if (!refs.isEmpty()) {
197 mail.setHeaderField("References", refs);
198 }
199 }
200 }
201 return mail;
202 }
203
204 QObject *MessageBuilder::identities() const
205 {
206 return m_identities;
207 }
208
209 void MessageBuilder::setLastDraftId(const QMailMessageId &id)
210 {
211 if (id.isValid()) {
212 m_lastDraftId = id;
213 }
214 }
215
216 void MessageBuilder::buildResponse(const MessageBuilder::ReplyType &type, const QMailMessage &src)
217 {
218 if (!hasIdentities()) {
219 qFatal("No identities");
220 return;
221 }
222 // next select the identity to use
223 int identityIdx = m_identities->determinePreferredIdentity(src);
224 m_identities->setSelectedIndex(identityIdx);
225 // next build recipient lists
226 buildRecipientsLists(type, src);
227 // subject
228 const QString subject = Formatting::mangleReplySubject(src.subject().simplified());
229 if (m_subject == Q_NULLPTR) {
230 m_internalSubject->setPlainText(subject);
231 } else {
232 m_subject->textDocument()->setPlainText(subject);
233 }
234
235 // body
236 QString body;
237 if (src.multipartType() == QMailMessagePartContainer::MultipartNone) {
238 if (src.hasBody()) {
239 if (src.hasHtmlBody()) {
240 qDebug() << "IsHtml";
241 QTextDocument b;
242 b.setHtml(src.body().data());
243 body = b.toPlainText();
244 } else {
245 qDebug() << "IsPlaintTExt";
246 body = src.body().data();
247 }
248 }
249 } else {
250 // were a multipart
251 QMailMessagePart *part = Q_NULLPTR;
252 // Atm we prefer plaintext parts until we have an proper html editor
253 QMailMessagePartContainer *ptext = src.findPlainTextContainer();
254 if (ptext) {
255 // YAY!
256 part = static_cast<QMailMessagePart *>(ptext);
257 body = part->body().data();
258 } else {
259 QMailMessagePartContainer *htext = src.findHtmlContainer();
260 if (htext) {
261 part = static_cast<QMailMessagePart *>(htext);
262 QTextDocument b;
263 b.setHtml(part->body().data());
264 body = b.toPlainText();
265 }
266 }
267 }
268 QString replyHeader = tr("On %1, %2 wrote:\n").arg(src.date().toString(), src.from().name());
269 QString quotedBody = QStringLiteral("\n") + replyHeader + QStringList(Formatting::quoteBody(body.split("\n"))).join(QStringLiteral("\n"));
270
271 if (m_body == Q_NULLPTR) {
272 m_internalBody->setPlainText(quotedBody);
273 } else {
274 m_body->textDocument()->setPlainText(quotedBody);
275 }
276 // attachments ?? not for a reply!!!
277 m_mode = Mode::Rply;
278 m_replyType = type;
279 m_srcMessageId = src.id();
280 }
281
282 void MessageBuilder::buildForward(const MessageBuilder::ForwardType &type, const QMailMessage &src)
283 {
284 const QString subject = Formatting::mangleForwardSubject(src.subject().simplified());
285 if (m_subject == Q_NULLPTR) {
286 m_internalSubject->setPlainText(subject);
287 } else {
288 m_subject->textDocument()->setPlainText(subject);
289 }
290
291 QString srcBody = "";
292 bool useInlineBody(false);
293
294 if (type == MessageBuilder::ForwardType::Inline) {
295 // if message has a plaintext part then we forward it inline
296 if (src.hasPlainTextBody()) {
297 useInlineBody = true;
298 srcBody = src.body().data();
299 }
300
301 if (src.multipartType() == QMailMessage::MultipartAlternative || src.multipartType() == QMailMessage::MultipartMixed) {
302 QMailMessagePartContainer *ptext = src.findPlainTextContainer();
303 if (ptext) {
304 useInlineBody = true;
305 srcBody = static_cast<QMailMessagePart *>(ptext)->body().data();
306 }
307 }
308
309 // if srcBody is still empty then try to use html body
310 if (srcBody.isEmpty() && src.hasHtmlBody()) {
311 QMailMessagePartContainer *htext = src.findHtmlContainer();
312 if (htext) {
313 QMailMessagePart *part = static_cast<QMailMessagePart *>(htext);
314 QTextDocument b;
315 b.setHtml(part->body().data());
316 srcBody = b.toPlainText();
317 useInlineBody = true;
318 } else {
319 qDebug() << "src.hasHtmlBody() but src.findHtmlContainer() == null. That should never happen!?!";
320 }
321 }
322 }
323
324 QString body;
325 if (useInlineBody) {
326 QString forwardBlock = "\n------------ " + tr("Forwarded Message") + " ------------\n";
327 forwardBlock += tr("Date: ") + src.date().toString() + '\n';
328 forwardBlock += tr("From: ") + src.from().toString() + '\n';
329 forwardBlock += tr("To: ") + QMailAddress::toStringList(src.to()).join(QLatin1String(", ")) + '\n';
330 forwardBlock += tr("Subject: ") + src.subject().simplified() + '\n';
331 body = (forwardBlock % QStringLiteral("\n") % srcBody);
332 } else {
333 qDebug() << "Seems we've found nothing to be used as body inline. Multipart type is: "
334 << src.multipartType();
335 // We need to attach the message instead using part refs if possible
336 Attachment *srcAttach = new Attachment(this, QString::number(src.id().toULongLong()), Attachment::PartType::Message, Attachment::Disposition::Attached);
337 m_attachments->append(srcAttach);
338 }
339 if (m_body == Q_NULLPTR) {
340 m_internalBody->setPlainText(body);
341 } else {
342 m_body->textDocument()->setPlainText(body);
343 }
344 m_mode = Mode::Fwd;
345 m_srcMessageId = src.id();
346 }
347
348 void MessageBuilder::composeMailTo(const QString &mailtoUri)
349 {
350 QUrl mailto(mailtoUri);
351 if (mailto.isEmpty() || mailto.scheme() != QStringLiteral("mailto")) {
352 qDebug() << "Not a valid mailto url" << mailto;
353 return;
354 }
355 QString host; // Will be our "To" addresses that aren't part of the queries
356 QString tos; // query to=
357 QString ccs; // query cc=
358 QString bccs; // query bcc=
359 QString encoded = mailto.path(QUrl::FullyDecoded).replace(QStringLiteral("mailto:"), QStringLiteral(""));
360 // qDebug() << "Encoded path" << encoded;
361 int index = encoded.indexOf(QChar('?'));
362 if (index != -1) {
363 QString query = encoded.mid(index + 1);
364 // qDebug() << "Query: " << query;
365 QUrlQuery opts(query);
366 if (opts.hasQueryItem(QStringLiteral("subject"))) {
367 setSubjectText(opts.queryItemValue(QStringLiteral("subject")));
368 }
369 if (opts.hasQueryItem(QStringLiteral("body"))) {
370 setBodyText(opts.queryItemValue(QStringLiteral("body")));
371 }
372 if (opts.hasQueryItem(QStringLiteral("to"))) {
373 tos = opts.queryItemValue(QStringLiteral("to"));
374 }
375 if (opts.hasQueryItem(QStringLiteral("cc"))) {
376 ccs = opts.queryItemValue(QStringLiteral("cc"));
377 }
378 if (opts.hasQueryItem(QStringLiteral("bcc"))) {
379 bccs = opts.queryItemValue(QStringLiteral("bcc"));
380 }
381 host = encoded.left(index);
382 } else {
383 host = encoded;
384 }
385 auto parseRecipients = [=](const QString &val) -> QStringList {
386 QStringList result;
387 if (val.contains(QChar(';'))) {
388 Q_FOREACH(const QString &addr, val.split(QChar(';'))) {
389 QMailAddress address(addr);
390 if (EmailValidator::instance()->validate(address.address())) {
391 result << addr;
392 } else {
393 qDebug() << "Invalid mailto address" << addr << ". Ignoring!!!!";
394 }
395 }
396 } else if (val.contains(QChar(','))) {
397 Q_FOREACH(const QString &addr, val.split(QChar(','))) {
398 QMailAddress address(addr);
399 if (EmailValidator::instance()->validate(address.address())) {
400 result << addr;
401 } else {
402 qDebug() << "Invalid mailto address" << addr << ". Ignoring!!!!";
403 }
404 }
405 } else {
406 QMailAddress address(val);
407 if (EmailValidator::instance()->validate(address.address())) {
408 result << val;
409 } else {
410 qDebug() << "Invalid mailto address" << val << ". Ignoring!!!!";
411 }
412 }
413 int ok = result.removeDuplicates();
414 Q_UNUSED(ok);
415 return result;
416 };
417 // need to make sure we include the tos as it maybe something stupid like
418 // mailto:[email protected][email protected],[email protected]&[email protected]...
419 if (!tos.isEmpty()) {
420 host.append(QChar(','));
421 host.append(tos);
422 }
423 QStringList tosList = parseRecipients(host);
424 Q_FOREACH(const QString &addr, tosList) {
425 addRecipient(To, addr);
426 }
427 if (!ccs.isEmpty()) {
428 QStringList ccList = parseRecipients(ccs);
429 Q_FOREACH(const QString &addr, ccList) {
430 addRecipient(Cc, addr);
431 }
432 }
433 if (!bccs.isEmpty()) {
434 QStringList bccList = parseRecipients(bccs);
435 Q_FOREACH(const QString &addr, bccList) {
436 addRecipient(Bcc, addr);
437 }
438 }
439 }
440
441 void MessageBuilder::reloadLastDraftId()
442 {
443 QMailMessage src(m_lastDraftId);
444 m_identities->setSelectedIndex(m_identities->determinePreferredIdentity(src));
445 if (src.responseType() == QMailMessage::Reply || src.responseType() == QMailMessage::ReplyToAll) {
446 m_srcMessageId = src.inResponseTo();
447 m_mode = Mode::Rply;
448 } else if (src.responseType() == QMailMessage::Reply) {
449 m_mode = Mode::Fwd;
450 } else {
451 m_mode = Mode::New;
452 }
453 addRecipients(To, src.to());
454 addRecipients(Cc, src.cc());
455 addRecipients(Bcc, src.bcc());
456 setSubjectText(src.subject());
457 if (src.multipartType() == QMailMessagePartContainer::MultipartNone) {
458 if (src.hasBody()) {
459 setBodyText(src.body().data());
460 }
461 } else {
462 // were a multipart
463 QMailMessagePart *part = Q_NULLPTR;
464 // Atm we prefer plaintext parts until we have an proper html editor
465 QMailMessagePartContainer *ptext = src.findPlainTextContainer();
466 if (ptext) {
467 // YAY!
468 part = static_cast<QMailMessagePart *>(ptext);
469 setBodyText(part->body().data());
470 } else {
471 QMailMessagePartContainer *htext = src.findHtmlContainer();
472 if (htext) {
473 part = static_cast<QMailMessagePart *>(htext);
474 QTextDocument b;
475 b.setHtml(part->body().data());
476 setBodyText(b.toPlainText());
477 }
478 }
479 }
480
481 // TODO: attachments
482 }
483
484 void MessageBuilder::addRecipient(const MessageBuilder::RecipientModels which, const QString &emailAddress)
485 {
486 if (emailAddress.isEmpty()) {
487 return;
488 }
489 switch(which) {
490 case To:
491 m_to->append(new MailAddress(Q_NULLPTR, emailAddress));
492 break;
493 case Cc:
494 m_cc->append(new MailAddress(Q_NULLPTR, emailAddress));
495 break;
496 case Bcc:
497 m_bcc->append(new MailAddress(Q_NULLPTR, emailAddress));
498 break;
499 }
500 emit maybeStartSaveTimer();
501 }
502
503 void MessageBuilder::addRecipient(const MessageBuilder::RecipientModels which, const QString &name, const QString &address)
504 {
505 if (address.isEmpty()) {
506 return;
507 }
508
509 if (name.isEmpty()) {
510 // ok only address given. Why are you calling this then?????
511 addRecipient(which, address);
512 return;
513 }
514
515 switch(which) {
516 case To:
517 m_to->append(new MailAddress(Q_NULLPTR, name, address));
518 break;
519 case Cc:
520 m_cc->append(new MailAddress(Q_NULLPTR, name, address));
521 break;
522 case Bcc:
523 m_bcc->append(new MailAddress(Q_NULLPTR, name, address));
524 break;
525 }
526 emit maybeStartSaveTimer();
527 }
528
529 void MessageBuilder::addRecipients(const MessageBuilder::RecipientModels which, const QMailAddressList &addresses)
530 {
531 if (addresses.isEmpty()) {
532 return;
533 }
534 Q_FOREACH(const QMailAddress & addr, addresses) {
535 switch(which) {
536 case To:
537 m_to->append(new MailAddress(Q_NULLPTR, addr));
538 break;
539 case Cc:
540 m_cc->append(new MailAddress(Q_NULLPTR, addr));
541 break;
542 case Bcc:
543 m_bcc->append(new MailAddress(Q_NULLPTR, addr));
544 break;
545 }
546 }
547 }
548
549 void MessageBuilder::removeRecipient(const MessageBuilder::RecipientModels which, const int &index)
550 {
551 if (index < 0) {
552 return;
553 }
554 switch(which) {
555 case To:
556 m_to->remove(index);
557 break;
558 case Cc:
559 m_cc->remove(index);
560 break;
561 case Bcc:
562 m_bcc->remove(index);
563 break;
564 }
565 }
566
567 void MessageBuilder::addFileAttachment(const QString &file)
568 {
569 if (file.isEmpty()) {
570 return;
571 }
572 QString newFile;
573 if (file.startsWith(QStringLiteral("file://"))) {
574 qDebug() << "Stripping file://";
575 newFile = file.split(QStringLiteral("://")).at(1);
576 } else {
577 newFile = file;
578 }
579 if (QFile::exists(newFile)) {
580 addFileAttachments(QStringList() << newFile);
581 } else {
582 qDebug() << "Attachment url " << newFile << "doesn't exist on the local file system";
583 }
584 }
585
586 void MessageBuilder::addFileAttachments(const QStringList &files)
587 {
588 Q_FOREACH(const QString &file, files) {
589 Attachment *a = new Attachment(this, file, Attachment::File, Attachment::Attached);
590 qDebug() << "======== New File Attachment ========";
591 qDebug() << "DisplayName: " << a->displayName();
592 qDebug() << "Size: " << a->size();
593 qDebug() << "Mimetype: " << a->mimeType();
594 qDebug() << "====================================";
595 m_attachments->append(a);
596 }
597 }
598
599 void MessageBuilder::appendTextToSubject(const QString &text)
600 {
601 if (m_subject) {
602 m_subject->textDocument()->setPlainText(text);
603 } else {
604 m_internalSubject->setPlainText(text);
605 }
606 }
607
608 void MessageBuilder::appendTextToBody(const QString &text)
609 {
610 QString body;
611 if (m_body == Q_NULLPTR) {
612 body = m_internalBody->toPlainText();
613 } else {
614 body = m_body->textDocument()->toPlainText();
615 }
616 if (body.isEmpty()) {
617 body.append(text);
618 } else {
619 body.append(QStringLiteral("\n\n%1").arg(text));
620 }
621 if (m_body) {
622 m_body->textDocument()->setPlainText(body);
623 } else {
624 m_internalBody->setPlainText(body);
625 }
626 }
627
628 void MessageBuilder::removeAttachment(const int &index)
629 {
630 if (index < 0 || index > m_attachments->size()) {
631 return;
632 }
633 m_attachments->remove(index);
634 }
635
636 void MessageBuilder::reset()
637 {
638 m_lastDraftId = QMailMessageId();
639 m_to->clear();
640 m_bcc->clear();
641 m_cc->clear();
642 m_attachments->clear();
643 if (m_subject != Q_NULLPTR) {
644 disconnect(m_subject->textDocument(), SIGNAL(contentsChange(int,int,int)), this, SLOT(subjectChanged(int,int,int)));
645 m_subject->textDocument()->clear();
646 }
647 m_subject = Q_NULLPTR;
648 m_internalSubject->clear();
649 if (m_body != Q_NULLPTR) {
650 disconnect(m_body->textDocument(), SIGNAL(contentsChange(int,int,int)), this, SLOT(bodyChanged(int,int,int)));
651 m_body->textDocument()->clear();
652 }
653 m_identities->reset();
654 m_body = Q_NULLPTR;
655 m_internalBody->clear();
656 m_mode = Mode::New;
657 m_srcMessageId = QMailMessageId();
658 }
659
660 void MessageBuilder::setSubject(QQuickTextDocument *subject)
661 {
662 if (m_subject == subject)
663 return;
664
665 m_subject = subject;
666 if (!m_internalSubject->isEmpty()) {
667 m_subject->textDocument()->setPlainText(m_internalSubject->toPlainText());
668 }
669 connect(m_subject->textDocument(), SIGNAL(contentsChange(int,int,int)), this, SLOT(subjectChanged(int,int,int)));
670 emit subjectChanged(subject);
671 }
672
673 void MessageBuilder::setBody(QQuickTextDocument *body)
674 {
675 if (m_body == body)
676 return;
677
678 m_body = body;
679 if (!m_internalBody->isEmpty()) {
680 m_body->textDocument()->setPlainText(m_internalBody->toPlainText());
681 }
682 connect(m_body->textDocument(), SIGNAL(contentsChange(int,int,int)), this, SLOT(bodyChanged(int,int,int)));
683 emit bodyChanged(body);
684 }
685
686 void MessageBuilder::setIdentities(QObject *identities)
687 {
688 SenderIdentities *i = qobject_cast<SenderIdentities *>(identities);
689 if (m_identities == i)
690 return;
691
692 m_identities = i;
693 emit identitiesChanged();
694 }
695
696 void MessageBuilder::buildRecipientsLists(const MessageBuilder::ReplyType &type, const QMailMessage &src)
697 {
698 // builds an address list from the To and Reply-To fields
699 auto prepareToReplies = [=](const QMailMessage &msg)->QMailAddressList {
700 bool hasReplyTo = false;
701 QMailAddressList tos;
702 // Start with the reply-to field and cater for ML munging
703 // we should try and respect the reply-to field if it's valid
704 QMailAddress replyTo(msg.replyTo());
705 if (replyTo.isNull()) {
706 tos << src.from();
707 } else if (replyTo.isGroup()) {
708 // Check for nasty ML reply-to munging. Yuk!!!
709 Q_FOREACH(const QMailAddress &addr, replyTo.groupMembers()) {
710 if (EmailValidator::instance()->validate(addr.address())) {
711 hasReplyTo = true;
712 tos << addr; // this one's ok.
713 }
714 }
715 } else {
716 if (EmailValidator::instance()->validate(replyTo.address())) {
717 hasReplyTo = true;
718 tos << replyTo;
719 }
720 }
721 if (hasReplyTo && (type == ReplyAll)) {
722 // we don't need to worry about duplicates as they get pruned next;
723 tos << src.from();
724 }
725 if (type == ReplyAll) {
726 tos << src.to();
727 }
728 qDebug() << "TOS COUNT; " << tos.count();
729 // if we still have nothing from the reply-to's then just use from
730 if (tos.isEmpty()) {
731 tos << src.from();
732 }
733 return tos;
734 };
735
736 auto deduplicateAndRemoveMe = [=](const QMailAddressList &list) -> QMailAddressList {
737 QMailAddressList tmpList;
738 tmpList << list;
739 for (int i = 0; i < list.size(); ++i) {
740 const QMailAddress addr = list.at(i);
741 if (m_identities->hasAddress(addr.address())) {
742 tmpList.removeAt(i);
743 }
744 }
745 // now deduplicate
746 QMailAddressList result;
747 Q_FOREACH(const QMailAddress &addr, tmpList) {
748 if (!result.contains(addr)) {
749 result << addr;
750 }
751 }
752 return result;
753 };
754
755 switch (type) {
756 case Reply:
757 {
758 QMailAddressList t1 = prepareToReplies(src);
759 addRecipients(To, deduplicateAndRemoveMe(t1));
760 break;
761 }
762 case ReplyAll:
763 {
764 QMailAddressList t2 = prepareToReplies(src);
765
766 if (!src.listId().isEmpty()) {
767 // include ML address
768 QByteArray lp = getListPostAddress(src);
769 if (!lp.isEmpty()) {
770 t2.append(QMailAddress(QString(lp)));
771 }
772 }
773 addRecipients(To, deduplicateAndRemoveMe(t2));
774
775 QMailAddressList c1 = src.cc();
776 if (!c1.isEmpty()) {
777 addRecipients(Cc, deduplicateAndRemoveMe(c1));
778 }
779 QMailAddressList b1 = src.bcc();
780 if (!b1.isEmpty()) {
781 addRecipients(Bcc, deduplicateAndRemoveMe(b1));
782 }
783 break;
784 }
785 case ReplyList:
786 {
787 QByteArray listPost = getListPostAddress(src);
788 if (!listPost.isEmpty()) {
789 m_to->append(new MailAddress(Q_NULLPTR, QString(listPost)));
790 } else {
791 qWarning() << "Invalid List-Post content " + listPost + " Falling back to using From field";
792 buildRecipientsLists(Reply, src);
793 }
794 break;
795 }
796 }
797 }
798
799 void MessageBuilder::subjectChanged(int position, int charsRemoved, int charsAdded) {
800 Q_UNUSED(position);
801 Q_UNUSED(charsRemoved);
802 Q_UNUSED(charsAdded);
803 const QString &subject = m_subject->textDocument()->toPlainText();
804 if (subject != m_internalSubject->toPlainText()) {
805 m_internalSubject->setPlainText(subject);
806 }
807 }
808
809 void MessageBuilder::bodyChanged(int position, int charsRemoved, int charsAdded) {
810 Q_UNUSED(position);
811 Q_UNUSED(charsRemoved);
812 Q_UNUSED(charsAdded);
813 const QString &body = m_body->textDocument()->toPlainText();
814 if (body != m_internalBody->toPlainText()) {
815 m_internalBody->setPlainText(body);
816 }
817 }
818
819 QByteArray MessageBuilder::getListPostAddress(const QMailMessage &src)
820 {
821 QMailMessageHeaderField h = src.headerField(QStringLiteral("List-Post"));
822 if (h.isNull()) {
823 return QByteArray();
824 }
825 QByteArray listPost = h.content().replace(QByteArrayLiteral("<"), QByteArrayLiteral("")).replace(QByteArrayLiteral(">"), QByteArrayLiteral(""));
826 if (EmailValidator::instance()->validate(listPost)) {
827 return listPost;
828 }
829 return QByteArray();
830 }
831
832 void MessageBuilder::setSubjectText(const QString &text)
833 {
834 if (m_subject == Q_NULLPTR) {
835 m_internalSubject->setPlainText(text);
836 } else {
837 m_subject->textDocument()->setPlainText(text);
838 }
839 }
840
841 void MessageBuilder::setBodyText(const QString &body)
842 {
843 if (m_body == Q_NULLPTR) {
844 m_internalBody->setPlainText(body);
845 } else {
846 m_body->textDocument()->setPlainText(body);
847 }
848 }