shareplugin.cpp 7.88 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
117
118
                KIO::getJobTracker()->registerJob(m_compositeJob);
            }

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

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

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

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

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

164
165
166
    return true;
}

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

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

187
void SharePlugin::shareUrl(const QUrl& url, bool open)
188
{
189
    NetworkPacket packet(PACKET_TYPE_SHARE_REQUEST);
190
    if (url.isLocalFile()) {
191
192
193
194
195
196
197
198
199
200
        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);
        }
201
    } else {
202
        packet.set<QString>(QStringLiteral("url"), url.toString());
203
    }
204
    sendPacket(packet);
205
206
}

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

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

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

#include "shareplugin.moc"