summaryrefslogtreecommitdiff
path: root/raveos-hyprland-theme/theme-data/DankMaterialShell/quickshell/Services/SystemUpdateService.qml
blob: 53ca7ade748911392b62a797439deab6ff366dae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
pragma Singleton
pragma ComponentBehavior: Bound

import QtQuick
import Quickshell
import Quickshell.Io
import qs.Common

Singleton {
    id: root

    property int refCount: 0
    property var availableUpdates: []
    property bool isChecking: false
    property bool hasError: false
    property string errorMessage: ""
    property string updChecker: ""
    property string pkgManager: ""
    property string distribution: ""
    property bool distributionSupported: false
    property string shellVersion: ""
    property string shellCodename: ""
    property string semverVersion: ""

    function getParsedShellVersion() {
        return parseVersion(semverVersion);
    }

    readonly property var archBasedUCSettings: {
        "listUpdatesSettings": {
            "params": [],
            "correctExitCodes": [0, 2]   // Exit code 0 = updates available, 2 = no updates
        },
        "parserSettings": {
            "lineRegex": /^(\S+)\s+([^\s]+)\s+->\s+([^\s]+)$/,
            "entryProducer": function (match) {
                return {
                    "name": match[1],
                    "currentVersion": match[2],
                    "newVersion": match[3],
                    "description": `${match[1]} ${match[2]} → ${match[3]}`
                };
            }
        }
    }

    readonly property var archBasedPMSettings: function(requiresSudo) {
        return {
            "listUpdatesSettings": {
                "params": ["-Qu"],
                "correctExitCodes": [0, 1]   // Exit code 0 = updates available, 1 = no updates
            },
            "upgradeSettings": {
                "params": ["-Syu"],
                "requiresSudo": requiresSudo
            },
            "parserSettings": {
                "lineRegex": /^(\S+)\s+([^\s]+)\s+->\s+([^\s]+)$/,
                "entryProducer": function (match) {
                    return {
                        "name": match[1],
                        "currentVersion": match[2],
                        "newVersion": match[3],
                        "description": `${match[1]} ${match[2]} → ${match[3]}`
                    };
                }
            }
        }
    }

    readonly property var fedoraBasedPMSettings: {
        "listUpdatesSettings": {
            "params": ["list", "--upgrades", "--quiet", "--color=never"],
            "correctExitCodes": [0, 1]   // Exit code 0 = updates available, 1 = no updates
        },
        "upgradeSettings": {
            "params": ["upgrade"],
            "requiresSudo": true
        },
        "parserSettings": {
            "lineRegex": /^([^\s]+)\s+([^\s]+)\s+.*$/,
            "entryProducer": function (match) {
                return {
                    "name": match[1],
                    "currentVersion": "",
                    "newVersion": match[2],
                    "description": `${match[1]} → ${match[2]}`
                };
            }
        }
    }

    readonly property var updateCheckerParams: {
        "checkupdates": archBasedUCSettings
    }
    readonly property var packageManagerParams: {
        "yay": archBasedPMSettings(false),
        "paru": archBasedPMSettings(false),
        "pacman": archBasedPMSettings(true),
        "dnf": fedoraBasedPMSettings
    }
    readonly property list<string> supportedDistributions: ["arch", "artix", "cachyos", "manjaro", "endeavouros", "fedora"]
    readonly property int updateCount: availableUpdates.length
    readonly property bool helperAvailable: pkgManager !== "" && distributionSupported

    Process {
        id: distributionDetection
        command: ["sh", "-c", "cat /etc/os-release | grep '^ID=' | cut -d'=' -f2 | tr -d '\"'"]
        running: true

        onExited: exitCode => {
            if (exitCode === 0) {
                distribution = stdout.text.trim().toLowerCase();
                distributionSupported = supportedDistributions.includes(distribution);

                if (distributionSupported) {
                    updateFinderDetection.running = true;
                    pkgManagerDetection.running = true;
                    checkForUpdates();
                } else {
                    console.warn("SystemUpdate: Unsupported distribution:", distribution);
                }
            } else {
                console.warn("SystemUpdate: Failed to detect distribution");
            }
        }

        stdout: StdioCollector {}

        Component.onCompleted: {
            versionDetection.running = true;
        }
    }

    Process {
        id: versionDetection
        command: ["sh", "-c", `cd "${Quickshell.shellDir}" && if [ -d .git ]; then echo "(git) $(git rev-parse --short HEAD)"; elif [ -f VERSION ]; then cat VERSION; fi`]

        stdout: StdioCollector {
            onStreamFinished: {
                shellVersion = text.trim();
            }
        }
    }

    Process {
        id: semverDetection
        command: ["sh", "-c", `cd "${Quickshell.shellDir}" && if [ -f VERSION ]; then cat VERSION; fi`]
        running: true

        stdout: StdioCollector {
            onStreamFinished: {
                semverVersion = text.trim();
            }
        }
    }

    Process {
        id: codenameDetection
        command: ["sh", "-c", `cd "${Quickshell.shellDir}" && if [ -f CODENAME ]; then cat CODENAME; fi`]
        running: true

        stdout: StdioCollector {
            onStreamFinished: {
                shellCodename = text.trim();
            }
        }
    }

    Process {
        id: updateFinderDetection
        command: ["sh", "-c", "which checkupdates"]

        onExited: exitCode => {
            if (exitCode === 0) {
                const exeFound = stdout.text.trim();
                updChecker = exeFound.split('/').pop();
            } else {
                console.warn("SystemUpdate: No update checker found. Will use package manager.");
            }
        }

        stdout: StdioCollector {}
    }

    Process {
        id: pkgManagerDetection
        command: ["sh", "-c", "which paru || which yay || which pacman || which dnf"]

        onExited: exitCode => {
            if (exitCode === 0) {
                const exeFound = stdout.text.trim();
                pkgManager = exeFound.split('/').pop();
            } else {
                console.warn("SystemUpdate: No package manager found");
            }
        }

        stdout: StdioCollector {}
    }

    Process {
        id: updateChecker

        onExited: exitCode => {
            isChecking = false;
            const correctExitCodes = updChecker.length > 0 ? [updChecker].concat(updateCheckerParams[updChecker].listUpdatesSettings.correctExitCodes) : [pkgManager].concat(packageManagerParams[pkgManager].listUpdatesSettings.correctExitCodes);
            if (correctExitCodes.includes(exitCode)) {
                parseUpdates(stdout.text);
                hasError = false;
                errorMessage = "";
            } else {
                hasError = true;
                errorMessage = "Failed to check for updates";
                console.warn("SystemUpdate: Update check failed with code:", exitCode);
            }
        }

        stdout: StdioCollector {}
    }

    Process {
        id: updater
        onExited: exitCode => {
            checkForUpdates();
        }
    }

    function checkForUpdates() {
        if (!distributionSupported || (!pkgManager && !updChecker) || isChecking)
            return;
        isChecking = true;
        hasError = false;
        if (pkgManager === "paru" || pkgManager === "yay") {
            const repoCmd = updChecker.length > 0 ? updChecker : `${pkgManager} -Qu`;
            updateChecker.command = ["sh", "-c", `(${repoCmd} 2>/dev/null; ${pkgManager} -Qua 2>/dev/null) || true`];
        } else if (updChecker.length > 0) {
            updateChecker.command = [updChecker].concat(updateCheckerParams[updChecker].listUpdatesSettings.params);
        } else {
            updateChecker.command = [pkgManager].concat(packageManagerParams[pkgManager].listUpdatesSettings.params);
        }
        updateChecker.running = true;
    }

    function parseUpdates(output) {
        const lines = output.trim().split('\n').filter(line => line.trim());
        const updates = [];

        const regex = packageManagerParams[pkgManager].parserSettings.lineRegex;
        const entryProducer = packageManagerParams[pkgManager].parserSettings.entryProducer;

        for (const line of lines) {
            const match = line.match(regex);
            if (match) {
                updates.push(entryProducer(match));
            }
        }

        availableUpdates = updates;
    }

    function runUpdates() {
        if (!distributionSupported || !pkgManager || updateCount === 0)
            return;
        const terminal = Quickshell.env("TERMINAL") || "xterm";

        if (SettingsData.updaterUseCustomCommand && SettingsData.updaterCustomCommand.length > 0) {
            const updateCommand = `${SettingsData.updaterCustomCommand} && echo -n "Updates complete! " ; echo "Press Enter to close..." && read`;
            const termClass = SettingsData.updaterTerminalAdditionalParams;

            var finalCommand = [terminal];
            if (termClass.length > 0) {
                finalCommand = finalCommand.concat(termClass.split(" "));
            }
            finalCommand.push("-e");
            finalCommand.push("sh");
            finalCommand.push("-c");
            finalCommand.push(updateCommand);
            updater.command = finalCommand;
        } else {
            const params = packageManagerParams[pkgManager].upgradeSettings.params.join(" ");
            const sudo = packageManagerParams[pkgManager].upgradeSettings.requiresSudo ? "sudo" : "";
            const updateCommand = `${sudo} ${pkgManager} ${params} && echo -n "Updates complete! " ; echo "Press Enter to close..." && read`;

            updater.command = [terminal, "-e", "sh", "-c", updateCommand];
        }
        updater.running = true;
    }

    Timer {
        interval: 30 * 60 * 1000
        repeat: true
        running: refCount > 0 && distributionSupported && (pkgManager || updChecker)
        onTriggered: checkForUpdates()
    }

    IpcHandler {
        target: "systemupdater"

        function updatestatus(): string {
            if (root.isChecking) {
                return "ERROR: already checking";
            }
            if (!distributionSupported) {
                return "ERROR: distribution not supported";
            }
            if (!pkgManager && !updChecker) {
                return "ERROR: update checker not available";
            }
            root.checkForUpdates();
            return "SUCCESS: Now checking...";
        }
    }

    function parseVersion(versionStr) {
        if (!versionStr || typeof versionStr !== "string")
            return {
                major: 0,
                minor: 0,
                patch: 0
            };

        let v = versionStr.trim();
        if (v.startsWith("v"))
            v = v.substring(1);

        const dashIdx = v.indexOf("-");
        if (dashIdx !== -1)
            v = v.substring(0, dashIdx);

        const plusIdx = v.indexOf("+");
        if (plusIdx !== -1)
            v = v.substring(0, plusIdx);

        const parts = v.split(".");
        return {
            major: parseInt(parts[0], 10) || 0,
            minor: parseInt(parts[1], 10) || 0,
            patch: parseInt(parts[2], 10) || 0
        };
    }

    function compareVersions(v1, v2) {
        if (v1.major !== v2.major)
            return v1.major - v2.major;
        if (v1.minor !== v2.minor)
            return v1.minor - v2.minor;
        return v1.patch - v2.patch;
    }

    function checkVersionRequirement(requirementStr, currentVersion) {
        if (!requirementStr || typeof requirementStr !== "string")
            return true;

        const req = requirementStr.trim();
        let operator = "";
        let versionPart = req;

        if (req.startsWith(">=")) {
            operator = ">=";
            versionPart = req.substring(2);
        } else if (req.startsWith("<=")) {
            operator = "<=";
            versionPart = req.substring(2);
        } else if (req.startsWith(">")) {
            operator = ">";
            versionPart = req.substring(1);
        } else if (req.startsWith("<")) {
            operator = "<";
            versionPart = req.substring(1);
        } else if (req.startsWith("=")) {
            operator = "=";
            versionPart = req.substring(1);
        } else {
            operator = ">=";
        }

        const reqVersion = parseVersion(versionPart);
        const cmp = compareVersions(currentVersion, reqVersion);

        switch (operator) {
        case ">=":
            return cmp >= 0;
        case ">":
            return cmp > 0;
        case "<=":
            return cmp <= 0;
        case "<":
            return cmp < 0;
        case "=":
            return cmp === 0;
        default:
            return cmp >= 0;
        }
    }
}