text_vcard.cpp 13.1 KB
Newer Older
Laurent Montel's avatar
Laurent Montel committed
1 2 3 4 5
/*

  This file is part of KMail, the KDE mail client.
  Copyright (c) 2004 Till Adam <adam@kde.org>
  Copyright (c) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.net>
Laurent Montel's avatar
Laurent Montel committed
6
  Copyright (C) 2012-2017 Laurent Montel <montel@kde.org>
Laurent Montel's avatar
Laurent Montel committed
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

  KMail 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.

  KMail 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.
*/
33

Laurent Montel's avatar
Laurent Montel committed
34 35 36
#include "updatecontactjob.h"
#include "vcardmemento.h"

37 38 39 40 41
#include <MessageViewer/BodyPartURLHandler>
#include <MimeTreeParser/BodyPartFormatter>
#include <MimeTreeParser/BodyPart>
#include <MimeTreeParser/NodeHelper>
#include <MimeTreeParser/HtmlWriter>
42
using MimeTreeParser::Interface::BodyPart;
Laurent Montel's avatar
Laurent Montel committed
43

Laurent Montel's avatar
Laurent Montel committed
44
#include <LibkdepimAkonadi/AddContactJob>
Laurent Montel's avatar
Laurent Montel committed
45 46 47 48 49 50 51 52

#include <Akonadi/Contact/ContactViewer>
#include <Akonadi/Contact/StandardContactFormatter>

#include <KContacts/VCardConverter>
#include <KContacts/Addressee>

#include <KLocalizedString>
53 54
#include <KIconLoader>

Laurent Montel's avatar
Laurent Montel committed
55 56 57 58 59 60 61 62 63 64
#include <QFileDialog>
#include <QIcon>
#include <QMenu>
#include <KMessageBox>
#include <QTemporaryFile>
#include <KJobWidgets>
#include <KIO/StatJob>
#include <KIO/FileCopyJob>
#include "vcard_debug.h"

