File indexing completed on 2024-04-28 16:51:32
0001 /* 0002 SPDX-FileCopyrightText: 2017 Kai Uwe Broulik <kde@privat.broulik.de> 0003 SPDX-FileCopyrightText: 2017 David Edmundson <davidedmundson@kde.org> 0004 0005 SPDX-License-Identifier: MIT 0006 */ 0007 0008 #include "downloadplugin.h" 0009 0010 #include "connection.h" 0011 0012 #include <KUiServerV2JobTracker> 0013 0014 DownloadPlugin::DownloadPlugin(QObject *parent) 0015 : AbstractBrowserPlugin(QStringLiteral("downloads"), 3, parent) 0016 , m_tracker(new KUiServerV2JobTracker(this)) 0017 { 0018 } 0019 0020 bool DownloadPlugin::onLoad() 0021 { 0022 // Have extension tell us about all the downloads 0023 sendData(QStringLiteral("createAll")); 0024 return true; 0025 } 0026 0027 bool DownloadPlugin::onUnload() 0028 { 0029 for (auto it = m_jobs.constBegin(), end = m_jobs.constEnd(); it != end; ++it) { 0030 it.value()->deleteLater(); // kill() would abort the download 0031 } 0032 return true; 0033 } 0034 0035 void DownloadPlugin::handleData(const QString &event, const QJsonObject &payload) 0036 { 0037 const QJsonObject &download = payload.value(QStringLiteral("download")).toObject(); 0038 0039 const int id = download.value(QStringLiteral("id")).toInt(-1); 0040 if (id < 0) { 0041 qWarning() << "Cannot update download with invalid id" << id; 0042 return; 0043 } 0044 0045 if (event == QLatin1String("created")) { 0046 // If we get a created event for an already existing job, update it instead 0047 auto *job = m_jobs.value(id); 0048 if (job) { 0049 job->update(download); 0050 return; 0051 } 0052 0053 job = new DownloadJob(); 0054 0055 // first register and then update, otherwise it will miss the initial description() emission 0056 m_tracker->registerJob(job); 0057 0058 job->update(download); 0059 0060 m_jobs.insert(id, job); 0061 0062 connect(job, &DownloadJob::killRequested, this, [this, id] { 0063 sendData(QStringLiteral("cancel"), 0064 { 0065 {QStringLiteral("downloadId"), id}, 0066 }); 0067 }); 0068 0069 connect(job, &DownloadJob::suspendRequested, this, [this, id] { 0070 sendData(QStringLiteral("suspend"), 0071 { 0072 {QStringLiteral("downloadId"), id}, 0073 }); 0074 }); 0075 0076 connect(job, &DownloadJob::resumeRequested, this, [this, id] { 0077 sendData(QStringLiteral("resume"), 0078 { 0079 {QStringLiteral("downloadId"), id}, 0080 }); 0081 }); 0082 0083 QObject::connect(job, &QObject::destroyed, this, [this, id] { 0084 m_jobs.remove(id); 0085 }); 0086 0087 job->start(); 0088 0089 QObject::connect(job, &KJob::finished, this, [this, job, id] {}); 0090 0091 } else if (event == QLatin1String("update")) { 0092 auto *job = m_jobs.value(id); 0093 if (!job) { 0094 debug() << "Failed to find download to update with id" << id; 0095 return; 0096 } 0097 0098 job->update(download); 0099 } 0100 }