KNewStuff

transaction.cpp
1/*
2 SPDX-FileCopyrightText: 2023 Aleix Pol Gonzalez <aleixpol@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.1-or-later
5*/
6
7#include "transaction.h"
8#include "enginebase.h"
9#include "enginebase_p.h"
10#include "entry_p.h"
11#include "provider.h"
12#include "question.h"
13
14#include <KLocalizedString>
15#include <KShell>
16#include <QDir>
17#include <QProcess>
18#include <QTimer>
19#include <QVersionNumber>
20
21#include <knewstuffcore_debug.h>
22
23using namespace KNSCore;
24
25namespace
26{
27std::optional<int> linkIdFromVersions(const QList<DownloadLinkInformationV2Private> &downloadLinksInformationList)
28{
29 switch (downloadLinksInformationList.size()) {
30 case 0:
31 return {};
32 case 1:
33 return downloadLinksInformationList.at(0).id;
34 }
35
36 QMap<QVersionNumber, int> infoByVersion;
37 for (const auto &info : downloadLinksInformationList) {
38 const auto number = QVersionNumber::fromString(info.version);
39 if (number.isNull()) {
40 qCDebug(KNEWSTUFFCORE) << "Found no valid version number on linkid" << info.id << info.version;
41 continue;
42 }
43 if (infoByVersion.contains(number)) {
44 qCWarning(KNEWSTUFFCORE) << "Encountered version number" << info.version << "more than once. Ignoring duplicates." << info.distributionType;
45 continue;
46 }
47 infoByVersion[number] = info.id;
48 }
49
50 if (infoByVersion.isEmpty()) { // found no valid version
51 return {};
52 }
53
54 return infoByVersion.last(); // map is sorted by keys, highest version is last entry.
55}
56} // namespace
57
58class KNSCore::TransactionPrivate
59{
60public:
61 TransactionPrivate(const KNSCore::Entry &entry, EngineBase *engine, Transaction *q)
62 : m_engine(engine)
63 , q(q)
64 , subject(entry)
65 {
66 }
67
68 void finish()
69 {
70 m_finished = true;
71 Q_EMIT q->finished();
72 q->deleteLater();
73 }
74
75 EngineBase *const m_engine;
76 Transaction *const q;
77 bool m_finished = false;
78 // Used for updating purposes - we ought to be saving this information, but we also have to deal with old stuff, and so... this will have to do for now
79 // TODO KF6: Installed state needs to move onto a per-downloadlink basis rather than per-entry
81 QMap<Entry, QString> payloadToIdentify;
82 const Entry subject;
83};
84
85/**
86 * we look for the directory where all the resources got installed.
87 * assuming it was extracted into a directory
88 */
89static QDir sharedDir(QStringList dirs, QString rootPath)
90{
91 // Ensure that rootPath definitely is a clean path with a slash at the end
92 rootPath = QDir::cleanPath(rootPath) + QStringLiteral("/");
93 qCInfo(KNEWSTUFFCORE) << Q_FUNC_INFO << dirs << rootPath;
94 while (!dirs.isEmpty()) {
95 QString thisDir(dirs.takeLast());
96 if (thisDir.endsWith(QStringLiteral("*"))) {
97 qCInfo(KNEWSTUFFCORE) << "Directory entry" << thisDir
98 << "ends in a *, indicating this was installed from an archive - see Installation::archiveEntries";
99 thisDir.chop(1);
100 }
101
102 const QString currentPath = QDir::cleanPath(thisDir);
103 qCInfo(KNEWSTUFFCORE) << "Current path is" << currentPath;
104 if (!currentPath.startsWith(rootPath)) {
105 qCInfo(KNEWSTUFFCORE) << "Current path" << currentPath << "does not start with" << rootPath << "and should be ignored";
106 continue;
107 }
108
109 const QFileInfo current(currentPath);
110 qCInfo(KNEWSTUFFCORE) << "Current file info is" << current;
111 if (!current.isDir()) {
112 qCInfo(KNEWSTUFFCORE) << "Current path" << currentPath << "is not a directory, and should be ignored";
113 continue;
114 }
115
116 const QDir dir(currentPath);
117 if (dir.path() == (rootPath + dir.dirName())) {
118 qCDebug(KNEWSTUFFCORE) << "Found directory" << dir;
119 return dir;
120 }
121 }
122 qCWarning(KNEWSTUFFCORE) << "Failed to locate any shared installed directory in" << dirs << "and this is almost certainly very bad.";
123 return {};
124}
125
126static QString getAdoptionCommand(const QString &command, const KNSCore::Entry &entry, Installation *inst)
127{
128 auto adoption = command;
129 if (adoption.isEmpty()) {
130 return {};
131 }
132
133 const QLatin1String dirReplace("%d");
134 if (adoption.contains(dirReplace)) {
135 QString installPath = sharedDir(entry.installedFiles(), inst->targetInstallationPath()).path();
136 adoption.replace(dirReplace, KShell::quoteArg(installPath));
137 }
138
139 const QLatin1String fileReplace("%f");
140 if (adoption.contains(fileReplace)) {
141 if (entry.installedFiles().isEmpty()) {
142 qCWarning(KNEWSTUFFCORE) << "no installed files to adopt";
143 return {};
144 } else if (entry.installedFiles().count() != 1) {
145 qCWarning(KNEWSTUFFCORE) << "can only adopt one file, will be using the first" << entry.installedFiles().at(0);
146 }
147
148 adoption.replace(fileReplace, KShell::quoteArg(entry.installedFiles().at(0)));
149 }
150 return adoption;
151}
152
153Transaction::Transaction(const KNSCore::Entry &entry, EngineBase *engine)
154 : QObject(engine)
155 , d(new TransactionPrivate(entry, engine, this))
156{
157 connect(d->m_engine->d->installation, &Installation::signalEntryChanged, this, [this](const KNSCore::Entry &changedEntry) {
158 Q_EMIT signalEntryEvent(changedEntry, Entry::StatusChangedEvent);
159 d->m_engine->cache()->registerChangedEntry(changedEntry);
160 });
161 connect(d->m_engine->d->installation, &Installation::signalInstallationFailed, this, [this](const QString &message, const KNSCore::Entry &entry) {
162 if (entry == d->subject) {
163 Q_EMIT signalErrorCode(KNSCore::ErrorCode::InstallationError, message, {});
164 d->finish();
165 }
166 });
167}
168
169Transaction::~Transaction() = default;
170
171Transaction *Transaction::install(EngineBase *engine, const KNSCore::Entry &_entry, int _linkId)
172{
173 auto ret = new Transaction(_entry, engine);
174 connect(engine->d->installation, &Installation::signalInstallationError, ret, [ret, _entry](const QString &msg, const KNSCore::Entry &entry) {
175 if (_entry.uniqueId() == entry.uniqueId()) {
176 Q_EMIT ret->signalErrorCode(KNSCore::ErrorCode::InstallationError, msg, {});
177 }
178 });
179
180 QTimer::singleShot(0, ret, [_entry, ret, _linkId, engine] {
181 int linkId = _linkId;
182 KNSCore::Entry entry = _entry;
183 if (entry.downloadLinkCount() == 0 && entry.payload().isEmpty()) {
184 // Turns out this happens sometimes, so we should deal with that and spit out an error
185 qCDebug(KNEWSTUFFCORE) << "There were no downloadlinks defined in the entry we were just asked to update: " << entry.uniqueId() << "on provider"
186 << entry.providerId();
187 Q_EMIT ret->signalErrorCode(
188 KNSCore::ErrorCode::InstallationError,
189 i18n("Could not perform an installation of the entry %1 as it does not have any downloadable items defined. Please contact the "
190 "author so they can fix this.",
191 entry.name()),
192 entry.uniqueId());
193 ret->d->finish();
194 } else {
195 if (entry.status() == KNSCore::Entry::Updateable) {
196 entry.setStatus(KNSCore::Entry::Updating);
197 } else {
198 entry.setStatus(KNSCore::Entry::Installing);
199 }
200 Q_EMIT ret->signalEntryEvent(entry, Entry::StatusChangedEvent);
201
202 qCDebug(KNEWSTUFFCORE) << "Install " << entry.name() << " from: " << entry.providerId();
203 QSharedPointer<Provider> p = engine->d->providers.value(entry.providerId());
204 if (p) {
205 connect(p.data(), &Provider::payloadLinkLoaded, ret, &Transaction::downloadLinkLoaded);
206 // If linkId is -1, assume we don't know what to update
207 if (linkId == -1) {
208 const auto downloadLinksInformationList = entry.d.constData()->mDownloadLinkInformationList;
209 const auto optionalLinkId = linkIdFromVersions(downloadLinksInformationList);
210 if (optionalLinkId.has_value()) {
211 qCDebug(KNEWSTUFFCORE) << "Found linkid by version" << optionalLinkId.value();
212 ret->d->payloadToIdentify[entry] = QString{};
213 linkId = optionalLinkId.value();
214 } else {
215 if (downloadLinksInformationList.size() == 1 || !entry.payload().isEmpty()) {
216 // If there is only one downloadable item (which also includes a predefined payload name), then we can fairly safely assume that's
217 // what we're wanting to update, meaning we can bypass some of the more expensive operations in downloadLinkLoaded
218 qCDebug(KNEWSTUFFCORE) << "Just the one download link, so let's use that";
219 ret->d->payloadToIdentify[entry] = QString{};
220 linkId = 1;
221 } else {
222 qCDebug(KNEWSTUFFCORE) << "Try and identify a download link to use from a total of" << entry.downloadLinkCount();
223 // While this seems silly, the payload gets reset when fetching the new download link information
224 ret->d->payloadToIdentify[entry] = entry.payload();
225 // Drop a fresh list in place so we've got something to work with when we get the links
226 ret->d->payloads[entry] = QStringList{};
227 linkId = 1;
228 }
229 }
230 } else {
231 qCDebug(KNEWSTUFFCORE) << "Link ID already known" << linkId;
232 // If there is no payload to identify, we will assume the payload is already known and just use that
233 ret->d->payloadToIdentify[entry] = QString{};
234 }
235
236 p->loadPayloadLink(entry, linkId);
237
238 ret->d->m_finished = false;
239 ret->d->m_engine->updateStatus();
240 }
241 }
242 });
243 return ret;
244}
245
246void Transaction::downloadLinkLoaded(const KNSCore::Entry &entry)
247{
248 if (entry.status() == KNSCore::Entry::Updating) {
249 if (d->payloadToIdentify[entry].isEmpty()) {
250 // If there's nothing to identify, and we've arrived here, then we know what the payload is
251 qCDebug(KNEWSTUFFCORE) << "If there's nothing to identify, and we've arrived here, then we know what the payload is";
252 d->m_engine->d->installation->install(entry);
253 d->payloadToIdentify.remove(entry);
254 d->finish();
255 } else if (d->payloads[entry].count() < entry.downloadLinkCount()) {
256 // We've got more to get before we can attempt to identify anything, so fetch the next one...
257 qCDebug(KNEWSTUFFCORE) << "We've got more to get before we can attempt to identify anything, so fetch the next one...";
258 QStringList payloads = d->payloads[entry];
259 payloads << entry.payload();
260 d->payloads[entry] = payloads;
261 QSharedPointer<Provider> p = d->m_engine->d->providers.value(entry.providerId());
262 if (p) {
263 // ok, so this should definitely always work, but... safety first, kids!
264 p->loadPayloadLink(entry, payloads.count());
265 }
266 } else {
267 // We now have all the links, so let's try and identify the correct one...
268 qCDebug(KNEWSTUFFCORE) << "We now have all the links, so let's try and identify the correct one...";
269 QString identifiedLink;
270 const QString payloadToIdentify = d->payloadToIdentify[entry];
272 const QStringList &payloads = d->payloads[entry];
273
274 if (payloads.contains(payloadToIdentify)) {
275 // Simplest option, the link hasn't changed at all
276 qCDebug(KNEWSTUFFCORE) << "Simplest option, the link hasn't changed at all";
277 identifiedLink = payloadToIdentify;
278 } else {
279 // Next simplest option, filename is the same but in a different folder
280 qCDebug(KNEWSTUFFCORE) << "Next simplest option, filename is the same but in a different folder";
281 const QString fileName = payloadToIdentify.split(QChar::fromLatin1('/')).last();
282 for (const QString &payload : payloads) {
283 if (payload.endsWith(fileName)) {
284 identifiedLink = payload;
285 break;
286 }
287 }
288
289 // Possibly the payload itself is named differently (by a CDN, for example), but the link identifier is the same...
290 qCDebug(KNEWSTUFFCORE) << "Possibly the payload itself is named differently (by a CDN, for example), but the link identifier is the same...";
291 QStringList payloadNames;
292 for (const Entry::DownloadLinkInformation &downloadLink : downloadLinks) {
293 qCDebug(KNEWSTUFFCORE) << "Download link" << downloadLink.name << downloadLink.id << downloadLink.size << downloadLink.descriptionLink;
294 payloadNames << downloadLink.name;
295 if (downloadLink.name == fileName) {
296 identifiedLink = payloads[payloadNames.count() - 1];
297 qCDebug(KNEWSTUFFCORE) << "Found a suitable download link for" << fileName << "which should match" << identifiedLink;
298 }
299 }
300
301 if (identifiedLink.isEmpty()) {
302 // Least simple option, no match - ask the user to pick (and if we still haven't got one... that's us done, no installation)
303 qCDebug(KNEWSTUFFCORE)
304 << "Least simple option, no match - ask the user to pick (and if we still haven't got one... that's us done, no installation)";
305 auto question = std::make_unique<Question>(Question::SelectFromListQuestion);
306 question->setTitle(i18n("Pick Update Item"));
307 question->setQuestion(
308 i18n("Please pick the item from the list below which should be used to apply this update. We were unable to identify which item to "
309 "select, based on the original item, which was named %1",
310 fileName));
311 question->setList(payloadNames);
312 if (question->ask() == Question::OKResponse) {
313 identifiedLink = payloads.value(payloadNames.indexOf(question->response()));
314 }
315 }
316 }
317 if (!identifiedLink.isEmpty()) {
318 KNSCore::Entry theEntry(entry);
319 theEntry.setPayload(identifiedLink);
320 d->m_engine->d->installation->install(theEntry);
321 connect(d->m_engine->d->installation, &Installation::signalInstallationFinished, this, [this, entry](const KNSCore::Entry &finishedEntry) {
322 if (entry.uniqueId() == finishedEntry.uniqueId()) {
323 d->finish();
324 }
325 });
326 } else {
327 qCWarning(KNEWSTUFFCORE) << "We failed to identify a good link for updating" << entry.name() << "and are unable to perform the update";
328 KNSCore::Entry theEntry(entry);
329 theEntry.setStatus(KNSCore::Entry::Updateable);
331 Q_EMIT signalErrorCode(ErrorCode::InstallationError,
332 i18n("We failed to identify a good link for updating %1, and are unable to perform the update", entry.name()),
333 {entry.uniqueId()});
334 }
335 // As the serverside data may change before next time this is called, even in the same session,
336 // let's not make assumptions, and just get rid of this
337 d->payloads.remove(entry);
338 d->payloadToIdentify.remove(entry);
339 d->finish();
340 }
341 } else {
342 d->m_engine->d->installation->install(entry);
343 connect(d->m_engine->d->installation, &Installation::signalInstallationFinished, this, [this, entry](const KNSCore::Entry &finishedEntry) {
344 if (entry.uniqueId() == finishedEntry.uniqueId()) {
345 d->finish();
346 }
347 });
348 }
349}
350
352{
353 auto ret = new Transaction(_entry, engine);
354 const KNSCore::Entry::List list = ret->d->m_engine->cache()->registryForProvider(_entry.providerId());
355 // we have to use the cached entry here, not the entry from the provider
356 // since that does not contain the list of installed files
357 KNSCore::Entry actualEntryForUninstall;
358 for (const KNSCore::Entry &eInt : list) {
359 if (eInt.uniqueId() == _entry.uniqueId()) {
360 actualEntryForUninstall = eInt;
361 break;
362 }
363 }
364 if (!actualEntryForUninstall.isValid()) {
365 qCDebug(KNEWSTUFFCORE) << "could not find a cached entry with following id:" << _entry.uniqueId() << " -> using the non-cached version";
366 actualEntryForUninstall = _entry;
367 }
368
369 QTimer::singleShot(0, ret, [actualEntryForUninstall, _entry, ret] {
370 KNSCore::Entry entry = _entry;
371 entry.setStatus(KNSCore::Entry::Installing);
372
373 Entry actualEntryForUninstall2 = actualEntryForUninstall;
374 actualEntryForUninstall2.setStatus(KNSCore::Entry::Installing);
375 Q_EMIT ret->signalEntryEvent(entry, Entry::StatusChangedEvent);
376
377 // We connect to/forward the relevant signals
378 qCDebug(KNEWSTUFFCORE) << "about to uninstall entry " << entry.uniqueId();
379 ret->d->m_engine->d->installation->uninstall(actualEntryForUninstall2);
380
381 // Update the correct entry
382 entry.setStatus(actualEntryForUninstall2.status());
383 Q_EMIT ret->signalEntryEvent(entry, Entry::StatusChangedEvent);
384
385 ret->d->finish();
386 });
387
388 return ret;
389}
390
392{
393 if (!engine->hasAdoptionCommand()) {
394 qCWarning(KNEWSTUFFCORE) << "no adoption command specified";
395 return nullptr;
396 }
397
398 auto ret = new Transaction(entry, engine);
399 const QString command = getAdoptionCommand(engine->d->adoptionCommand, entry, engine->d->installation);
400
401 QTimer::singleShot(0, ret, [command, entry, ret] {
402 QStringList split = KShell::splitArgs(command);
403 QProcess *process = new QProcess(ret);
404 process->setProgram(split.takeFirst());
405 process->setArguments(split);
406
408 // The debug output is too talkative to be useful
409 env.insert(QStringLiteral("QT_LOGGING_RULES"), QStringLiteral("*.debug=false"));
410 process->setProcessEnvironment(env);
411
412 process->start();
413
414 connect(process, &QProcess::finished, ret, [ret, process, entry, command](int exitCode) {
415 if (exitCode == 0) {
416 Q_EMIT ret->signalEntryEvent(entry, Entry::EntryEvent::AdoptedEvent);
417
418 // Handle error output as warnings if the process hasn't crashed
419 const QString stdErr = QString::fromLocal8Bit(process->readAllStandardError());
420 if (!stdErr.isEmpty()) {
421 Q_EMIT ret->signalMessage(stdErr);
422 }
423 } else {
424 const QString errorMsg = i18n("Failed to adopt '%1'\n%2", entry.name(), QString::fromLocal8Bit(process->readAllStandardError()));
425 Q_EMIT ret->signalErrorCode(KNSCore::ErrorCode::AdoptionError, errorMsg, QVariantList{command});
426 }
427 ret->d->finish();
428 });
429 });
430 return ret;
431}
432
434{
435 return d->m_finished;
436}
437
438#include "moc_transaction.cpp"
KNewStuff engine.
Definition enginebase.h:52
bool hasAdoptionCommand() const
Whether or not an adoption command exists for this engine.
KNewStuff data entry container.
Definition entry.h:48
QList< DownloadLinkInformation > downloadLinkInformationList() const
A list of downloadable data for this entry.
Definition entry.cpp:354
@ StatusChangedEvent
Used when an event's status is set (use Entry::status() to get the new status)
Definition entry.h:122
@ AdoptedEvent
Used when an entry has been successfully adopted (use this to determine whether a call to Engine::ado...
Definition entry.h:123
QStringList installedFiles() const
Retrieve the locally installed files.
Definition entry.cpp:339
QString payload() const
Retrieve the file name of the object.
Definition entry.cpp:186
void setStatus(KNSCore::Entry::Status status)
Sets the entry's status.
Definition entry.cpp:329
int downloadLinkCount() const
The number of available download options for this entry.
Definition entry.cpp:349
KNewStuff Transaction.
Definition transaction.h:38
static Transaction * install(EngineBase *engine, const Entry &entry, int linkId=1)
Performs an install on the given entry from the engine.
void signalEntryEvent(const KNSCore::Entry &entry, KNSCore::Entry::EntryEvent event)
Informs about how the entry has changed.
void signalErrorCode(KNSCore::ErrorCode::ErrorCode errorCode, const QString &message, const QVariant &metadata)
Fires in the case of any critical or serious errors, such as network or API problems.
static Transaction * adopt(EngineBase *engine, const Entry &entry)
Adopt the entry from engine using the adoption command.
static Transaction * uninstall(EngineBase *engine, const Entry &entry)
Uninstalls the given entry from the engine.
bool isFinished() const
QString i18n(const char *text, const TYPE &arg...)
KIOCORE_EXPORT QString number(KIO::filesize_t size)
KIOCORE_EXPORT QString dir(const QString &fileClass)
KCOREADDONS_EXPORT QStringList splitArgs(const QString &cmd, Options flags=NoOptions, Errors *err=nullptr)
KCOREADDONS_EXPORT QString quoteArg(const QString &arg)
QChar fromLatin1(char c)
QString cleanPath(const QString &path)
QString path() const const
const T * constData() const const
const_reference at(qsizetype i) const const
qsizetype count() const const
bool isEmpty() const const
T & last()
qsizetype size() const const
value_type takeFirst()
value_type takeLast()
T value(qsizetype i) const const
bool contains(const Key &key) const const
bool isEmpty() const const
T & last()
Q_EMITQ_EMIT
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void deleteLater()
void finished(int exitCode, QProcess::ExitStatus exitStatus)
QByteArray readAllStandardError()
void setArguments(const QStringList &arguments)
void setProcessEnvironment(const QProcessEnvironment &environment)
void setProgram(const QString &program)
void start(OpenMode mode)
void insert(const QProcessEnvironment &e)
QProcessEnvironment systemEnvironment()
T * data() const const
QString fromLocal8Bit(QByteArrayView str)
bool isEmpty() const const
bool isNull() const const
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
QStringList split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
bool contains(QLatin1StringView str, Qt::CaseSensitivity cs) const const
qsizetype indexOf(const QRegularExpression &re, qsizetype from) const const
QFuture< ArgsType< Signal > > connect(Sender *sender, Signal signal)
QVersionNumber fromString(QAnyStringView string, qsizetype *suffixIndex)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Jul 26 2024 11:56:35 by doxygen 1.11.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.