2 * SPDX-FileCopyrightText: 2019 Alexander Potashev <aspotashev@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
10 #include <QStandardPaths>
12 #include <QDirIterator>
13 #include <QCommandLineParser>
14 #include <QMimeDatabase>
16 #include <QGuiApplication>
17 #include <KLocalizedString>
20 #include "../../../config-packagekit.h"
22 const static QStringList binaryPackages
= {QStringLiteral("application/vnd.debian.binary-package"),
23 QStringLiteral("application/x-rpm"),
24 QStringLiteral("application/x-xz"),
25 QStringLiteral("application/zstd")};
26 enum PackageOperation
{
31 #ifdef HAVE_PACKAGEKIT
32 #include <PackageKit/Daemon>
33 #include <PackageKit/Details>
34 #include <PackageKit/Transaction>
36 #include <QDesktopServices>
39 // @param msg Error that gets logged to CLI
40 Q_NORETURN
void fail(const QString
&str
)
43 const QStringList args
= {"--detailederror" ,i18n("Dolphin service menu installation failed"), str
};
44 QProcess::startDetached("kdialog", args
);
49 QString
getServiceMenusDir()
51 const QString dataLocation
= QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation
);
52 return QDir(dataLocation
).absoluteFilePath("kservices5/ServiceMenus");
55 #ifdef HAVE_PACKAGEKIT
56 void packageKitInstall(const QString
&fileName
)
58 PackageKit::Transaction
*transaction
= PackageKit::Daemon::installFile(fileName
);
60 const auto exitWithError
= [=](PackageKit::Transaction::Error
, const QString
&details
) {
64 QObject::connect(transaction
, &PackageKit::Transaction::finished
,
65 [=](PackageKit::Transaction::Exit status
, uint
) {
66 if (status
== PackageKit::Transaction::ExitSuccess
) {
69 // Fallback error handling
70 QTimer::singleShot(500, [=](){
71 fail(i18n("Failed to install \"%1\", exited with status \"%2\"",
72 fileName
, QVariant::fromValue(status
).toString()));
75 QObject::connect(transaction
, &PackageKit::Transaction::errorCode
, exitWithError
);
78 void packageKitUninstall(const QString
&fileName
)
80 const auto exitWithError
= [=](PackageKit::Transaction::Error
, const QString
&details
) {
83 const auto uninstallLambda
= [=](PackageKit::Transaction::Exit status
, uint
) {
84 if (status
== PackageKit::Transaction::ExitSuccess
) {
89 PackageKit::Transaction
*transaction
= PackageKit::Daemon::getDetailsLocal(fileName
);
90 QObject::connect(transaction
, &PackageKit::Transaction::details
,
91 [=](const PackageKit::Details
&details
) {
92 PackageKit::Transaction
*transaction
= PackageKit::Daemon::removePackage(details
.packageId());
93 QObject::connect(transaction
, &PackageKit::Transaction::finished
, uninstallLambda
);
94 QObject::connect(transaction
, &PackageKit::Transaction::errorCode
, exitWithError
);
97 QObject::connect(transaction
, &PackageKit::Transaction::errorCode
, exitWithError
);
98 // Fallback error handling
99 QObject::connect(transaction
, &PackageKit::Transaction::finished
,
100 [=](PackageKit::Transaction::Exit status
, uint
) {
101 if (status
!= PackageKit::Transaction::ExitSuccess
) {
102 QTimer::singleShot(500, [=]() {
103 fail(i18n("Failed to uninstall \"%1\", exited with status \"%2\"",
104 fileName
, QVariant::fromValue(status
).toString()));
111 Q_NORETURN
void packageKit(PackageOperation operation
, const QString
&fileName
)
113 #ifdef HAVE_PACKAGEKIT
114 QFileInfo
fileInfo(fileName
);
115 if (!fileInfo
.exists()) {
116 fail(i18n("The file does not exist!"));
118 const QString absPath
= fileInfo
.absoluteFilePath();
119 if (operation
== PackageOperation::Install
) {
120 packageKitInstall(absPath
);
122 packageKitUninstall(absPath
);
124 QGuiApplication::exec(); // For event handling, no return after signals finish
125 fail(i18n("Unknown error when installing package"));
128 QDesktopServices::openUrl(QUrl(fileName
));
133 struct UncompressCommand
140 enum ScriptExecution
{
145 void runUncompress(const QString
&inputPath
, const QString
&outputPath
)
147 QVector
<QPair
<QStringList
, UncompressCommand
>> mimeTypeToCommand
;
148 mimeTypeToCommand
.append({{"application/x-tar", "application/tar", "application/x-gtar", "multipart/x-tar"},
149 UncompressCommand({"tar", {"-xf"}, {"-C"}})});
150 mimeTypeToCommand
.append({{"application/x-gzip", "application/gzip",
151 "application/x-gzip-compressed-tar", "application/gzip-compressed-tar",
152 "application/x-gzip-compressed", "application/gzip-compressed",
153 "application/tgz", "application/x-compressed-tar",
154 "application/x-compressed-gtar", "file/tgz",
155 "multipart/x-tar-gz", "application/x-gunzip", "application/gzipped",
157 UncompressCommand({"tar", {"-zxf"}, {"-C"}})});
158 mimeTypeToCommand
.append({{"application/bzip", "application/bzip2", "application/x-bzip",
159 "application/x-bzip2", "application/bzip-compressed",
160 "application/bzip2-compressed", "application/x-bzip-compressed",
161 "application/x-bzip2-compressed", "application/bzip-compressed-tar",
162 "application/bzip2-compressed-tar", "application/x-bzip-compressed-tar",
163 "application/x-bzip2-compressed-tar", "application/x-bz2"},
164 UncompressCommand({"tar", {"-jxf"}, {"-C"}})});
165 mimeTypeToCommand
.append({{"application/zip", "application/x-zip", "application/x-zip-compressed",
167 UncompressCommand({"unzip", {}, {"-d"}})});
169 const auto mime
= QMimeDatabase().mimeTypeForFile(inputPath
).name();
171 UncompressCommand command
{};
172 for (const auto &pair
: qAsConst(mimeTypeToCommand
)) {
173 if (pair
.first
.contains(mime
)) {
174 command
= pair
.second
;
179 if (command
.command
.isEmpty()) {
180 fail(i18n("Unsupported archive type %1: %2", mime
, inputPath
));
186 QStringList() << command
.args1
<< inputPath
<< command
.args2
<< outputPath
,
188 if (!process
.waitForStarted()) {
189 fail(i18n("Failed to run uncompressor command for %1", inputPath
));
192 if (!process
.waitForFinished()) {
194 i18n("Process did not finish in reasonable time: %1 %2", process
.program(), process
.arguments().join(" ")));
197 if (process
.exitStatus() != QProcess::NormalExit
|| process
.exitCode() != 0) {
198 fail(i18n("Failed to uncompress %1", inputPath
));
202 QString
findRecursive(const QString
&dir
, const QString
&basename
)
204 QDirIterator
it(dir
, QStringList
{basename
}, QDir::Files
, QDirIterator::Subdirectories
);
205 while (it
.hasNext()) {
206 return QFileInfo(it
.next()).canonicalFilePath();
212 bool runScriptOnce(const QString
&path
, const QStringList
&args
, ScriptExecution execution
)
215 process
.setWorkingDirectory(QFileInfo(path
).absolutePath());
217 const static bool konsoleAvailable
= !QStandardPaths::findExecutable("konsole").isEmpty();
218 if (konsoleAvailable
&& execution
== ScriptExecution::Konsole
) {
219 QString bashCommand
= KShell::quoteArg(path
) + ' ';
220 if (!args
.isEmpty()) {
221 bashCommand
.append(args
.join(' '));
223 bashCommand
.append("|| $SHELL");
224 // If the install script fails a shell opens and the user can fix the problem
225 // without an error konsole closes
226 process
.start("konsole", QStringList() << "-e" << "bash" << "-c" << bashCommand
, QIODevice::NotOpen
);
228 process
.start(path
, args
, QIODevice::NotOpen
);
230 if (!process
.waitForStarted()) {
231 fail(i18n("Failed to run installer script %1", path
));
234 // Wait until installer exits, without timeout
235 if (!process
.waitForFinished(-1)) {
236 qWarning() << "Failed to wait on installer:" << process
.program() << process
.arguments().join(" ");
240 if (process
.exitStatus() != QProcess::NormalExit
|| process
.exitCode() != 0) {
241 qWarning() << "Installer script exited with error:" << process
.program() << process
.arguments().join(" ");
248 // If hasArgVariants is true, run "path".
249 // If hasArgVariants is false, run "path argVariants[i]" until successful.
250 bool runScriptVariants(const QString
&path
, bool hasArgVariants
, const QStringList
&argVariants
, QString
&errorText
)
253 if (!file
.setPermissions(QFile::ReadOwner
| QFile::WriteOwner
| QFile::ExeOwner
)) {
254 errorText
= i18n("Failed to set permissions on %1: %2", path
, file
.errorString());
258 qInfo() << "[servicemenuinstaller]: Trying to run installer/uninstaller" << path
;
259 if (hasArgVariants
) {
260 for (const auto &arg
: argVariants
) {
261 if (runScriptOnce(path
, {arg
}, ScriptExecution::Process
)) {
265 } else if (runScriptOnce(path
, {}, ScriptExecution::Konsole
)) {
270 "%2 = comma separated list of arguments",
271 "Installer script %1 failed, tried arguments \"%2\".", path
, argVariants
.join(i18nc("Separator between arguments", "\", \"")));
275 QString
generateDirPath(const QString
&archive
)
277 return QStringLiteral("%1-dir").arg(archive
);
280 bool cmdInstall(const QString
&archive
, QString
&errorText
)
282 const auto serviceDir
= getServiceMenusDir();
283 if (!QDir().mkpath(serviceDir
)) {
284 // TODO Cannot get error string because of this bug: https://bugreports.qt.io/browse/QTBUG-1483
285 errorText
= i18n("Failed to create path %1", serviceDir
);
289 if (archive
.endsWith(QLatin1String(".desktop"))) {
290 // Append basename to destination directory
291 const auto dest
= QDir(serviceDir
).absoluteFilePath(QFileInfo(archive
).fileName());
292 qInfo() << "Single-File Service-Menu" << archive
<< dest
;
294 QFile
source(archive
);
295 if (!source
.copy(dest
)) {
296 errorText
= i18n("Failed to copy .desktop file %1 to %2: %3", archive
, dest
, source
.errorString());
300 if (binaryPackages
.contains(QMimeDatabase().mimeTypeForFile(archive
).name())) {
301 packageKit(PackageOperation::Install
, archive
);
303 const QString dir
= generateDirPath(archive
);
304 if (QFile::exists(dir
)) {
305 if (!QDir(dir
).removeRecursively()) {
306 errorText
= i18n("Failed to remove directory %1", dir
);
311 if (QDir().mkdir(dir
)) {
312 errorText
= i18n("Failed to create directory %1", dir
);
315 runUncompress(archive
, dir
);
317 // Try "install-it" first
318 QString installItPath
;
319 const QStringList basenames1
= {"install-it.sh", "install-it"};
320 for (const auto &basename
: basenames1
) {
321 const auto path
= findRecursive(dir
, basename
);
322 if (!path
.isEmpty()) {
323 installItPath
= path
;
328 if (!installItPath
.isEmpty()) {
329 return runScriptVariants(installItPath
, false, QStringList
{}, errorText
);
332 // If "install-it" is missing, try "install"
333 QString installerPath
;
334 const QStringList basenames2
= {"installKDE4.sh", "installKDE4", "install.sh", "install"};
335 for (const auto &basename
: basenames2
) {
336 const auto path
= findRecursive(dir
, basename
);
337 if (!path
.isEmpty()) {
338 installerPath
= path
;
343 if (!installerPath
.isEmpty()) {
344 // Try to run script without variants first
345 if (!runScriptVariants(installerPath
, false, {}, errorText
)) {
346 return runScriptVariants(installerPath
, true, {"--local", "--local-install", "--install"}, errorText
);
351 fail(i18n("Failed to find an installation script in %1", dir
));
357 bool cmdUninstall(const QString
&archive
, QString
&errorText
)
359 const auto serviceDir
= getServiceMenusDir();
360 if (archive
.endsWith(QLatin1String(".desktop"))) {
361 // Append basename to destination directory
362 const auto dest
= QDir(serviceDir
).absoluteFilePath(QFileInfo(archive
).fileName());
364 if (!file
.remove()) {
365 errorText
= i18n("Failed to remove .desktop file %1: %2", dest
, file
.errorString());
369 if (binaryPackages
.contains(QMimeDatabase().mimeTypeForFile(archive
).name())) {
370 packageKit(PackageOperation::Uninstall
, archive
);
372 const QString dir
= generateDirPath(archive
);
374 // Try "deinstall" first
375 QString deinstallPath
;
376 const QStringList basenames1
= {"uninstall.sh", "uninstal", "deinstall.sh", "deinstall"};
377 for (const auto &basename
: basenames1
) {
378 const auto path
= findRecursive(dir
, basename
);
379 if (!path
.isEmpty()) {
380 deinstallPath
= path
;
385 if (!deinstallPath
.isEmpty()) {
386 const bool ok
= runScriptVariants(deinstallPath
, false, {}, errorText
);
391 // If "deinstall" is missing, try "install --uninstall"
392 QString installerPath
;
393 const QStringList basenames2
= {"install-it.sh", "install-it", "installKDE4.sh",
394 "installKDE4", "install.sh", "install"};
395 for (const auto &basename
: basenames2
) {
396 const auto path
= findRecursive(dir
, basename
);
397 if (!path
.isEmpty()) {
398 installerPath
= path
;
403 if (!installerPath
.isEmpty()) {
404 const bool ok
= runScriptVariants(installerPath
, true,
405 {"--remove", "--delete", "--uninstall", "--deinstall"}, errorText
);
410 fail(i18n("Failed to find an uninstallation script in %1", dir
));
415 if (!dirObject
.removeRecursively()) {
416 errorText
= i18n("Failed to remove directory %1", dir
);
424 int main(int argc
, char *argv
[])
426 QGuiApplication
app(argc
, argv
);
428 QCommandLineParser parser
;
429 parser
.addPositionalArgument(QStringLiteral("command"), i18nc("@info:shell", "Command to execute: install or uninstall."));
430 parser
.addPositionalArgument(QStringLiteral("path"), i18nc("@info:shell", "Path to archive."));
433 const QStringList args
= parser
.positionalArguments();
434 if (args
.isEmpty()) {
435 fail(i18n("Command is required."));
437 if (args
.size() == 1) {
438 fail(i18n("Path to archive is required."));
441 const QString cmd
= args
[0];
442 const QString archive
= args
[1];
445 if (cmd
== QLatin1String("install")) {
446 if (!cmdInstall(archive
, errorText
)) {
449 } else if (cmd
== QLatin1String("uninstall")) {
450 if (!cmdUninstall(archive
, errorText
)) {
454 fail(i18n("Unsupported command %1", cmd
));