Repository navigation
Expand file tree
/
Copy pathappify
More file actions
6098 lines (5496 loc) · 258 KB
/
Copy pathappify
File metadata and controls
6098 lines (5496 loc) · 258 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Appify 3.0.1-1 - PyQt6 Port with Griffin Dark Theme
WINDOWS SUPPORT: this single file now runs on Linux AND Windows 10/11.
Linux -> bash wrappers + .desktop files (unchanged behaviour)
Windows -> registry-based browser detection, Start Menu .lnk shortcuts,
process-priority launching, installer-based self-update.
See the "Windows platform support" section below and windows/README.md.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NEW in 3.0.2
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- FIXED: Text fields in Chromium-based app windows (Edge, Brave, Chrome,
Chromium, Vivaldi, Opera, ungoogled-chromium) could show a blinking caret
but silently discard every keystroke. Root cause: Chromium's GTK4 toolkit
on Linux has broken IBus/Fcitx input-method integration on X11 sessions.
Generated wrappers now export GTK_IM_MODULE=xim for Chromium-based
browsers when running under X11, restoring working keyboard input.
Wayland sessions are unaffected and unchanged. Existing apps need their
wrappers regenerated (hamburger menu → Regenerate All Wrappers) to pick
this up.
- ADDED: "Force X11/XWayland Mode" option (Advanced Options, alongside GPU
Acceleration). Works around a separate, upstream Chromium bug in its
native Wayland text-input-v3 implementation that can also cause dropped
keystrokes in --app windows on Wayland sessions (GNOME, KDE, Sway,
Hyprland, labwc), which can appear or worsen after a Chromium update.
Off by default; enable it only if you hit that symptom on Wayland.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NEW in 3.0.1-1
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- Fixed the light and dark theme modes
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NEW in 3.0.0
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- PYQT6 PORT: Full rewrite of the UI layer from GTK4/libadwaita to PyQt6.
All logic is identical; only the UI toolkit changed.
- GRIFFIN DARK THEME: UI styled to match the rest of Griffin's UI colors, deep navy
backgrounds, blue accents.
- LAUNCH BUTTON: Test any installed app directly from the manager without
leaving the window. The button is disabled until the selected app is installed.
- STORE.JSON: Appify now uses a data-driven application catalog. New apps and
extension presets can be added without requiring an Appify update. The official
catalog is protected using GitHub CODEOWNERS to ensure changes are reviewed
before being merged.
- KNOWN ISSUES:
1. Some toolbar icons and menu buttons may appear slightly smaller than intended when
using the Griffin Dark Theme. This is a cosmetic issue caused by differences between GTK4
and PyQt6 stylesheet rendering and does not affect functionality.
2. Xbox's XCLOUD has an issue with third-party gamepads in any Chromium browser.
This appears to be a limitation of Xbox Cloud Gaming in Chromium-based browsers rather than
Appify. Existing community workarounds, including Better xCloud, have not fully resolved the issue.
- FIXED: Opening the Firefox extension store (or adding a custom extension) for an
already-running app could incorrectly report "Firefox is already running, but is
not responding" and never open. The store/extension launcher now remotes the URL
into the app's existing window when it's already open, and clears out stale
profile locks left behind by a crash or unclean shutdown when it isn't.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CARRIED FORWARD FROM 2.2.3
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- CONFIG DIR MIGRATION: ~/.pwa_manager renamed to ~/.appify.
- EXPORT / IMPORT: Export zips ~/.appify; import extracts and regenerates wrappers.
- CATEGORIES: 11 categories with collapsible browser panel and ✓ installed markers.
- PROFILE SIZE INDICATOR: Async on-disk size display.
- REGENERATE ALL WRAPPERS: Hamburger menu action.
- BACKUP EXTENSION WARNING: Lists extensions before backup.
- INTELLIGENT BROWSER DETECTION, WAYLAND/X11 NATIVE SUPPORT,
8 Browsers, WebHID gamepad, GPU acceleration, nice/ionice per-app, and more.
"""
import os
import re
import sys
import io
import json
import shutil
import argparse
import subprocess
import tempfile
import shlex
import tarfile
import threading
import datetime
import logging
import stat
from urllib.parse import urlparse
from pathlib import Path
from packaging.version import Version
import gettext
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGridLayout, QLabel, QLineEdit, QPushButton, QCheckBox, QSpinBox,
QComboBox, QScrollArea, QListWidget, QListWidgetItem, QGroupBox,
QFrame, QDialog, QDialogButtonBox, QFileDialog,
QMessageBox, QMenu, QMenuBar, QStatusBar, QToolBar, QSizePolicy,
QAbstractItemView, QTextEdit, QToolButton, QSplitter, QTimeEdit
)
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal, QObject, QSize, QMetaObject, Q_ARG, QTime
from PyQt6.QtGui import QAction, QIcon, QPalette, QColor, QFont, QTextOption, QPixmap, QPainter
CURRENT_VERSION = "3.0.8"
CONFIG_VERSION = 2
IS_WINDOWS = sys.platform == "win32"
IS_MAC = sys.platform == "darwin"
IS_FROZEN = bool(getattr(sys, "frozen", False)) # True inside a PyInstaller build
# A windowed (no-console) PyInstaller build has sys.stdout / sys.stderr == None,
# which makes print(..., file=sys.stderr) and logging.StreamHandler blow up.
for _stream_name in ("stdout", "stderr"):
if getattr(sys, _stream_name) is None:
setattr(sys, _stream_name, open(os.devnull, "w", encoding="utf-8"))
def resource_path(name: str) -> Path:
"""Locate a bundled data file (works from source and from PyInstaller)."""
base = getattr(sys, "_MEIPASS", None)
return (Path(base) if base else Path(__file__).resolve().parent) / name
# ─────────────────────────────────────────────────────────────────────────────
# GLib stub — replaces gi.repository.GLib so all original GLib.idle_add /
# GLib.timeout_add_seconds / GLib.source_remove calls work unchanged.
# _idle_dispatcher is set in main() after QApplication is created.
# ─────────────────────────────────────────────────────────────────────────────
class _QtIdleDispatcher(QObject):
_dispatch = pyqtSignal(object)
def __init__(self):
super().__init__()
self._dispatch.connect(self._execute, Qt.ConnectionType.QueuedConnection)
def _execute(self, fn):
try:
fn()
except Exception as _exc:
_logger.debug("idle_add callback error: %s", _exc)
def post(self, fn):
self._dispatch.emit(fn)
_idle_dispatcher: "_QtIdleDispatcher | None" = None
class GLib:
_timers: dict = {}
_next_id: int = 0
@staticmethod
def idle_add(fn, *args):
if _idle_dispatcher is not None:
_idle_dispatcher.post(lambda: fn(*args))
else:
fn(*args)
return False
@staticmethod
def timeout_add_seconds(n, fn):
GLib._next_id += 1
tid = GLib._next_id
def _fire():
result = fn()
if result and tid in GLib._timers:
t2 = QTimer()
t2.setSingleShot(True)
t2.timeout.connect(_fire)
t2.start(int(n * 1000))
GLib._timers[tid] = t2
else:
GLib._timers.pop(tid, None)
t = QTimer()
t.setSingleShot(True)
t.timeout.connect(_fire)
t.start(int(n * 1000))
GLib._timers[tid] = t
return tid
@staticmethod
def source_remove(tid):
t = GLib._timers.pop(tid, None)
if t:
t.stop()
# ─────────────────────────────────────────────────────────────────────────────
# Logging
# ─────────────────────────────────────────────────────────────────────────────
def _setup_logger() -> logging.Logger:
logger = logging.getLogger("appify")
if logger.handlers:
return logger
logger.setLevel(logging.DEBUG)
fmt = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
sh = logging.StreamHandler(sys.stderr)
sh.setFormatter(fmt)
logger.addHandler(sh)
return logger
_logger = _setup_logger()
def _ensure_file_log_handler():
for h in _logger.handlers:
if isinstance(h, logging.FileHandler):
return
try:
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
fh = logging.FileHandler(str(LOG_FILE), encoding="utf-8")
fh.setFormatter(logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
))
_logger.addHandler(fh)
except Exception as exc:
_logger.warning("Could not attach file log handler: %s", exc)
def log_debug(msg: str):
_ensure_file_log_handler()
_logger.debug(msg)
def open_url(url: str) -> None:
"""Open a URL in the user's default browser (xdg-open on Linux)."""
try:
if IS_WINDOWS:
os.startfile(url) # type: ignore[attr-defined]
elif IS_MAC:
subprocess.Popen(["open", url])
else:
subprocess.Popen(["xdg-open", url])
except Exception as exc:
_logger.warning("Could not open %s: %s", url, exc)
# ─────────────────────────────────────────────────────────────────────────────
# Internationalization
# ─────────────────────────────────────────────────────────────────────────────
def setup_i18n():
lang = (
os.environ.get("LC_ALL")
or os.environ.get("LANGUAGE")
or os.environ.get("LANG")
or ""
).split(".")[0].split(":")[0]
if not lang or lang.lower().startswith("c") or lang.lower() == "posix":
return lambda s: s
search_dirs = []
search_dirs.append(Path.home() / ".local" / "share" / "locale")
appdir = os.environ.get("APPDIR")
if appdir:
search_dirs.append(Path(appdir) / "usr" / "share" / "locale")
for p in ["/usr/share/locale", "/usr/local/share/locale",
"/var/lib/flatpak/exports/share/locale",
"/snap/core/current/usr/share/locale"]:
search_dirs.append(Path(p))
search_dirs.append(Path(__file__).parent / "locale")
lang_variants = [lang]
if "_" in lang:
lang_variants.append(lang.split("_")[0])
for locale_dir in search_dirs:
for lang_code in lang_variants:
mo_path = locale_dir / lang_code / "LC_MESSAGES" / "appify.mo"
if mo_path.exists():
try:
translation = gettext.translation(
domain="appify",
localedir=str(locale_dir),
languages=[lang_code],
fallback=False,
)
_logger.info("Loaded translation: %s", mo_path)
return translation.gettext
except Exception as e:
_logger.warning("Translation load failed (%s): %s", mo_path, e)
continue
return lambda s: s
tr = setup_i18n()
# ─────────────────────────────────────────────────────────────────────────────
# Browser Detection System
# ─────────────────────────────────────────────────────────────────────────────
BROWSER_DESKTOP_MAP: dict[str, str] = {
"firefox": "firefox",
"org.mozilla.firefox": "firefox",
"microsoft-edge": "edge",
"com.microsoft.edge": "edge",
"msedge": "edge",
"edge": "edge",
"brave": "brave",
"brave-browser": "brave",
"com.brave.browser": "brave",
"vivaldi": "vivaldi",
"com.vivaldi.vivaldi": "vivaldi",
"google-chrome": "chrome",
"com.google.chrome": "chrome",
"chrome": "chrome",
"chromium": "chromium",
"chromium-browser": "chromium",
"org.chromium.chromium":"chromium",
"opera": "opera",
"com.opera.opera": "opera",
}
_SNAP_NAMES: dict[str, str] = {
"firefox": "firefox",
"edge": "microsoft-edge",
"brave": "brave",
"vivaldi": "vivaldi",
"chrome": "google-chrome",
"chromium": "chromium",
"opera": "opera",
"ungoogled-chromium": "ungoogled-chromium",
}
_CHROMIUM_KEYS = ("edge", "brave", "vivaldi", "chrome", "chromium", "opera",
"ungoogled-chromium")
def is_wayland_session() -> bool:
return bool(os.environ.get('WAYLAND_DISPLAY'))
def is_x11_session() -> bool:
return bool(os.environ.get('DISPLAY')) and not is_wayland_session()
def get_session_type() -> str:
if IS_WINDOWS:
return "windows"
if IS_MAC:
return "macos"
if is_wayland_session():
return "wayland"
elif is_x11_session():
return "x11"
return "unknown"
def detect_wayland_compositor() -> str:
if not is_wayland_session():
return "unknown"
if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
return "hyprland"
if os.environ.get("SWAYSOCK"):
return "sway"
xdg = (os.environ.get("XDG_CURRENT_DESKTOP") or "").lower()
ds = (os.environ.get("DESKTOP_SESSION") or "").lower()
combined = f"{xdg} {ds}"
if "gnome" in combined:
return "gnome"
if "kde" in combined or "plasma" in combined:
return "kde"
if "sway" in combined:
return "sway"
if "hyprland" in combined:
return "hyprland"
if "cosmic" in combined:
return "cosmic"
if "wayfire" in combined:
return "wayfire"
if "river" in combined:
return "river"
if "labwc" in combined:
return "labwc"
try:
procs = subprocess.run(
["ps", "-eo", "comm"], capture_output=True, text=True, timeout=2
).stdout.lower()
for name, comp in [("gnome-shell","gnome"),("kwin_wayland","kde"),
("sway","sway"),("hyprland","hyprland"),
("cosmic-comp","cosmic"),("wayfire","wayfire"),
("river","river"),("labwc","labwc")]:
if name in procs:
return comp
except Exception:
pass
return "unknown"
def get_display_backend_flags(browser_key: str = "") -> str:
if IS_WINDOWS or IS_MAC:
return "" # Wayland/X11/Ozone flags are Linux-only
session = get_session_type()
chromium_browsers = ["edge","brave","vivaldi","chrome","chromium","opera","ungoogled-chromium"]
if browser_key.lower() not in chromium_browsers:
return ""
if session == "x11":
return "--use-gl=desktop --ignore-gpu-blocklist"
if session == "wayland":
if CONFIG.get("x11_fallback", False):
# Route Chromium through XWayland instead of native Wayland/Ozone.
# Works around a long-standing upstream Chromium bug where the
# native Wayland text-input-v3 implementation mistimes/drops
# keyboard-IME commits in --app (borderless) windows on several
# compositors (GNOME, KDE, Sway, Hyprland, labwc). Regressions in
# that code path have shipped in recent Chromium releases, which
# is why typing can stop working after a browser update even
# though nothing in Appify changed. XWayland's older X11 input
# path isn't affected.
return "--ozone-platform=x11 --ozone-platform-hint=x11"
compositor = detect_wayland_compositor()
base = "--ozone-platform=wayland --enable-features=UseOzonePlatform"
if compositor in ("kde", "gnome", "cosmic", "sway", "hyprland",
"river", "labwc", "wayfire"):
return f"{base},WaylandWindowDecorations"
return f"{base},WaylandWindowDecorations"
return "--ozone-platform-hint=auto"
_MAC_BROWSER_BINARIES: "dict[str, str]" = {
"firefox": "Firefox.app/Contents/MacOS/firefox",
"edge": "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"brave": "Brave Browser.app/Contents/MacOS/Brave Browser",
"vivaldi": "Vivaldi.app/Contents/MacOS/Vivaldi",
"chrome": "Google Chrome.app/Contents/MacOS/Google Chrome",
"chromium": "Chromium.app/Contents/MacOS/Chromium",
"opera": "Opera.app/Contents/MacOS/Opera",
"ungoogled-chromium": "Ungoogled Chromium.app/Contents/MacOS/Chromium",
}
_MAC_BUNDLE_ID_MAP = {
"com.google.chrome": "chrome", "com.microsoft.edgemac": "edge",
"org.mozilla.firefox": "firefox", "com.brave.browser": "brave",
"com.vivaldi.vivaldi": "vivaldi", "com.operasoftware.opera": "opera",
"org.chromium.chromium": "chromium",
}
def _mac_find_browser(browser_key: str) -> str:
"""Return a browser executable inside its macOS app bundle, if installed."""
relative_path = _MAC_BROWSER_BINARIES.get(browser_key)
if not relative_path:
return ""
for base in (Path("/Applications"), Path.home() / "Applications"):
executable = base / relative_path
if executable.is_file() and os.access(str(executable), os.X_OK):
return str(executable)
return ""
def _mac_default_browser_key(plist_path: "Path | None" = None) -> str:
"""Return the Appify key for the default HTTP(S) handler, if supported."""
import plistlib
plist_path = plist_path or (
Path.home() / "Library" / "Preferences" / "com.apple.LaunchServices" /
"com.apple.launchservices.secure.plist")
try:
with open(plist_path, "rb") as file:
handlers = plistlib.load(file).get("LSHandlers", [])
except Exception:
return ""
for scheme in ("https", "http"):
for handler in handlers:
if str(handler.get("LSHandlerURLScheme", "")).lower() == scheme:
bundle_id = str(handler.get("LSHandlerRoleAll", "")).lower()
return _MAC_BUNDLE_ID_MAP.get(bundle_id, "")
return ""
def detect_browser_installation(browser_key: str) -> dict:
browsers_info = {
"firefox": {"native_cmds": ["firefox", "/usr/bin/firefox"],
"flatpak": "org.mozilla.firefox", "snap": "firefox", "name": "Firefox"},
"edge": {"native_cmds": ["microsoft-edge", "microsoft-edge-stable"],
"flatpak": "com.microsoft.Edge", "snap": "microsoft-edge", "name": "Microsoft Edge"},
"brave": {"native_cmds": ["brave-browser-stable", "brave-browser", "brave"],
"flatpak": "com.brave.Browser", "snap": "brave", "name": "Brave"},
"vivaldi": {"native_cmds": ["vivaldi", "vivaldi-stable"],
"flatpak": "com.vivaldi.Vivaldi", "snap": "vivaldi", "name": "Vivaldi"},
"chrome": {"native_cmds": ["google-chrome", "google-chrome-stable"],
"flatpak": "com.google.Chrome", "snap": "google-chrome", "name": "Google Chrome"},
"chromium": {"native_cmds": ["chromium", "chromium-browser"],
"flatpak": "org.chromium.Chromium", "snap": "chromium", "name": "Chromium"},
"opera": {"native_cmds": ["opera", "opera-stable"],
"flatpak": "com.opera.Opera", "snap": "opera", "name": "Opera"},
"ungoogled-chromium": {"native_cmds": ["ungoogled-chromium"],
"flatpak": None, "snap": None, "name": "Ungoogled Chromium"},
}
if browser_key not in browsers_info:
return {'type': 'not_found', 'cmd': '', 'display_name': browser_key}
info = browsers_info[browser_key]
if IS_WINDOWS:
exe = _win_find_browser(browser_key)
if exe:
return {'type': 'native', 'cmd': exe,
'display_name': f"{info['name']} (Installed)"}
return {'type': 'not_found', 'cmd': '',
'display_name': f"{info['name']} (Not Installed)"}
if IS_MAC:
exe = _mac_find_browser(browser_key)
if exe:
return {'type': 'native', 'cmd': exe,
'display_name': f"{info['name']} (Installed)"}
return {'type': 'not_found', 'cmd': '',
'display_name': f"{info['name']} (Not Installed)"}
for cmd in info["native_cmds"]:
if shutil.which(cmd):
return {'type': 'native', 'cmd': cmd,
'display_name': f"{info['name']} (Native)"}
if info.get("flatpak"):
try:
result = subprocess.run(
["flatpak", "info", info["flatpak"]],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
return {'type': 'flatpak', 'cmd': f"flatpak run {info['flatpak']}",
'flatpak_id': info['flatpak'],
'display_name': f"{info['name']} (Flatpak)"}
except Exception:
pass
if info.get("snap"):
try:
result = subprocess.run(
["snap", "list", info["snap"]],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
return {'type': 'snap', 'cmd': f"snap run {info['snap']}",
'snap_name': info['snap'],
'display_name': f"{info['name']} (Snap)"}
except Exception:
pass
return {'type': 'not_found', 'cmd': '',
'display_name': f"{info['name']} (Not Installed)"}
def get_default_browser() -> str:
if IS_WINDOWS:
key = _win_default_browser_key()
if key and detect_browser_installation(key)['type'] != 'not_found':
return key
for browser in ['edge', 'chrome', 'firefox', 'brave', 'vivaldi', 'opera', 'chromium']:
if detect_browser_installation(browser)['type'] != 'not_found':
return browser
return 'edge' # ships with every Windows 10/11 install
if IS_MAC:
key = _mac_default_browser_key()
if key and detect_browser_installation(key)['type'] != 'not_found':
return key
# Safari is not supported for isolated Appify app windows.
for browser in ['chrome', 'edge', 'firefox', 'brave', 'vivaldi', 'opera', 'chromium']:
if detect_browser_installation(browser)['type'] != 'not_found':
return browser
return 'chrome'
try:
result = subprocess.run(
["xdg-settings", "get", "default-web-browser"],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
desktop_file = result.stdout.strip().lower()
browser_map = BROWSER_DESKTOP_MAP
desktop_name = desktop_file.replace('.desktop', '')
if desktop_name in browser_map:
return browser_map[desktop_name]
for key, browser_key in browser_map.items():
if key in desktop_file:
return browser_key
except Exception:
pass
try:
mimeapps_paths = [
Path.home() / '.config/mimeapps.list',
Path.home() / '.local/share/applications/mimeapps.list',
Path('/etc/xdg/mimeapps.list'),
]
for mimeapps_path in mimeapps_paths:
if mimeapps_path.exists():
with open(mimeapps_path, 'r') as f:
content = f.read().lower()
for pattern, browser_key in BROWSER_DESKTOP_MAP.items():
if (f'text/html={pattern}' in content or
f'x-scheme-handler/http={pattern}' in content):
return browser_key
except Exception:
pass
try:
result = subprocess.run(
["gio", "mime", "x-scheme-handler/http"],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
desktop_file = result.stdout.strip().lower()
for key, browser_key in BROWSER_DESKTOP_MAP.items():
if key in desktop_file:
return browser_key
except Exception:
pass
priority_order = ['edge', 'firefox', 'chrome', 'brave', 'chromium', 'vivaldi', 'opera']
for browser in priority_order:
detection = detect_browser_installation(browser)
if detection['type'] != 'not_found':
return browser
return 'firefox'
def scan_available_browsers() -> dict:
browsers = {}
for browser_key in ["firefox","edge","brave","vivaldi","chrome",
"chromium","opera","ungoogled-chromium"]:
detection = detect_browser_installation(browser_key)
if detection['type'] != 'not_found':
browsers[browser_key] = detection
return browsers
_PORTAL_BACKENDS: dict[str, str] = {
"kde": "xdg-desktop-portal-kde",
"gnome": "xdg-desktop-portal-gnome",
"cosmic": "xdg-desktop-portal-cosmic",
"hyprland": "xdg-desktop-portal-hyprland",
"sway": "xdg-desktop-portal-wlr",
"river": "xdg-desktop-portal-wlr",
"labwc": "xdg-desktop-portal-wlr",
"wayfire": "xdg-desktop-portal-wlr",
"x11": "xdg-desktop-portal-gtk",
"unknown": "xdg-desktop-portal-gtk",
}
def check_webhid_portal() -> dict:
if IS_WINDOWS or IS_MAC:
return {"ok": True, "portal": "built-in", "running": True,
"backend_found": True,
"reason": "The operating system handles HID device permissions natively "
"(no xdg-desktop-portal needed)."}
compositor = detect_wayland_compositor() if is_wayland_session() else "x11"
portal_pkg = _PORTAL_BACKENDS.get(compositor, "xdg-desktop-portal-gtk")
result: dict = {"ok": False, "portal": portal_pkg, "reason": "",
"running": False, "backend_found": False}
if not shutil.which("xdg-desktop-portal"):
result["reason"] = (
"xdg-desktop-portal is not installed. "
"WebHID/gamepad permission dialogs will not appear.")
return result
try:
pgrep = subprocess.run(
["pgrep", "-x", "xdg-desktop-por"], capture_output=True, timeout=2)
if pgrep.returncode != 0:
pgrep = subprocess.run(
["pgrep", "-f", "xdg-desktop-portal"], capture_output=True, timeout=2)
result["running"] = pgrep.returncode == 0
except Exception:
result["running"] = False
extra_dirs = ["/usr/libexec", "/usr/lib/xdg-desktop-portal",
"/usr/lib", "/usr/local/libexec"]
backend_found = bool(shutil.which(portal_pkg))
if not backend_found:
backend_found = any((Path(d) / portal_pkg).exists() for d in extra_dirs)
result["backend_found"] = backend_found
if not result["running"]:
result["reason"] = (
f"xdg-desktop-portal is installed but not running. "
f"Start it with: systemctl --user start xdg-desktop-portal")
return result
if not backend_found:
result["reason"] = (
f"The portal daemon is running but the {compositor.upper()} backend "
f"({portal_pkg}) was not found.")
return result
result["ok"] = True
result["reason"] = f"Portal OK ({portal_pkg} present and daemon running)"
return result
# ─────────────────────────────────────────────────────────────────────────────
# Utilities
# ─────────────────────────────────────────────────────────────────────────────
def slugify(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
def sanitize_shell_string(value: str) -> str:
return re.sub(r'[^a-zA-Z0-9 _.~/:?=&#%+@-]', '', value)
def get_browsers():
return CONFIG.get("browsers", DEFAULT_CONFIG.get("browsers", {}))
def get_profile_dir(app: dict) -> Path:
return CONFIG_DIR / "profiles" / slugify(app.get("name", "untitled"))
def profile_config_path(app: dict) -> Path:
return get_profile_dir(app) / "profile.json"
def load_profile_config(app: dict) -> dict:
p = profile_config_path(app)
if p.exists():
try:
return json.loads(p.read_text())
except Exception:
return {}
return {}
def save_profile_config(app: dict, data: dict):
pd = get_profile_dir(app)
pd.mkdir(parents=True, exist_ok=True)
target = profile_config_path(app)
tmp = target.with_suffix(".json.tmp")
try:
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
tmp.chmod(0o600)
tmp.replace(target)
except Exception as exc:
_logger.error("save_profile_config failed: %s", exc)
tmp.unlink(missing_ok=True)
raise
def get_hostname_from_url(url: str) -> str:
try:
parsed = urlparse(url)
hostname = parsed.netloc or parsed.path
return hostname.replace('www.', '').split('/')[0].split(':')[0]
except Exception:
return ""
PAID_UPDATE_MANIFEST_URL = (
"https://raw.githubusercontent.com/bobbycomet/Appify/main/windows-update.json")
PAID_UPDATE_INSTRUCTIONS = (
"Free updates are available to existing purchasers. Sign in to your Ko-fi account "
"and open Payments & Orders to download the latest Appify version.")
def check_paid_latest_version() -> "str | None":
"""Read the public version notice for paid desktop builds distributed through Ko-fi."""
try:
import urllib.request
import ssl
req = urllib.request.Request(
PAID_UPDATE_MANIFEST_URL,
headers={"Accept": "application/json",
"User-Agent": f"Appify/{CURRENT_VERSION}"})
with urllib.request.urlopen(req, context=ssl.create_default_context(),
timeout=8) as resp:
if resp.status != 200:
return None
data = json.loads(resp.read().decode("utf-8"))
except Exception as exc:
_logger.debug("Paid app update check failed: %s", exc)
return None
version = data.get("version") if isinstance(data, dict) else None
if not isinstance(version, str) or not version.strip():
_logger.warning("Paid app update manifest has no version")
return None
version = version.strip()
try:
Version(version)
except Exception as exc:
_logger.warning("Invalid paid app update version %r: %s", version, exc)
return None
return version
def check_for_updates(callback):
def _check():
try:
if IS_WINDOWS or IS_MAC:
latest_version = check_paid_latest_version()
if latest_version and Version(latest_version) > Version(CURRENT_VERSION):
msg = (f"New version available: {latest_version}!\n"
f"{PAID_UPDATE_INSTRUCTIONS}")
GLib.idle_add(callback, msg)
return
import urllib.request
import ssl
url = "https://api.github.com/repos/bobbycomet/Appify/releases/latest"
ctx = ssl.create_default_context()
req = urllib.request.Request(
url,
headers={"Accept": "application/vnd.github+json",
"User-Agent": f"Appify/{CURRENT_VERSION}"})
with urllib.request.urlopen(req, context=ctx, timeout=8) as resp:
if resp.status != 200:
return
data = json.loads(resp.read().decode())
if data.get("prerelease") or data.get("draft"):
return
latest_tag = data["tag_name"].lstrip("v")
if Version(latest_tag) > Version(CURRENT_VERSION):
msg = f"New version available: {data['tag_name']}!\nDownload from GitHub Releases."
GLib.idle_add(callback, msg)
except Exception as exc:
_logger.debug("Update check failed: %s", exc)
threading.Thread(target=_check, daemon=True).start()
APPIFY_GITHUB_REPO = "bobbycomet/Appify"
def check_appify_latest_release() -> "dict | None":
"""Fetch the latest GitHub release info for Appify itself (separate from the
lightweight check_for_updates() banner check — this one also grabs asset URLs
so we can actually download and install the update)."""
try:
import urllib.request, ssl
ctx = ssl.create_default_context()
req = urllib.request.Request(
f"https://api.github.com/repos/{APPIFY_GITHUB_REPO}/releases/latest",
headers={"Accept": "application/vnd.github+json",
"User-Agent": f"Appify/{CURRENT_VERSION}"})
with urllib.request.urlopen(req, context=ctx, timeout=10) as resp:
if resp.status != 200:
return None
data = json.loads(resp.read().decode())
except Exception as exc:
_logger.debug("check_appify_latest_release failed: %s", exc)
return None
if data.get("prerelease") or data.get("draft"):
return None
tag = data.get("tag_name", "")
if not tag:
return None
appimage_url = ""
deb_url = ""
exe_url = ""
exe_sha256 = ""
for asset in data.get("assets", []):
url = asset.get("browser_download_url", "")
name = (asset.get("name") or url.rsplit("/", 1)[-1]).lower()
if url.lower().endswith(".appimage"):
appimage_url = url
elif url.lower().endswith(".deb"):
deb_url = url
elif name.endswith(".exe") and "setup" in name: # Windows installer
exe_url = url
digest = str(asset.get("digest") or "")
if digest.startswith("sha256:"):
exe_sha256 = digest[len("sha256:"):].lower()
return {
"tag": tag,
"version": tag.lstrip("v"),
"appimage_url": appimage_url,
"deb_url": deb_url,
"exe_url": exe_url,
"exe_sha256": exe_sha256,
"html_url": data.get("html_url", f"https://github.com/{APPIFY_GITHUB_REPO}/releases"),
}
def _detect_appify_install_type() -> "tuple[str, str]":
"""Returns (install_type, path). install_type is 'appimage', 'deb',
'windows-installer', 'windows-portable' or 'unknown'."""
if IS_WINDOWS:
if IS_FROZEN:
exe = Path(sys.executable)
# Inno Setup drops unins000.exe next to the app; a zip extract doesn't.
kind = "windows-installer" if (exe.parent / "unins000.exe").exists() else "windows-portable"
return kind, str(exe)
return "unknown", ""
if IS_MAC:
executable = Path(sys.executable).resolve()
if IS_FROZEN and len(executable.parents) > 2 and executable.parents[2].suffix == ".app":
return "macos-app", str(executable.parents[2])
return "unknown", ""
env_appimage = os.environ.get("APPIMAGE", "")
if env_appimage and Path(env_appimage).is_file():
return "appimage", env_appimage
try:
result = subprocess.run(
["dpkg-query", "-W", "-f=${Status}", "appify"],
capture_output=True, text=True, timeout=5)
if "install ok installed" in result.stdout:
return "deb", ""
except Exception:
pass
return "unknown", ""
def _run_privileged_script(script: str, timeout: int = 60) -> "tuple[bool, str]":
try:
proc = subprocess.run(["pkexec", "bash", "-c", script],
capture_output=True, text=True, timeout=timeout)
if proc.returncode == 0:
return True, ""
return False, (proc.stderr or proc.stdout or f"exit code {proc.returncode}").strip()
except Exception as exc:
return False, str(exc)
def _appify_updater_timer_unit(schedule: str) -> str:
return (
"[Unit]\n"
f"Description=Run Appify Updater ({schedule})\n\n"
"[Timer]\n"
f"OnCalendar={schedule}\n"
"Persistent=true\n\n"
"[Install]\n"
"WantedBy=timers.target\n"
)
APPIFY_UPDATER_SERVICE_UNIT = \
'[Unit]\nDescription=Appify Updater Service\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/appify-updater.sh\n'
APPIFY_UPDATER_SCRIPT = \
'#!/bin/bash\nset -euo pipefail\n\n# =====================================\n# Appify Self-Updater\n# =====================================\n# Updates Appify itself from GitHub releases. Supports both AppImage and\n# .deb installs. Run as root (via the appify-updater.service/.timer pair).\n\nGITHUB_REPO="bobbycomet/Appify"\nCONFIG_FILE="/etc/appify-updater.conf"\nLOG_FILE="/var/log/appify-updater.log"\nCACHE_DIR="/var/cache/appify-updater"\nCACHE_FILE="$CACHE_DIR/last_check"\n\nmkdir -p "$CACHE_DIR" 2>/dev/null || true\n\n# Utility function for logging (stdout for the journal + a persistent logfile)\nlog() {\n local line\n line="[$(date \'+%Y-%m-%d %H:%M:%S\')] $*"\n echo "$line"\n echo "$line" >> "$LOG_FILE" 2>/dev/null || true\n}\n\n# Notification function (only if notify-send exists)\nnotify_user() {\n local message="$1"\n if command -v notify-send &>/dev/null; then\n for user_runtime in /run/user/*; do\n user_id=$(basename "$user_runtime")\n if [ -S "$user_runtime/bus" ]; then\n sudo -u "#$user_id" DBUS_SESSION_BUS_ADDRESS="unix:path=$user_runtime/bus" \\\n notify-send "Appify Updater" "$message" || true\n fi\n done\n else\n log "ℹ️ Notifications skipped (notify-send not installed)."\n fi\n}\n\n# Ensure required commands exist\nfor cmd in curl dpkg-query dpkg; do\n if ! command -v "$cmd" &>/dev/null; then\n echo "Error: Required command \'$cmd\' not found."\n exit 1\n fi\ndone\n\n# =====================================\n# Load / bootstrap config\n# =====================================\n# CONFIG_FILE format:\n# INSTALL_TYPE=appimage|deb\n# APPIMAGE_PATH=/full/path/to/Appify.AppImage (only used if INSTALL_TYPE=appimage)\n# DEB_PACKAGE_NAME=appify (only used if INSTALL_TYPE=deb)\n\nINSTALL_TYPE=""\nAPPIMAGE_PATH=""\nDEB_PACKAGE_NAME="appify"\n\nif [ -f "$CONFIG_FILE" ]; then\n # shellcheck disable=SC1090\n source "$CONFIG_FILE"\nfi\n\nbootstrap_config() {\n # Try to figure out how Appify is installed if no config exists yet.\n if dpkg-query -W -f=\'${Status}\' "$DEB_PACKAGE_NAME" 2>/dev/null | grep -q "install ok installed"; then\n INSTALL_TYPE="deb"\n log "Detected deb install of Appify (package: $DEB_PACKAGE_NAME)."\n else\n # Look for a recorded AppImage path in known desktop launcher files.\n local desktop_files=(\n "/usr/share/applications/appify.desktop"\n "/usr/local/share/applications/appify.desktop"\n )\n for df in "${desktop_files[@]}"; do\n if [ -f "$df" ]; then\n local exec_path\n exec_path=$(grep -m1 \'^Exec=\' "$df" | sed -E \'s/^Exec=//; s/ .*//\')\n if [ -n "$exec_path" ] && [ -f "$exec_path" ]; then\n INSTALL_TYPE="appimage"\n APPIMAGE_PATH="$exec_path"\n log "Detected AppImage install of Appify at: $APPIMAGE_PATH"\n break\n fi\n fi\n done\n fi\n\n if [ -z "$INSTALL_TYPE" ]; then\n log "⚠️ Could not detect how Appify is installed. Skipping this run."\n log " Create $CONFIG_FILE manually with INSTALL_TYPE=appimage (+ APPIMAGE_PATH=...) or INSTALL_TYPE=deb."\n exit 0\n fi\n\n {\n echo "INSTALL_TYPE=$INSTALL_TYPE"\n echo "APPIMAGE_PATH=$APPIMAGE_PATH"\n echo "DEB_PACKAGE_NAME=$DEB_PACKAGE_NAME"\n } > "$CONFIG_FILE"\n chmod 644 "$CONFIG_FILE"\n}\n\nif [ -z "$INSTALL_TYPE" ]; then\n bootstrap_config\nfi\n\nif [ "$INSTALL_TYPE" = "appimage" ] && { [ -z "$APPIMAGE_PATH" ] || [ ! -f "$APPIMAGE_PATH" ]; }; then\n log "❌ INSTALL_TYPE=appimage but APPIMAGE_PATH (\'$APPIMAGE_PATH\') doesn\'t exist. Fix $CONFIG_FILE."\n exit 1\nfi\n\n# =====================================\n# Determine currently installed version\n# =====================================\nif [ "$INSTALL_TYPE" = "deb" ]; then\n CURRENT_VERSION=$(dpkg-query -W -f=\'${Version}\' "$DEB_PACKAGE_NAME" 2>/dev/null || true)\nelse\n CURRENT_VERSION=$("$APPIMAGE_PATH" --print-version 2>/dev/null || true)\nfi\n\nif [ -z "$CURRENT_VERSION" ]; then\n log "⚠️ Could not determine the currently installed Appify version. Continuing anyway."\n CURRENT_VERSION="0"\nelse\n log "Current installed Appify version: $CURRENT_VERSION"\nfi\n\n# =====================================\n# Fetch latest release info from GitHub\n# =====================================\nlog "Checking for the latest Appify release..."\nRELEASE_JSON=$(curl -fsSL -H "Accept: application/vnd.github+json" \\\n "https://api.github.com/repos/${GITHUB_REPO}/releases/latest") || {\n log "❌ Failed to reach the GitHub releases API."\n exit 1\n}\n\nLATEST_TAG=$(echo "$RELEASE_JSON" | grep -m1 \'"tag_name"\' | sed -E \'s/.*"tag_name":[[:space:]]*"([^"]+)".*/\\1/\')\nif [ -z "$LATEST_TAG" ]; then\n log "❌ Failed to parse the latest release tag."\n exit 1\nfi\nLATEST_VERSION="${LATEST_TAG#v}"\n\necho "$(date -Iseconds) latest=$LATEST_VERSION" > "$CACHE_FILE" 2>/dev/null || true\n\nlog "Latest Appify version available: $LATEST_VERSION"\n\nif dpkg --compare-versions "$CURRENT_VERSION" ge "$LATEST_VERSION" 2>/dev/null; then\n log "✨ Appify is already up to date."\n exit 0\nfi\n\n# =====================================\n# Download + install the update\n# =====================================\nif [ "$INSTALL_TYPE" = "appimage" ]; then\n ASSET_URL=$(echo "$RELEASE_JSON" \\\n | grep -o \'"browser_download_url":[[:space:]]*"[^"]*\\.AppImage"\' \\\n | sed -E \'s/.*"(https[^"]+)"/\\1/\' | head -n1)\n if [ -z "$ASSET_URL" ]; then\n log "❌ No .AppImage asset found in the latest release."\n exit 1\n fi\n\n TMP_FILE=$(mktemp /tmp/appify.XXXXXX.AppImage)\n log "⬇️ Downloading Appify v$LATEST_VERSION (AppImage)..."\n if ! curl -fsSL -o "$TMP_FILE" "$ASSET_URL"; then\n log "❌ Failed to download the new AppImage."\n rm -f "$TMP_FILE"\n exit 1\n fi\n log "SHA-256: $(sha256sum "$TMP_FILE" | cut -d\' \' -f1)"\n\n chmod +x "$TMP_FILE"\n # Overwrite in place, at the exact path the user originally chose, so\n # desktop launchers/symlinks that point at APPIMAGE_PATH keep working.\n # mv within the same directory is atomic and effectively removes the old file.\n if ! mv -f "$TMP_FILE" "$APPIMAGE_PATH"; then\n log "❌ Failed to install the new AppImage to $APPIMAGE_PATH."\n rm -f "$TMP_FILE"\n exit 1\n fi\n chmod +x "$APPIMAGE_PATH"\n\n log "✅ Appify has been updated to version $LATEST_VERSION successfully! ($APPIMAGE_PATH)"\n notify_user "Appify has been updated to version $LATEST_VERSION ✅"\n\nelse\n DEB_URL=$(echo "$RELEASE_JSON" \\\n | grep -o \'"browser_download_url":[[:space:]]*"[^"]*\\.deb"\' \\\n | sed -E \'s/.*"(https[^"]+)"/\\1/\' | head -n1)\n if [ -z "$DEB_URL" ]; then\n log "❌ No .deb asset found in the latest release."\n exit 1\n fi\n\n DEB_FILE=$(mktemp /tmp/appify.XXXXXX.deb)\n log "⬇️ Downloading Appify v$LATEST_VERSION (.deb)..."\n if ! curl -fsSL -o "$DEB_FILE" "$DEB_URL"; then\n log "❌ Failed to download the new .deb package."\n rm -f "$DEB_FILE"\n exit 1\n fi\n log "SHA-256: $(sha256sum "$DEB_FILE" | cut -d\' \' -f1)"\n\n log "📦 Installing Appify v$LATEST_VERSION..."\n if ! apt-get install -y "$DEB_FILE"; then\n log "❌ Installation failed."\n rm -f "$DEB_FILE"\n exit 1\n fi\n rm -f "$DEB_FILE"\n\n log "✅ Appify has been updated to version $LATEST_VERSION successfully!"\n notify_user "Appify has been updated to version $LATEST_VERSION ✅"\nfi\n'
def is_appify_updater_installed() -> bool:
return Path("/etc/systemd/system/appify-updater.timer").exists()
def get_appify_updater_schedule() -> "str | None":
timer_path = Path("/etc/systemd/system/appify-updater.timer")
if not timer_path.exists():
return None
try:
for line in timer_path.read_text().splitlines():
line = line.strip()
if line.startswith("OnCalendar="):
return line.split("=", 1)[1].strip()
except Exception:
pass
return None
def enable_appify_updater(schedule: str, status_callback=None) -> bool:
"""Install the appify-updater.sh/.service/.timer/.conf files and enable the
timer, in a single pkexec prompt."""
install_type, appimage_path = _detect_appify_install_type()
if install_type == "unknown":
if status_callback:
status_callback("Could not detect a deb or AppImage install of Appify — "
"automatic updates unavailable.")
return False
tmp_dir = Path(tempfile.mkdtemp(prefix="appify-updater-"))
try:
sh_path = tmp_dir / "appify-updater.sh"
service_path = tmp_dir / "appify-updater.service"
timer_path = tmp_dir / "appify-updater.timer"
conf_path = tmp_dir / "appify-updater.conf"
sh_path.write_text(APPIFY_UPDATER_SCRIPT)
service_path.write_text(APPIFY_UPDATER_SERVICE_UNIT)
timer_path.write_text(_appify_updater_timer_unit(schedule))
conf_lines = [f"INSTALL_TYPE={install_type}"]
if install_type == "appimage":
conf_lines.append(f"APPIMAGE_PATH={appimage_path}")
conf_lines.append("DEB_PACKAGE_NAME=appify")
conf_path.write_text("\n".join(conf_lines) + "\n")
script = (
"set -e\n"
f"cp {shlex.quote(str(sh_path))} /usr/local/bin/appify-updater.sh\n"
"chmod 755 /usr/local/bin/appify-updater.sh\n"
f"cp {shlex.quote(str(service_path))} /etc/systemd/system/appify-updater.service\n"
f"cp {shlex.quote(str(timer_path))} /etc/systemd/system/appify-updater.timer\n"
f"cp {shlex.quote(str(conf_path))} /etc/appify-updater.conf\n"
"chmod 644 /etc/systemd/system/appify-updater.service "
"/etc/systemd/system/appify-updater.timer /etc/appify-updater.conf\n"
"systemctl daemon-reload\n"
"systemctl enable --now appify-updater.timer\n"
)
ok, err = _run_privileged_script(script)
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
if status_callback:
status_callback("Automatic update checks enabled." if ok
else f"Failed to enable automatic updates: {err}")
return ok
def set_appify_updater_schedule(schedule: str, status_callback=None) -> bool:
tmp_dir = Path(tempfile.mkdtemp(prefix="appify-updater-"))
try:
timer_path = tmp_dir / "appify-updater.timer"
timer_path.write_text(_appify_updater_timer_unit(schedule))
script = (
"set -e\n"
f"cp {shlex.quote(str(timer_path))} /etc/systemd/system/appify-updater.timer\n"
"chmod 644 /etc/systemd/system/appify-updater.timer\n"
"systemctl daemon-reload\n"
"systemctl restart appify-updater.timer\n"
)
ok, err = _run_privileged_script(script)
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
if status_callback:
status_callback(f"Update check schedule set to: {schedule}" if ok
else f"Failed to update schedule: {err}")
return ok
def disable_appify_updater(status_callback=None) -> bool:
ok, err = _run_privileged_script("systemctl disable --now appify-updater.timer")
if status_callback:
status_callback("Automatic update checks disabled." if ok
else f"Failed to disable automatic updates: {err}")
return ok
def _install_windows_update(release: dict, status_callback=None) -> bool:
"""Download the Setup.exe from the release and run it silently. The Inno
Setup script closes Appify, upgrades in place and relaunches it."""