Laurent Montel's avatar
Laurent Montel committed
65
namespace {
66
class Formatter : public MimeTreeParser::Interface::BodyPartFormatter
Laurent Montel's avatar
Laurent Montel committed
67 68 69 70 71 72
{
public:
    Formatter()
    {
    }

73
    Result format(MimeTreeParser::Interface::BodyPart *bodyPart, MimeTreeParser::HtmlWriter *writer) const Q_DECL_OVERRIDE
Laurent Montel's avatar
Laurent Montel committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    {
        if (!writer) {
            return Ok;
        }

        const QString vCard = bodyPart->asText();
        if (vCard.isEmpty()) {
            return AsIcon;
        }

        KContacts::VCardConverter vcc;

        MessageViewer::VcardMemento *memento = dynamic_cast<MessageViewer::VcardMemento *>(bodyPart->memento());
        QStringList lst;

        // Pre-count the number of non-empty addressees
        int count = 0;
Laurent Montel's avatar
Laurent Montel committed
91
        const KContacts::Addressee::List al = vcc.parseVCards(vCard.toUtf8());
Laurent Montel's avatar
Laurent Montel committed
92
        for (const KContacts::Addressee &a : al) {
Laurent Montel's avatar
Laurent Montel committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106
            if (a.isEmpty()) {
                continue;
            }
            if (!memento) {
                if (!a.emails().isEmpty()) {
                    lst.append(a.emails().first());
                    count++;
                }
            }
        }
        if (!count) {
            return AsIcon;
        }

Laurent Montel's avatar
Laurent Montel committed
107 108 109
        writer->queue(QLatin1String("<div align=\"center\"><h2>")
                      +i18np("Attached business card", "Attached business cards", count)
                      +QLatin1String("</h2></div>"));
Laurent Montel's avatar
Laurent Montel committed
110 111

        count = 0;
Laurent Montel's avatar
Laurent Montel committed
112 113
        static QString defaultPixmapPath = QUrl::fromLocalFile(KIconLoader::global()->iconPath(QStringLiteral("user-identity"), KIconLoader::Desktop)).url();
        static QString defaultMapIconPath = QUrl::fromLocalFile(KIconLoader::global()->iconPath(QStringLiteral("document-open-remote"), KIconLoader::Small)).url();
Laurent Montel's avatar
Laurent Montel committed
114 115 116 117 118

        if (!memento) {
            MessageViewer::VcardMemento *memento = new MessageViewer::VcardMemento(lst);
            bodyPart->setBodyPartMemento(memento);

119 120 121 122
            auto nodeHelper = bodyPart->nodeHelper();
            if (nodeHelper) {
                QObject::connect(memento, &MessageViewer::VcardMemento::update,
                                 nodeHelper, &MimeTreeParser::NodeHelper::update);
Laurent Montel's avatar
Laurent Montel committed
123 124 125
            }
        }

Laurent Montel's avatar
Laurent Montel committed
126
        for (const KContacts::Addressee &a : al) {
Laurent Montel's avatar
Laurent Montel committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
            if (a.isEmpty()) {
                continue;
            }
            Akonadi::StandardContactFormatter formatter;
            formatter.setContact(a);
            formatter.setDisplayQRCode(false);
            QString htmlStr = formatter.toHtml(Akonadi::StandardContactFormatter::EmbeddableForm);
            const KContacts::Picture photo = a.photo();
            htmlStr.replace(QStringLiteral("<img src=\"map_icon\""), QStringLiteral("<img src=\"%1\"").arg(defaultMapIconPath));
            if (photo.isEmpty()) {
                htmlStr.replace(QStringLiteral("img src=\"contact_photo\""), QStringLiteral("img src=\"%1\"").arg(defaultPixmapPath));
            } else {
                QImage img = a.photo().data();
                const QString dir = bodyPart->nodeHelper()->createTempDir(QLatin1String("vcard-") + a.uid());
                const QString filename = dir + QDir::separator() + a.uid();
                img.save(filename, "PNG");
                bodyPart->nodeHelper()->addTempFile(filename);
                const QString href = QLatin1String("file:") + QLatin1String(QUrl::toPercentEncoding(filename));
                htmlStr.replace(QLatin1String("img src=\"contact_photo\""), QStringLiteral("img src=\"%1\"").arg(href));
            }
            writer->queue(htmlStr);

Laurent Montel's avatar
Laurent Montel committed
149 150 151
            if (!memento
                || (memento && !memento->finished())
                || (memento && memento->finished() && !memento->vcardExist(count))) {
Laurent Montel's avatar
Laurent Montel committed
152 153
                const QString addToLinkText = i18n("[Add this contact to the address book]");
                QString op = QStringLiteral("addToAddressBook:%1").arg(count);
Laurent Montel's avatar
Laurent Montel committed
154 155 156 157 158
                writer->queue(QLatin1String("<div align=\"center\"><a href=\"")
                              +bodyPart->makeLink(op)
                              +QLatin1String("\">")
                              +addToLinkText
                              +QLatin1String("</a></div><br><br>"));
Laurent Montel's avatar
Laurent Montel committed
159 160 161 162
            } else {
                if (memento->address(count) != a) {
                    const QString addToLinkText = i18n("[Update this contact to the address book]");
                    const QString op = QStringLiteral("updateToAddressBook:%1").arg(count);
Laurent Montel's avatar
Laurent Montel committed
163 164 165 166 167
                    writer->queue(QLatin1String("<div align=\"center\"><a href=\"")
                                  +bodyPart->makeLink(op)
                                  +QLatin1String("\">")
                                  +addToLinkText
                                  +QLatin1String("</a></div><br><br>"));
Laurent Montel's avatar
Laurent Montel committed
168 169
                } else {
                    const QString addToLinkText = i18n("[This contact is already in addressbook]");
Laurent Montel's avatar
Laurent Montel committed
170 171 172
                    writer->queue(QLatin1String("<div align=\"center\">")
                                  +addToLinkText
                                  +QLatin1String("</a></div><br><br>"));
Laurent Montel's avatar
Laurent Montel committed
173 174 175 176 177 178 179 180 181
                }
            }
            count++;
        }

        return Ok;
    }
};

182
class UrlHandler : public MimeTreeParser::Interface::BodyPartURLHandler
Laurent Montel's avatar
Laurent Montel committed
183 184
{
public:
Laurent Montel's avatar
Laurent Montel committed
185
    bool handleClick(MessageViewer::Viewer *viewerInstance, BodyPart *bodyPart, const QString &path) const Q_DECL_OVERRIDE
Laurent Montel's avatar
Laurent Montel committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    {
        Q_UNUSED(viewerInstance);
        const QString vCard = bodyPart->asText();
        if (vCard.isEmpty()) {
            return true;
        }
        KContacts::VCardConverter vcc;
        const KContacts::Addressee::List al = vcc.parseVCards(vCard.toUtf8());
        const int index = path.rightRef(path.length() - path.lastIndexOf(QLatin1Char(':')) - 1).toInt();
        if (index == -1 || index >= al.count()) {
            return true;
        }
        const KContacts::Addressee a = al.at(index);
        if (a.isEmpty()) {
            return true;
        }

        if (path.startsWith(QStringLiteral("addToAddressBook"))) {
Laurent Montel's avatar
Laurent Montel committed
204
            KPIM::AddContactJob *job = new KPIM::AddContactJob(a, nullptr);
Laurent Montel's avatar
Laurent Montel committed
205 206
            job->start();
        } else if (path.startsWith(QStringLiteral("updateToAddressBook"))) {
Laurent Montel's avatar
Laurent Montel committed
207
            UpdateContactJob *job = new UpdateContactJob(a.emails().first(), a, nullptr);
Laurent Montel's avatar
Laurent Montel committed
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
            job->start();
        }

        return true;
    }

    static KContacts::Addressee findAddressee(BodyPart *part, const QString &path)
    {
        const QString vCard = part->asText();
        if (!vCard.isEmpty()) {
            KContacts::VCardConverter vcc;
            const KContacts::Addressee::List al = vcc.parseVCards(vCard.toUtf8());
            const int index = path.rightRef(path.length() - path.lastIndexOf(QLatin1Char(':')) - 1).toInt();
            if (index >= 0 && index < al.count()) {
                return al.at(index);
            }
        }
        return KContacts::Addressee();
    }

    bool handleContextMenuRequest(BodyPart *part, const QString &path, const QPoint &point) const Q_DECL_OVERRIDE
    {
        const QString vCard = part->asText();
        if (vCard.isEmpty()) {
            return true;
        }
        KContacts::Addressee a = findAddressee(part, path);
        if (a.isEmpty()) {
            return true;
        }

        QMenu *menu = new QMenu();
Laurent Montel's avatar
Laurent Montel committed
240 241 242 243
        QAction *open
            = menu->addAction(QIcon::fromTheme(QStringLiteral("document-open")), i18n("View Business Card"));
        QAction *saveas
            = menu->addAction(QIcon::fromTheme(QStringLiteral("document-save-as")), i18n("Save Business Card As..."));
Laurent Montel's avatar
Laurent Montel committed
244

Laurent Montel's avatar
Laurent Montel committed
245
        QAction *action = menu->exec(point, nullptr);
Laurent Montel's avatar
Laurent Montel committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        if (action == open) {
            openVCard(a, vCard);
        } else if (action == saveas) {
            saveAsVCard(a, vCard);
        }
        delete menu;
        return true;
    }

    QString statusBarMessage(BodyPart *part, const QString &path) const Q_DECL_OVERRIDE
    {
        KContacts::Addressee a = findAddressee(part, path);
        const bool addToAddressBook = path.startsWith(QStringLiteral("addToAddressBook"));
        if (a.realName().isEmpty()) {
            return addToAddressBook ? i18n("Add this contact to the address book.") : i18n("Update this contact to the address book.");
        } else {
            return addToAddressBook ? i18n("Add \"%1\" to the address book.", a.realName()) : i18n("Update \"%1\" to the address book.", a.realName());
        }
    }

    bool openVCard(const KContacts::Addressee &a, const QString &vCard) const
    {
        Q_UNUSED(vCard);
Laurent Montel's avatar
Laurent Montel committed
269
        Akonadi::ContactViewer *view = new Akonadi::ContactViewer(nullptr);
Laurent Montel's avatar
Laurent Montel committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        view->setRawContact(a);
        view->setMinimumSize(300, 400);
        view->show();
        return true;
    }

    bool saveAsVCard(const KContacts::Addressee &a, const QString &vCard) const
    {
        QString fileName;
        const QString givenName(a.givenName());
        if (givenName.isEmpty()) {
            fileName = a.familyName() + QLatin1String(".vcf");
        } else {
            fileName = givenName + QLatin1Char('_') + a.familyName() + QLatin1String(".vcf");
        }
        // get the saveas file name
Laurent Montel's avatar
Laurent Montel committed
286 287 288 289 290 291 292 293
        QUrl saveAsUrl
            = QFileDialog::getSaveFileUrl(nullptr, i18n("Save Business Card"), QUrl::fromUserInput(fileName));
        if (saveAsUrl.isEmpty()
            || (QFileInfo::exists(saveAsUrl.path())
                && (KMessageBox::warningYesNo(
                        nullptr,
                        i18n("%1 already exists. Do you want to overwrite it?",
                             saveAsUrl.path())) == KMessageBox::No))) {
Laurent Montel's avatar
Laurent Montel committed
294 295 296 297 298 299 300 301 302 303
            return false;
        }

        // put the attachment in a temporary file and save it
        QTemporaryFile tmpFile;
        tmpFile.open();

        QByteArray data = vCard.toUtf8();
        tmpFile.write(data);
        tmpFile.flush();
Laurent Montel's avatar
Laurent Montel committed
304
        auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), saveAsUrl, -1, KIO::Overwrite);
Laurent Montel's avatar
Laurent Montel committed
305 306 307 308
        return job->exec();
    }
};

