shareplugin.cpp 7.96 KB
Newer Older
1
/**
2
 * SPDX-FileCopyrightText: 2013 Albert Vaca <albertvaka@gmail.com>
3
 *
4
 * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
5
6
 */

7
#include "shareplugin.h"
8

Àlex Fiestas's avatar
Àlex Fiestas committed
9
#include <QStandardPaths>
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
10
#include <QProcess>
11
#include <QDir>
12
#include <QDesktopServices>
13
#include <QDBusConnection>
14
#include <QTemporaryFile>
15
#include <QDateTime>
16

Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
17
18
19
#include <KLocalizedString>
#include <KJobTrackerInterface>
#include <KPluginFactory>
20
#include <KIO/Job>
21
#include <KIO/MkpathJob>
Nicolas Fella's avatar
Nicolas Fella committed
22
#include <KApplicationTrader>
23
#include <KFileUtils>
24

25
#include "core/filetransferjob.h"
26
#include "core/daemon.h"
27
#include "plugin_share_debug.h"
28

Nicolas Fella's avatar
Nicolas Fella committed
29
K_PLUGIN_CLASS_WITH_JSON(SharePlugin, "kdeconnect_share.json")
30

31
SharePlugin::SharePlugin(QObject* parent, const QVariantList& args)
32
    : KdeConnectPlugin(parent, args)
33
    , m_compositeJob()
34
{
35
36
}

Àlex Fiestas's avatar
Àlex Fiestas committed
37
QUrl SharePlugin::destinationDir() const
38
{
39
    const QString defaultDownloadPath = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
Nicolas Fella's avatar
Nicolas Fella committed
40
    QUrl dir = QUrl::fromLocalFile(config()->getString(QStringLiteral("incoming_path"), defaultDownloadPath));
41

42
    if (dir.path().contains(QLatin1String("%1"))) {
43
        dir.setPath(dir.path().arg(device()->name()));
Àlex Fiestas's avatar
Àlex Fiestas committed
44
    }
45

46
47
48
49
50
    KJob* job = KIO::mkpath(dir);
    bool ret = job->exec();
    if (!ret) {
        qWarning() << "couldn't create" << dir;
    }
51

52
    return dir;
53
54
}

55
56
57
58
QUrl SharePlugin::getFileDestination(const QString filename) const
{
    const QUrl dir = destinationDir().adjusted(QUrl::StripTrailingSlash);
    QUrl destination(dir);
59
    destination.setPath(dir.path() + QStringLiteral("/") + filename, QUrl::DecodedMode);
60
    if (destination.isLocalFile() && QFile::exists(destination.toLocalFile())) {
61
        destination.setPath(dir.path() + QStringLiteral("/") + KFileUtils::suggestName(dir, filename), QUrl::DecodedMode);
62
63
64
65
    }
    return destination;
}

66
67
68
69
70
71
static QString cleanFilename(const QString &filename)
{
    int idx = filename.lastIndexOf(QLatin1Char('/'));
    return idx>=0 ? filename.mid(idx + 1) : filename;
}

72
73
74
void SharePlugin::setDateModified(const QUrl& destination, const qint64 timestamp)
{
    QFile receivedFile(destination.toLocalFile());
75
76
    if (!receivedFile.exists() || !receivedFile.open(QIODevice::ReadWrite | QIODevice::Text)) {
        return;
77
78
79
80
    }
    receivedFile.setFileTime(QDateTime::fromMSecsSinceEpoch(timestamp), QFileDevice::FileTime(QFileDevice::FileModificationTime));
}

