]> cloud.milkyroute.net Git - dolphin.git/blob - src/settings/services/servicemenuinstaller/servicemenuinstaller.cpp
06f34c6b932be4a252ba5454fa35bb467082c3f7
[dolphin.git] / src / settings / services / servicemenuinstaller / servicemenuinstaller.cpp
1 /***************************************************************************
2 * Copyright © 2019 Alexander Potashev <aspotashev@gmail.com> *
3 * *
4 * This program is free software; you can redistribute it and/or *
5 * modify it under the terms of the GNU General Public License as *
6 * published by the Free Software Foundation; either version 2 of *
7 * the License or (at your option) version 3 or any later version *
8 * accepted by the membership of KDE e.V. (or its successor approved *
9 * by the membership of KDE e.V.), which shall act as a proxy *
10 * defined in Section 14 of version 3 of the license. *
11 * *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
19 ***************************************************************************/
20
21 #include <QDebug>
22 #include <QProcess>
23 #include <QStandardPaths>
24 #include <QDir>
25 #include <QDirIterator>
26 #include <QCommandLineParser>
27 #include <QMimeDatabase>
28 #include <QUrl>
29 #include <QDesktopServices>
30 #include <QGuiApplication>
31
32 #include <KLocalizedString>
33
34 // @param msg Error that gets logged to CLI
35 Q_NORETURN void fail(const QString &str)
36 {
37 qCritical() << str;
38
39 QProcess process;
40 const QStringList args = {"--passivepopup", i18n("Dolphin service menu installation failed"), "15"};
41 process.start("kdialog", args, QIODevice::ReadOnly);
42 if (!process.waitForStarted()) {
43 qFatal("Failed to run kdialog");
44 }
45
46 exit(1);
47 }
48
49 QString getServiceMenusDir()
50 {
51 const QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
52 return QDir(dataLocation).absoluteFilePath("kservices5/ServiceMenus");
53 }
54
55 struct UncompressCommand
56 {
57 QString command;
58 QStringList args1;
59 QStringList args2;
60 };
61
62 void runUncompress(const QString &inputPath, const QString &outputPath)
63 {
64 QVector<QPair<QStringList, UncompressCommand>> mimeTypeToCommand;
65 mimeTypeToCommand.append({{"application/x-tar", "application/tar", "application/x-gtar", "multipart/x-tar"},
66 UncompressCommand({"tar", {"-xf"}, {"-C"}})});
67 mimeTypeToCommand.append({{"application/x-gzip", "application/gzip",
68 "application/x-gzip-compressed-tar", "application/gzip-compressed-tar",
69 "application/x-gzip-compressed", "application/gzip-compressed",
70 "application/tgz", "application/x-compressed-tar",
71 "application/x-compressed-gtar", "file/tgz",
72 "multipart/x-tar-gz", "application/x-gunzip", "application/gzipped",
73 "gzip/document"},
74 UncompressCommand({"tar", {"-zxf"}, {"-C"}})});
75 mimeTypeToCommand.append({{"application/bzip", "application/bzip2", "application/x-bzip",
76 "application/x-bzip2", "application/bzip-compressed",
77 "application/bzip2-compressed", "application/x-bzip-compressed",
78 "application/x-bzip2-compressed", "application/bzip-compressed-tar",
79 "application/bzip2-compressed-tar", "application/x-bzip-compressed-tar",
80 "application/x-bzip2-compressed-tar", "application/x-bz2"},
81 UncompressCommand({"tar", {"-jxf"}, {"-C"}})});
82 mimeTypeToCommand.append({{"application/zip", "application/x-zip", "application/x-zip-compressed",
83 "multipart/x-zip"},
84 UncompressCommand({"unzip", {}, {"-d"}})});
85
86 const auto mime = QMimeDatabase().mimeTypeForFile(inputPath).name();
87
88 UncompressCommand command{};
89 for (const auto &pair : qAsConst(mimeTypeToCommand)) {
90 if (pair.first.contains(mime)) {
91 command = pair.second;
92 break;
93 }
94 }
95
96 if (command.command.isEmpty()) {
97 fail(i18n("Unsupported archive type %1: %2", mime, inputPath));
98 }
99
100 QProcess process;
101 process.start(
102 command.command,
103 QStringList() << command.args1 << inputPath << command.args2 << outputPath,
104 QIODevice::NotOpen);
105 if (!process.waitForStarted()) {
106 fail(i18n("Failed to run uncompressor command for %1", inputPath));
107 }
108
109 if (!process.waitForFinished()) {
110 fail(
111 i18n("Process did not finish in reasonable time: %1 %2", process.program(), process.arguments().join(" ")));
112 }
113
114 if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
115 fail(i18n("Failed to uncompress %1", inputPath));
116 }
117 }
118
119 QString findRecursive(const QString &dir, const QString &basename)
120 {
121 QDirIterator it(dir, QStringList{basename}, QDir::Files, QDirIterator::Subdirectories);
122 while (it.hasNext()) {
123 return QFileInfo(it.next()).canonicalFilePath();
124 }
125
126 return QString();
127 }
128
129 bool runScriptOnce(const QString &path, const QStringList &args)
130 {
131 QProcess process;
132 process.setWorkingDirectory(QFileInfo(path).absolutePath());
133
134 process.start(path, args, QIODevice::NotOpen);
135 if (!process.waitForStarted()) {
136 fail(i18n("Failed to run installer script %1", path));
137 }
138
139 // Wait until installer exits, without timeout
140 if (!process.waitForFinished(-1)) {
141 qWarning() << "Failed to wait on installer:" << process.program() << process.arguments().join(" ");
142 return false;
143 }
144
145 if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
146 qWarning() << "Installer script exited with error:" << process.program() << process.arguments().join(" ");
147 return false;
148 }
149
150 return true;
151 }
152
153 // If hasArgVariants is true, run "path".
154 // If hasArgVariants is false, run "path argVariants[i]" until successful.
155 bool runScriptVariants(const QString &path, bool hasArgVariants, const QStringList &argVariants, QString &errorText)
156 {
157 QFile file(path);
158 if (!file.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)) {
159 errorText = i18n("Failed to set permissions on %1: %2", path, file.errorString());
160 return false;
161 }
162
163 qInfo() << "[servicemenuinstaller]: Trying to run installer/uninstaller" << path;
164 if (hasArgVariants) {
165 for (const auto &arg : argVariants) {
166 if (runScriptOnce(path, {arg})) {
167 return true;
168 }
169 }
170 } else if (runScriptOnce(path, {})) {
171 return true;
172 }
173
174 errorText = i18nc(
175 "%2 = comma separated list of arguments",
176 "Installer script %1 failed, tried arguments \"%2\".", path, argVariants.join(i18nc("Separator between arguments", "\", \"")));
177 return false;
178 }
179
180 QString generateDirPath(const QString &archive)
181 {
182 return QStringLiteral("%1-dir").arg(archive);
183 }
184
185 bool cmdInstall(const QString &archive, QString &errorText)
186 {
187 const auto serviceDir = getServiceMenusDir();
188 if (!QDir().mkpath(serviceDir)) {
189 // TODO Cannot get error string because of this bug: https://bugreports.qt.io/browse/QTBUG-1483
190 errorText = i18n("Failed to create path %1", serviceDir);
191 return false;
192 }
193
194 if (archive.endsWith(QLatin1String(".desktop"))) {
195 // Append basename to destination directory
196 const auto dest = QDir(serviceDir).absoluteFilePath(QFileInfo(archive).fileName());
197 qInfo() << "Single-File Service-Menu" << archive << dest;
198
199 QFile source(archive);
200 if (!source.copy(dest)) {
201 errorText = i18n("Failed to copy .desktop file %1 to %2: %3", archive, dest, source.errorString());
202 return false;
203 }
204 } else {
205 const QStringList binaryPackages = {"application/vnd.debian.binary-package", "application/x-rpm"};
206 if (binaryPackages.contains(QMimeDatabase().mimeTypeForFile(archive).name())) {
207 return QDesktopServices::openUrl(QUrl(archive));
208 }
209 const QString dir = generateDirPath(archive);
210 if (QFile::exists(dir)) {
211 if (!QDir(dir).removeRecursively()) {
212 errorText = i18n("Failed to remove directory %1", dir);
213 return false;
214 }
215 }
216
217 if (QDir().mkdir(dir)) {
218 errorText = i18n("Failed to create directory %1", dir);
219 }
220
221 runUncompress(archive, dir);
222
223 // Try "install-it" first
224 QString installItPath;
225 const QStringList basenames1 = {"install-it.sh", "install-it"};
226 for (const auto &basename : basenames1) {
227 const auto path = findRecursive(dir, basename);
228 if (!path.isEmpty()) {
229 installItPath = path;
230 break;
231 }
232 }
233
234 if (!installItPath.isEmpty()) {
235 return runScriptVariants(installItPath, false, QStringList{}, errorText);
236 }
237
238 // If "install-it" is missing, try "install"
239 QString installerPath;
240 const QStringList basenames2 = {"installKDE4.sh", "installKDE4", "install.sh", "install"};
241 for (const auto &basename : basenames2) {
242 const auto path = findRecursive(dir, basename);
243 if (!path.isEmpty()) {
244 installerPath = path;
245 break;
246 }
247 }
248
249 if (!installerPath.isEmpty()) {
250 return runScriptVariants(installerPath, true, {"--local", "--local-install", "--install"}, errorText);
251 }
252
253 fail(i18n("Failed to find an installation script in %1", dir));
254 }
255
256 return true;
257 }
258
259 bool cmdUninstall(const QString &archive, QString &errorText)
260 {
261 const auto serviceDir = getServiceMenusDir();
262 if (archive.endsWith(QLatin1String(".desktop"))) {
263 // Append basename to destination directory
264 const auto dest = QDir(serviceDir).absoluteFilePath(QFileInfo(archive).fileName());
265 QFile file(dest);
266 if (!file.remove()) {
267 errorText = i18n("Failed to remove .desktop file %1: %2", dest, file.errorString());
268 return false;
269 }
270 } else {
271 const QString dir = generateDirPath(archive);
272
273 // Try "deinstall" first
274 QString deinstallPath;
275 const QStringList basenames1 = {"uninstall.sh", "uninstal", "deinstall.sh", "deinstall"};
276 for (const auto &basename : basenames1) {
277 const auto path = findRecursive(dir, basename);
278 if (!path.isEmpty()) {
279 deinstallPath = path;
280 break;
281 }
282 }
283
284 if (!deinstallPath.isEmpty()) {
285 const bool ok = runScriptVariants(deinstallPath, false, {}, errorText);
286 if (!ok) {
287 return ok;
288 }
289 } else {
290 // If "deinstall" is missing, try "install --uninstall"
291 QString installerPath;
292 const QStringList basenames2 = {"install-it.sh", "install-it", "installKDE4.sh",
293 "installKDE4", "install.sh", "install"};
294 for (const auto &basename : basenames2) {
295 const auto path = findRecursive(dir, basename);
296 if (!path.isEmpty()) {
297 installerPath = path;
298 break;
299 }
300 }
301
302 if (!installerPath.isEmpty()) {
303 const bool ok = runScriptVariants(installerPath, true,
304 {"--remove", "--delete", "--uninstall", "--deinstall"}, errorText);
305 if (!ok) {
306 return ok;
307 }
308 } else {
309 fail(i18n("Failed to find an uninstallation script in %1", dir));
310 }
311 }
312
313 QDir dirObject(dir);
314 if (!dirObject.removeRecursively()) {
315 errorText = i18n("Failed to remove directory %1", dir);
316 return false;
317 }
318 }
319
320 return true;
321 }
322
323 int main(int argc, char *argv[])
324 {
325 QGuiApplication app(argc, argv);
326
327 QCommandLineParser parser;
328 parser.addPositionalArgument(QStringLiteral("command"), i18nc("@info:shell", "Command to execute: install or uninstall."));
329 parser.addPositionalArgument(QStringLiteral("path"), i18nc("@info:shell", "Path to archive."));
330 parser.process(app);
331
332 const QStringList args = parser.positionalArguments();
333 if (args.isEmpty()) {
334 fail(i18n("Command is required."));
335 }
336 if (args.size() == 1) {
337 fail(i18n("Path to archive is required."));
338 }
339
340 const QString cmd = args[0];
341 const QString archive = args[1];
342
343 QString errorText;
344 if (cmd == QLatin1String("install")) {
345 if (!cmdInstall(archive, errorText)) {
346 fail(errorText);
347 }
348 } else if (cmd == QLatin1String("uninstall")) {
349 if (!cmdUninstall(archive, errorText)) {
350 fail(errorText);
351 }
352 } else {
353 fail(i18n("Unsupported command %1", cmd));
354 }
355
356 return 0;
357 }