309
class Plugin : public MimeTreeParser::Interface::BodyPartFormatterPlugin
Laurent Montel's avatar
Laurent Montel committed
310 311
{
public:
312
    const MimeTreeParser::Interface::BodyPartFormatter *bodyPartFormatter(int idx) const Q_DECL_OVERRIDE
Laurent Montel's avatar
Laurent Montel committed
313
    {
Laurent Montel's avatar
Laurent Montel committed
314
        return validIndex(idx) ? new Formatter() : nullptr;
Laurent Montel's avatar
Laurent Montel committed
315
    }
Laurent Montel's avatar
Laurent Montel committed
316

Laurent Montel's avatar
Laurent Montel committed
317 318
    const char *type(int idx) const Q_DECL_OVERRIDE
    {
Laurent Montel's avatar
Laurent Montel committed
319
        return validIndex(idx) ? "text" : nullptr;
Laurent Montel's avatar
Laurent Montel committed
320
    }
Laurent Montel's avatar
Laurent Montel committed
321

Laurent Montel's avatar
Laurent Montel committed
322 323 324 325 326 327 328 329 330 331
    const char *subtype(int idx) const Q_DECL_OVERRIDE
    {
        switch (idx) {
        case 0:
            return "x-vcard";
        case 1:
            return "vcard";
        case 2:
            return "directory";
        default:
Laurent Montel's avatar
Laurent Montel committed
332
            return nullptr;
Laurent Montel's avatar
Laurent Montel committed
333 334 335
        }
    }

336
    const MimeTreeParser::Interface::BodyPartURLHandler *urlHandler(int idx) const Q_DECL_OVERRIDE
Laurent Montel's avatar
Laurent Montel committed
337
    {
Laurent Montel's avatar
Laurent Montel committed
338
        return validIndex(idx) ? new UrlHandler() : nullptr;
Laurent Montel's avatar
Laurent Montel committed
339 340 341 342 343
    }

private:
    bool validIndex(int idx) const
    {
Laurent Montel's avatar
Laurent Montel committed
344
        return idx >= 0 && idx <= 2;
Laurent Montel's avatar
Laurent Montel committed
345 346 347 348 349
    }
};
}

extern "C"
Laurent Montel's avatar
Laurent Montel committed
350 351
Q_DECL_EXPORT MimeTreeParser::Interface::BodyPartFormatterPlugin
*messageviewer_bodypartformatter_text_vcard_create_bodypart_formatter_plugin()
Laurent Montel's avatar
Laurent Montel committed
352 353 354
{
    return new Plugin();
}