81
bool SharePlugin::receivePacket(const NetworkPacket& np)
82
{
83
/*
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
84
    //TODO: Write a test like this
85
    if (np.type() == PACKET_TYPE_PING) {
86

87
        qCDebug(KDECONNECT_PLUGIN_SHARE) << "sending file" << (QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc");
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
88

89
        NetworkPacket out(PACKET_TYPE_SHARE_REQUEST);
90
        out.set("filename", mDestinationDir + "itworks.txt");
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
91
        AutoClosingQFile* file = new AutoClosingQFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); //Test file to transfer
92

93
        out.setPayload(file, file->size());
94

95
        device()->sendPacket(out);
96
97

        return true;
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
98

99
    }
100
*/
101

102
    qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer";
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
103

104
105
    if (np.hasPayload() || np.has(QStringLiteral("filename"))) {
//         qCDebug(KDECONNECT_PLUGIN_SHARE) << "receiving file" << filename << "in" << dir << "into" << destination;
106
        const QString filename = cleanFilename(np.get<QString>(QStringLiteral("filename"), QString::number(QDateTime::currentMSecsSinceEpoch())));
107
        QUrl destination = getFileDestination(filename);
108

109
        if (np.hasPayload()) {
110
            qint64 dateModified = np.get<qint64>(QStringLiteral("lastModified"), QDateTime::currentMSecsSinceEpoch());
111
            const bool open = np.get<bool>(QStringLiteral("open"), false);
Nicolas Fella's avatar
Nicolas Fella committed
112

113
114
            if (!m_compositeJob) {
                m_compositeJob = new CompositeFileTransferJob(device()->id());
115
                m_compositeJob->setProperty("destUrl", destinationDir().toString());
116
                m_compositeJob->setProperty("immediateProgressReporting", true);
117
118
119
                KIO::getJobTracker()->registerJob(m_compositeJob);
            }

120
            FileTransferJob* job = np.createPayloadTransferJob(destination);
121
            job->setOriginName(device()->name() + QStringLiteral(": ") + filename);
122
            connect(job, &KJob::result, this, [this, dateModified, open] (KJob* job) -> void { finished(job, dateModified, open); });
123
124
125
126
127
            m_compositeJob->addSubjob(job);

            if (!m_compositeJob->isRunning()) {
                m_compositeJob->start();
            }
128
129
130
131
        } else {
            QFile file(destination.toLocalFile());
            file.open(QIODevice::WriteOnly);
            file.close();
132
        }
133
134
    } else if (np.has(QStringLiteral("text"))) {
        QString text = np.get<QString>(QStringLiteral("text"));
135

Nicolas Fella's avatar
Nicolas Fella committed
136
        KService::Ptr service = KApplicationTrader::preferredService(QStringLiteral("text/plain"));
137
138
139
        const QString defaultApp = service ? service->desktopEntryName() : QString();

        if (defaultApp == QLatin1String("org.kde.kate") || defaultApp == QLatin1String("org.kde.kwrite")) {
140
141
            QProcess* proc = new QProcess();
            connect(proc, SIGNAL(finished(int)), proc, SLOT(deleteLater()));
142
            proc->start(defaultApp.section(QStringLiteral("."), 2,2), QStringList(QStringLiteral("--stdin")));
143
144
145
146
            proc->write(text.toUtf8());
            proc->closeWriteChannel();
        } else {
            QTemporaryFile tmpFile;
147
            tmpFile.setFileTemplate(QStringLiteral("kdeconnect-XXXXXX.txt"));
148
149
150
151
            tmpFile.setAutoRemove(false);
            tmpFile.open();
            tmpFile.write(text.toUtf8());
            tmpFile.close();
152

153
154
155
            const QString fileName = tmpFile.fileName();
            Q_EMIT shareReceived(fileName);
            QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));
156
        }
157
158
    } else if (np.has(QStringLiteral("url"))) {
        QUrl url = QUrl::fromEncoded(np.get<QByteArray>(QStringLiteral("url")));
159
        QDesktopServices::openUrl(url);
160
        Q_EMIT shareReceived(url.toString());
161
    } else {
162
        qCDebug(KDECONNECT_PLUGIN_SHARE) << "Error: Nothing attached!";
163
    }
164

165
166
167
    return true;
}

168
void SharePlugin::finished(KJob* job, const qint64 dateModified, const bool open)
169
{
170
    FileTransferJob* ftjob = qobject_cast<FileTransferJob*>(job);
171
172
    if (ftjob && !job->error()) {
        Q_EMIT shareReceived(ftjob->destination().toString());
173
        setDateModified(ftjob->destination(), dateModified);
174
        qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer finished." << ftjob->destination();
175
176
177
        if (open) {
            QDesktopServices::openUrl(ftjob->destination());
        }
178
179
180
    } else {
        qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer failed." << (ftjob ? ftjob->destination() : QUrl());
    }
181
}
182

183
void SharePlugin::openDestinationFolder()
184
{
185
    QDesktopServices::openUrl(destinationDir());
186
}
187

188
void SharePlugin::shareUrl(const QUrl& url, bool open)
189
{
190
    NetworkPacket packet(PACKET_TYPE_SHARE_REQUEST);
191
    if (url.isLocalFile()) {
192
193
194
195
196
197
198
199
200
201
        QSharedPointer<QFile> ioFile(new QFile(url.toLocalFile()));

        if (!ioFile->exists()) {
            Daemon::instance()->reportError(i18n("Could not share file"), i18n("%1 does not exist", url.toLocalFile()));
            return;
        } else {
            packet.setPayload(ioFile, ioFile->size());
            packet.set<QString>(QStringLiteral("filename"), QUrl(url).fileName());
            packet.set<bool>(QStringLiteral("open"), open);
        }
202
    } else {
203
        packet.set<QString>(QStringLiteral("url"), url.toString());
204
    }
205
    sendPacket(packet);
206
207
}

208
void SharePlugin::shareUrls(const QStringList& urls) {
Nicolas Fella's avatar
Use ref    
Nicolas Fella committed
209
    for(const QString& url : urls) {
210
        shareUrl(QUrl(url), false);
211
212
213
    }
}

214
215
216
217
218
219
220
void SharePlugin::shareText(const QString& text)
{
    NetworkPacket packet(PACKET_TYPE_SHARE_REQUEST);
    packet.set<QString>(QStringLiteral("text"), text);
    sendPacket(packet);
}

221
222
QString SharePlugin::dbusPath() const
{
223
    return QStringLiteral("/modules/kdeconnect/devices/") + device()->id() + QStringLiteral("/share");
224
}
225
226

#include "shareplugin.moc"