File: mailclient_p.cpp

package info (click to toggle)
akonadi-calendar 4:18.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 3,808 kB
  • sloc: cpp: 14,079; xml: 36; makefile: 8; sh: 4
file content (374 lines) | stat: -rw-r--r-- 15,334 bytes parent folder | download
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
/*
  Copyright (c) 1998 Barry D Benowitz <b.benowitz@telesciences.com>
  Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
  Copyright (c) 2009 Allen Winter <winter@kde.org>

  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 "mailclient_p.h"

#include "akonadi-calendar-version.h"

#include <collection.h>

#include <kcalcore/attendee.h>
#include <kcalcore/incidence.h>
#include <kcalcore/incidencebase.h>
#include <kcalutils/incidenceformatter.h>
#include <kmime/kmime_message.h>
#include <identity.h>
#include <kemailaddress.h>

#include <messagequeuejob.h>
#include <transport.h>
#include <transportmanager.h>

#include "akonadicalendar_debug.h"
#include <KLocalizedString>
#include <KJob>
#include <KProtocolManager>

using namespace Akonadi;

MailClient::MailClient(ITIPHandlerComponentFactory *factory, QObject *parent) : QObject(parent)
    , mFactory(factory ? factory : new ITIPHandlerComponentFactory(this))
{
}

MailClient::~MailClient()
{
}

void MailClient::mailAttendees(const KCalCore::IncidenceBase::Ptr &incidence,
                               const KIdentityManagement::Identity &identity,
                               bool bccMe, const QString &attachment,
                               const QString &mailTransport)
{
    Q_ASSERT(incidence);
    KCalCore::Attendee::List attendees = incidence->attendees();
    if (attendees.isEmpty()) {
        qCWarning(AKONADICALENDAR_LOG) << "There are no attendees to e-mail";
        emit finished(ResultNoAttendees, i18n("There are no attendees to e-mail"));
        return;
    }

    const QString from = incidence->organizer()->fullName();
    const QString organizerEmail = incidence->organizer()->email();

    QStringList toList;
    QStringList ccList;
    const int numberOfAttendees = attendees.count();
    for (int i = 0; i < numberOfAttendees; ++i) {
        KCalCore::Attendee::Ptr a = attendees.at(i);

        const QString email = a->email();
        if (email.isEmpty()) {
            continue;
        }

        // In case we (as one of our identities) are the organizer we are sending
        // this mail. We could also have added ourselves as an attendee, in which
        // case we don't want to send ourselves a notification mail.
        if (organizerEmail == email) {
            continue;
        }

        // Optional Participants and Non-Participants are copied on the email
        if (a->role() == KCalCore::Attendee::OptParticipant ||
                a->role() == KCalCore::Attendee::NonParticipant) {
            ccList << a->email();
        } else {
            toList << a->email();
        }
    }
    if (toList.isEmpty() && ccList.isEmpty()) {
        // Not really to be called a groupware meeting, eh
        qCWarning(AKONADICALENDAR_LOG) << "There are really no attendees to e-mail";
        emit finished(ResultReallyNoAttendees, i18n("There are no attendees to e-mail"));
        return;
    }
    QString to;
    if (!toList.isEmpty()) {
        to = toList.join(QStringLiteral(", "));
    }
    QString cc;
    if (!ccList.isEmpty()) {
        cc = ccList.join(QStringLiteral(", "));
    }

    QString subject;
    if (incidence->type() != KCalCore::Incidence::TypeFreeBusy) {
        KCalCore::Incidence::Ptr inc = incidence.staticCast<KCalCore::Incidence>();
        subject = inc->summary();
    } else {
        subject = i18n("Free Busy Object");
    }

    const QString body = KCalUtils::IncidenceFormatter::mailBodyStr(incidence);

    send(incidence, identity, from, to, cc, subject, body, false, bccMe, attachment, mailTransport);
}

void MailClient::mailOrganizer(const KCalCore::IncidenceBase::Ptr &incidence,
                               const KIdentityManagement::Identity &identity,
                               const QString &from, bool bccMe,
                               const QString &attachment,
                               const QString &sub, const QString &mailTransport)
{
    const QString to = incidence->organizer()->fullName();
    QString subject = sub;

    if (incidence->type() != KCalCore::Incidence::TypeFreeBusy) {
        KCalCore::Incidence::Ptr inc = incidence.staticCast<KCalCore::Incidence>();
        if (subject.isEmpty()) {
            subject = inc->summary();
        }
    } else {
        subject = i18n("Free Busy Message");
    }

    const QString body = KCalUtils::IncidenceFormatter::mailBodyStr(incidence);

    send(incidence, identity, from, to, QString(), subject, body, false, bccMe, attachment, mailTransport);
}

void MailClient::mailTo(const KCalCore::IncidenceBase::Ptr &incidence,
                        const KIdentityManagement::Identity &identity,
                        const QString &from, bool bccMe,
                        const QString &recipients, const QString &attachment,
                        const QString &mailTransport)
{
    QString subject;

    if (incidence->type() != KCalCore::Incidence::TypeFreeBusy) {
        KCalCore::Incidence::Ptr inc = incidence.staticCast<KCalCore::Incidence>();
        subject = inc->summary();
    } else {
        subject = i18n("Free Busy Message");
    }

    const QString body = KCalUtils::IncidenceFormatter::mailBodyStr(incidence);

    send(incidence, identity, from, recipients, QString(), subject, body, false,
         bccMe, attachment, mailTransport);
}

static QStringList extractEmailAndNormalize(const QString &email)
{
    const QStringList splittedEmail = KEmailAddress::splitAddressList(email);
    QStringList normalizedEmail;
    normalizedEmail.reserve(splittedEmail.count());
    for (const QString &email : splittedEmail) {
        const QString str = KEmailAddress::extractEmailAddress(KEmailAddress::normalizeAddressesAndEncodeIdn(email));
        normalizedEmail << str;
    }
    return normalizedEmail;
}

void MailClient::send(const KCalCore::IncidenceBase::Ptr &incidence,
                      const KIdentityManagement::Identity &identity,
                      const QString &from, const QString &_to,
                      const QString &cc, const QString &subject,
                      const QString &body, bool hidden, bool bccMe,
                      const QString &attachment, const QString &mailTransport)
{
    Q_UNUSED(hidden);
    if (!MailTransport::TransportManager::self()->showTransportCreationDialog(
                nullptr, MailTransport::TransportManager::IfNoTransportExists)) {
        qCritical() << "Error while creating transport";
        emit finished(ResultErrorCreatingTransport, i18n("Error while creating transport"));
        return;
    }

    // We must have a recipients list for most MUAs. Thus, if the 'to' list
    // is empty simply use the 'from' address as the recipient.
    QString to = _to;
    if (to.isEmpty()) {
        to = from;
    }
    qCDebug(AKONADICALENDAR_LOG) << "\nFrom:" << from
                                 << "\nTo:" << to
                                 << "\nCC:" << cc
                                 << "\nSubject:" << subject << "\nBody: \n" << body
                                 << "\nAttachment:\n" << attachment
                                 << "\nmailTransport: " << mailTransport;

    MailTransport::Transport *transport =
        MailTransport::TransportManager::self()->transportByName(mailTransport);

    if (!transport) {
        transport =
            MailTransport::TransportManager::self()->transportByName(
                MailTransport::TransportManager::self()->defaultTransportName());
    }

    if (!transport) {
        qCritical() << "Error fetching transport; mailTransport"
                    << mailTransport << MailTransport::TransportManager::self()->defaultTransportName();
        emit finished(ResultErrorFetchingTransport,
                      i18n("Error fetching transport. Unable to send invitations"));
        return;
    }

    const int transportId = transport->id();

    // gather config values
    KConfig config(QStringLiteral("kmail2rc"));

    KConfigGroup configGroup(&config, QStringLiteral("Invitations"));
    const bool outlookConformInvitation = configGroup.readEntry("LegacyBodyInvites",
#ifdef KDEPIM_ENTERPRISE_BUILD
                                          true
#else
                                          false
#endif
                                                               );

    // Now build the message we like to send. The message KMime::Message::Ptr instance
    // will be the root message that has 2 additional message. The body itself and
    // the attached cal.ics calendar file.
    KMime::Message::Ptr message = KMime::Message::Ptr(new KMime::Message);
    message->contentTransferEncoding()->clear();  // 7Bit, decoded.

    // Set the headers

    message->userAgent()->fromUnicodeString(
        KProtocolManager::userAgentForApplication(
            QStringLiteral("KOrganizer"), QStringLiteral(AKONADI_CALENDAR_VERSION)), "utf-8");

    message->from()->fromUnicodeString(from, "utf-8");
    message->to()->fromUnicodeString(to, "utf-8");
    message->cc()->fromUnicodeString(cc, "utf-8");
    if (bccMe) {
        message->bcc()->fromUnicodeString(from, "utf-8");   //from==me, right?
    }
    message->date()->setDateTime(QDateTime::currentDateTime());
    message->subject()->fromUnicodeString(subject, "utf-8");

    if (outlookConformInvitation) {
        message->contentType()->setMimeType("text/calendar");
        message->contentType()->setCharset("utf-8");
        message->contentType()->setName(QStringLiteral("cal.ics"), "utf-8");
        message->contentType()->setParameter(QStringLiteral("method"), QStringLiteral("request"));

        if (!attachment.isEmpty()) {
            KMime::Headers::ContentDisposition *disposition = new KMime::Headers::ContentDisposition;
            disposition->setDisposition(KMime::Headers::CDinline);
            message->setHeader(disposition);
            message->contentTransferEncoding()->setEncoding(KMime::Headers::CEquPr);
            message->setBody(KMime::CRLFtoLF(attachment.toUtf8()));
        }
    } else {
        // We need to set following 4 lines by hand else KMime::Content::addContent
        // will create a new Content instance for us to attach the main message
        // what we don't need cause we already have the main message instance where
        // 2 additional messages are attached.
        KMime::Headers::ContentType *ct = message->contentType();
        ct->setMimeType("multipart/mixed");
        ct->setBoundary(KMime::multiPartBoundary());
        ct->setCategory(KMime::Headers::CCcontainer);

        // Set the first multipart, the body message.
        KMime::Content *bodyMessage = new KMime::Content;
        KMime::Headers::ContentDisposition *bodyDisposition = new KMime::Headers::ContentDisposition;
        bodyDisposition->setDisposition(KMime::Headers::CDinline);
        bodyMessage->contentType()->setMimeType("text/plain");
        bodyMessage->contentType()->setCharset("utf-8");
        bodyMessage->contentTransferEncoding()->setEncoding(KMime::Headers::CEquPr);
        bodyMessage->setBody(KMime::CRLFtoLF(body.toUtf8()));
        bodyMessage->setHeader(bodyDisposition);
        message->addContent(bodyMessage);

        // Set the second multipart, the attachment.
        if (!attachment.isEmpty()) {
            KMime::Content *attachMessage = new KMime::Content;
            KMime::Headers::ContentDisposition *attachDisposition = new KMime::Headers::ContentDisposition;
            attachDisposition->setDisposition(KMime::Headers::CDattachment);
            attachMessage->contentType()->setMimeType("text/calendar");
            attachMessage->contentType()->setCharset("utf-8");
            attachMessage->contentType()->setName(QStringLiteral("cal.ics"), "utf-8");
            attachMessage->contentType()->setParameter(QStringLiteral("method"),
                    QStringLiteral("request"));
            attachMessage->setHeader(attachDisposition);
            attachMessage->contentTransferEncoding()->setEncoding(KMime::Headers::CEquPr);
            attachMessage->setBody(KMime::CRLFtoLF(attachment.toUtf8()));
            message->addContent(attachMessage);
        }
    }

    // Job done, attach the both multiparts and assemble the message.
    message->assemble();

    // Put the newly created item in the MessageQueueJob.
    MailTransport::MessageQueueJob *qjob = mFactory->createMessageQueueJob(incidence, identity, this);

    if (identity.disabledFcc()) {
        qjob->sentBehaviourAttribute().setSentBehaviour(MailTransport::SentBehaviourAttribute::Delete);
    } else {
        const Akonadi::Collection sentCollection(identity.fcc().toLongLong());
        if (sentCollection.isValid()) {
            qjob->sentBehaviourAttribute().setSentBehaviour(MailTransport::SentBehaviourAttribute::MoveToCollection);
            qjob->sentBehaviourAttribute().setMoveToCollection(sentCollection);
        } else {
            qjob->sentBehaviourAttribute().setSentBehaviour(
                MailTransport::SentBehaviourAttribute::MoveToDefaultSentCollection);
        }
    }
    qjob->transportAttribute().setTransportId(transportId);

    const QString unormalizedFrom = (transport && transport->specifySenderOverwriteAddress()) ?
                                    transport->senderOverwriteAddress() : from;

    const QString normalizedFrom = KEmailAddress::extractEmailAddress(
                                       KEmailAddress::normalizeAddressesAndEncodeIdn(unormalizedFrom));

    const QString finalFrom = KEmailAddress::extractEmailAddress(normalizedFrom);
    qjob->addressAttribute().setFrom(finalFrom);

    QStringList toStringList;
    if (!to.isEmpty()) {
        toStringList = extractEmailAndNormalize(to);
        qjob->addressAttribute().setTo(toStringList);
    }

    QStringList ccStringList;
    if (!cc.isEmpty()) {
        ccStringList = extractEmailAndNormalize(cc);
        qjob->addressAttribute().setCc(ccStringList);
    }

    QStringList bccStringList;
    if (bccMe) {
        bccStringList = extractEmailAndNormalize(from);
        qjob->addressAttribute().setBcc(bccStringList);
    }

    qjob->setMessage(message);
    connect(qjob, &KJob::finished, this, &MailClient::handleQueueJobFinished);
    qjob->start();
}

void MailClient::handleQueueJobFinished(KJob *job)
{
    if (job->error()) {
        qCritical() << "Error queueing message:" << job->errorText();
        emit finished(ResultQueueJobError, i18n("Error queuing message in outbox: %1",
                                                job->errorText()));
    } else {
        emit finished(ResultSuccess, QString());
    }
}