attachmenthandler.cpp 10.1 KB
Newer Older
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
/*
  Copyright (c) 2010 Klarlvdalens Datakonsult AB, a KDAB Group company <info@kdab.net>
    Author: Allen Winter <allen.winter@kdab.com>
  Copyright (C) 2014 Sergio Martins <iamsergio@gmail.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.
*/
/**
  @file
  This file is part of the API for handling calendar data and provides
  static functions for dealing with calendar incidence attachments.

  @brief
  vCalendar/iCalendar attachment handling.

  @author Allen Winter \<winter@kde.org\>
*/
#include "attachmenthandler.h"
#include "calendarsupport_debug.h"
#include "calendarsupport/utils.h"

#include <ItemFetchJob>

#include <KLocalizedString>
#include <KMessageBox>
#include <KRun>
#include <KIO/FileCopyJob>
#include <KIO/StatJob>
#include <KJobWidgets>
#include <KJob>

#include <QFileDialog>
#include <QTemporaryFile>
#include <QFile>
#include <QPointer>
#include <QMimeDatabase>
#include <QDesktopServices>

using namespace KCalCore;
using namespace Akonadi;

namespace CalendarSupport
{

struct ReceivedInfo {
    QString uid;
    QString attachmentName;
};

class Q_DECL_HIDDEN AttachmentHandler::Private
{
public:
    Private(QWidget *parent)
    {
        mParent = parent;
    }
    QMap<KJob *, ReceivedInfo> mJobToReceivedInfo;
    QPointer<QWidget> mParent;
};

AttachmentHandler::AttachmentHandler(QWidget *parent) : QObject(parent), d(new Private(parent))
{

}

AttachmentHandler::~AttachmentHandler()
{
    delete d;
}

Attachment::Ptr AttachmentHandler::find(const QString &attachmentName,
                                        const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return Attachment::Ptr();
    }

    // get the attachment by name from the incidence
    const Attachment::List as = incidence->attachments();
    Attachment::Ptr a;
    if (!as.isEmpty()) {
        Attachment::List::ConstIterator it;
        Attachment::List::ConstIterator end(as.constEnd());

        for (it = as.constBegin(); it != end; ++it) {
            if ((*it)->label() == attachmentName) {
                a = *it;
                break;
            }
        }
    }

    if (!a) {
        KMessageBox::error(
            d->mParent,
            i18n("No attachment named \"%1\" found in the incidence.", attachmentName));
        return Attachment::Ptr();
    }

    if (a->isUri()) {
        auto job = KIO::stat(QUrl(a->uri()), KIO::StatJob::SourceSide, 0);
        KJobWidgets::setWindow(job, d->mParent);
        if (!job->exec()) {
            KMessageBox::sorry(
                d->mParent,
                i18n("The attachment \"%1\" is a web link that is inaccessible from this computer. ",
                     QUrl::fromPercentEncoding(a->uri().toLatin1())));
            return Attachment::Ptr();
        }
    }
    return a;
}

Attachment::Ptr AttachmentHandler::find(const QString &attachmentName,
                                        const ScheduleMessage::Ptr &message)
{
    if (!message) {
        return Attachment::Ptr();
    }

    Incidence::Ptr incidence = message->event().dynamicCast<Incidence>();
    if (!incidence) {
        KMessageBox::error(
            d->mParent,
            i18n("The calendar invitation stored in this email message is broken in some way. "
                 "Unable to continue."));
        return Attachment::Ptr();
    }

    return find(attachmentName, incidence);
}

Laurent Montel's avatar
Laurent Montel committed
146
static QTemporaryFile *s_tempFile = Q_NULLPTR;
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

static QUrl tempFileForAttachment(const Attachment::Ptr &attachment)
{
    QUrl url;

    QMimeDatabase db;
    QStringList patterns = db.mimeTypeForName(attachment->mimeType()).globPatterns();
    if (!patterns.empty()) {
        s_tempFile = new QTemporaryFile(QDir::tempPath() + QLatin1String("/attachementview_XXXXXX") + patterns.first().remove(QLatin1Char('*')));
    } else {
        s_tempFile = new QTemporaryFile();
    }
    s_tempFile->setAutoRemove(false);
    s_tempFile->open();
    s_tempFile->setPermissions(QFile::ReadUser);
    s_tempFile->write(QByteArray::fromBase64(attachment->data()));
    s_tempFile->close();
    QFile tf(s_tempFile->fileName());
    if (tf.size() != attachment->size()) {
        //whoops. failed to write the entire attachment. return an invalid URL.
        delete s_tempFile;
Laurent Montel's avatar
Laurent Montel committed
168
        s_tempFile = Q_NULLPTR;
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        return url;
    }

    url.setPath(s_tempFile->fileName());
    return url;
}

bool AttachmentHandler::view(const Attachment::Ptr &attachment)
{
    if (!attachment) {
        return false;
    }

    bool stat = true;
    if (attachment->isUri()) {
        QDesktopServices::openUrl(QUrl(attachment->uri()));
    } else {
        // put the attachment in a temporary file and launch it
        QUrl tempUrl = tempFileForAttachment(attachment);
        if (tempUrl.isValid()) {
Laurent Montel's avatar
Laurent Montel committed
189
            stat = KRun::runUrl(tempUrl, attachment->mimeType(), Q_NULLPTR, true);
190 191 192 193 194 195 196
        } else {
            stat = false;
            KMessageBox::error(
                d->mParent,
                i18n("Unable to create a temporary file for the attachment."));
        }
        delete s_tempFile;
Laurent Montel's avatar
Laurent Montel committed
197
        s_tempFile = Q_NULLPTR;
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
    }
    return stat;
}

bool AttachmentHandler::view(const QString &attachmentName,
                             const Incidence::Ptr &incidence)
{
    return view(find(attachmentName, incidence));
}

void AttachmentHandler::view(const QString &attachmentName, const QString &uid)
{
    Item item;
    item.setGid(uid);
    ItemFetchJob *job = new ItemFetchJob(item);
    connect(job, &ItemFetchJob::result, this, &AttachmentHandler::slotFinishView);
    ReceivedInfo info;
    info.attachmentName = attachmentName;
    info.uid = uid;
    d->mJobToReceivedInfo[job] = info;
}

bool AttachmentHandler::view(const QString &attachmentName,
                             const ScheduleMessage::Ptr &message)
{
    return view(find(attachmentName, message));
}

bool AttachmentHandler::saveAs(const Attachment::Ptr &attachment)
{
    // get the saveas file name
    QString saveAsFile = QFileDialog::getSaveFileName(d->mParent, i18n("Save Attachment"), attachment->label());
    if (saveAsFile.isEmpty() ||
            (QFile(saveAsFile).exists() &&
             (KMessageBox::warningYesNo(
                  d->mParent,
                  i18n("%1 already exists. Do you want to overwrite it?",
                       saveAsFile)) == KMessageBox::No))) {
        return false;
    }

    bool stat = false;
    if (attachment->isUri()) {
        // save the attachment url
        auto job = KIO::file_copy(QUrl(attachment->uri()), QUrl::fromLocalFile(saveAsFile));
        stat = job->exec();
    } else {
        // put the attachment in a temporary file and save it
        QUrl tempUrl = tempFileForAttachment(attachment);
        if (tempUrl.isValid()) {
            auto job = KIO::file_copy(tempUrl, QUrl::fromLocalFile(saveAsFile));
            stat = job->exec();
            if (!stat && job->error()) {
                KMessageBox::error(d->mParent, job->errorString());
            }
        } else {
            stat = false;
            KMessageBox::error(
                d->mParent,
                i18n("Unable to create a temporary file for the attachment."));
        }
        delete s_tempFile;
Laurent Montel's avatar
Laurent Montel committed
260
        s_tempFile = Q_NULLPTR;
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
    }
    return stat;
}

bool AttachmentHandler::saveAs(const QString &attachmentName,
                               const Incidence::Ptr &incidence)
{
    return saveAs(find(attachmentName, incidence));
}

void AttachmentHandler::saveAs(const QString &attachmentName, const QString &uid)
{
    Item item;
    item.setGid(uid);
    ItemFetchJob *job = new ItemFetchJob(item);
    connect(job, &ItemFetchJob::result, this, &AttachmentHandler::slotFinishView);

    ReceivedInfo info;
    info.attachmentName = attachmentName;
    info.uid = uid;
    d->mJobToReceivedInfo[job] = info;
}

bool AttachmentHandler::saveAs(const QString &attachmentName,
                               const ScheduleMessage::Ptr &message)
{
    return saveAs(find(attachmentName, message));
}

void AttachmentHandler::slotFinishSaveAs(KJob *job)
{
    ReceivedInfo info = d->mJobToReceivedInfo[job];
    bool success = false;

    if (job->error() != 0) {
        ItemFetchJob *fetchJob = qobject_cast<ItemFetchJob *>(job);
        const Item::List items = fetchJob->items();
        if (!items.isEmpty()) {
            Incidence::Ptr incidence = CalendarSupport::incidence(items.first());
            success = incidence && saveAs(info.attachmentName, incidence);
        } else {
            qCWarning(CALENDARSUPPORT_LOG) << Q_FUNC_INFO << "No item found";
        }
    } else {
        qCWarning(CALENDARSUPPORT_LOG) << Q_FUNC_INFO << "Job error:" << job->errorString();
    }

    Q_EMIT saveAsFinished(info.uid, info.attachmentName, success);
    d->mJobToReceivedInfo.remove(job);
}

void AttachmentHandler::slotFinishView(KJob *job)
{
    ReceivedInfo info = d->mJobToReceivedInfo[job];
    bool success = false;

    if (job->error() != 0) {
        ItemFetchJob *fetchJob = qobject_cast<ItemFetchJob *>(job);
        const Item::List items = fetchJob->items();
        if (!items.isEmpty()) {
            Incidence::Ptr incidence = CalendarSupport::incidence(items.first());
            success = incidence && view(info.attachmentName, incidence);
        } else {
            qCWarning(CALENDARSUPPORT_LOG) << Q_FUNC_INFO << "No item found";
        }
    } else {
        qCWarning(CALENDARSUPPORT_LOG) << Q_FUNC_INFO << "Job error:" << job->errorString();
    }

    Q_EMIT viewFinished(info.uid, info.attachmentName, success);
    d->mJobToReceivedInfo.remove(job);
}

} // namespace CalendarSupport