forked from FaithLife-Community/LogosLinuxInstaller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1710 lines (1447 loc) · 63.3 KB
/
utils.py
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
import atexit
import distro
import hashlib
import json
import logging
import os
import psutil
import queue
import re
import requests
import shutil
import signal
import stat
import subprocess
import sys
import threading
import tkinter as tk
import zipfile
from base64 import b64encode
from datetime import datetime, timedelta
from packaging import version
from pathlib import Path
from typing import List, Union
from urllib.parse import urlparse
from xml.etree import ElementTree as ET
import config
import msg
import wine
import tui
class Props():
def __init__(self, uri=None):
self.path = None
self.size = None
self.md5 = None
if uri is not None:
self.path = uri
class FileProps(Props):
def __init__(self, f=None):
super().__init__(f)
if f is not None:
self.path = Path(self.path)
if self.path.is_file():
self.get_size()
# self.get_md5()
def get_size(self):
if self.path is None:
return
self.size = self.path.stat().st_size
return self.size
def get_md5(self):
if self.path is None:
return
md5 = hashlib.md5()
with self.path.open('rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
md5.update(chunk)
self.md5 = b64encode(md5.digest()).decode('utf-8')
logging.debug(f"{str(self.path)} MD5: {self.md5}")
return self.md5
class UrlProps(Props):
def __init__(self, url=None):
super().__init__(url)
self.headers = None
if url is not None:
self.get_headers()
self.get_size()
self.get_md5()
def get_headers(self):
if self.path is None:
self.headers = None
logging.debug(f"Getting headers from {self.path}.")
try:
h = {'Accept-Encoding': 'identity'} # force non-compressed txfr
r = requests.head(self.path, allow_redirects=True, headers=h)
except requests.exceptions.ConnectionError:
logging.critical("Failed to connect to the server.")
return None
except Exception as e:
logging.error(e)
return None
except KeyboardInterrupt:
print()
msg.logos_error("Interrupted by Ctrl+C")
return None
self.headers = r.headers
return self.headers
def get_size(self):
if self.headers is None:
r = self.get_headers()
if r is None:
return
content_length = self.headers.get('Content-Length')
content_encoding = self.headers.get('Content-Encoding')
if content_encoding is not None:
logging.critical(f"The server requires receiving the file compressed as '{content_encoding}'.") # noqa: E501
logging.debug(f"{content_length=}")
if content_length is not None:
self.size = int(content_length)
return self.size
def get_md5(self):
if self.headers is None:
r = self.get_headers()
if r is None:
return
if self.headers.get('server') == 'AmazonS3':
content_md5 = self.headers.get('etag')
if content_md5 is not None:
# Convert from hex to base64
content_md5_hex = content_md5.strip('"').strip("'")
content_md5 = b64encode(bytes.fromhex(content_md5_hex)).decode() # noqa: E501
else:
content_md5 = self.headers.get('Content-MD5')
if content_md5 is not None:
content_md5 = content_md5.strip('"').strip("'")
logging.debug(f"{content_md5=}")
if content_md5 is not None:
self.md5 = content_md5
return self.md5
# Set "global" variables.
def set_default_config():
get_os()
get_superuser_command()
get_package_manager()
if config.CONFIG_FILE is None:
config.CONFIG_FILE = config.DEFAULT_CONFIG_PATH
config.PRESENT_WORKING_DIRECTORY = os.getcwd()
config.MYDOWNLOADS = get_user_downloads_dir()
os.makedirs(os.path.dirname(config.LOGOS_LOG), exist_ok=True)
def set_runtime_config():
# Set runtime variables that are dependent on ones from config file.
if config.INSTALLDIR and not config.WINEPREFIX:
config.WINEPREFIX = f"{config.INSTALLDIR}/data/wine64_bottle"
if config.WINE_EXE and not config.WINESERVER_EXE:
bin_dir = Path(config.WINE_EXE).parent
config.WINESERVER_EXE = str(bin_dir / 'wineserver')
if config.FLPRODUCT and config.WINEPREFIX and not config.LOGOS_EXE:
config.LOGOS_EXE = find_installed_product()
def write_config(config_file_path):
logging.info(f"Writing config to {config_file_path}")
os.makedirs(os.path.dirname(config_file_path), exist_ok=True)
config_data = {key: config.__dict__.get(key) for key in config.core_config_keys} # noqa: E501
try:
with open(config_file_path, 'w') as config_file:
json.dump(config_data, config_file, indent=4, sort_keys=True)
config_file.write('\n')
except IOError as e:
msg.logos_error(f"Error writing to config file {config_file_path}: {e}") # noqa: E501
def update_config_file(config_file_path, key, value):
config_file_path = Path(config_file_path)
with config_file_path.open(mode='r') as f:
config_data = json.load(f)
if config_data.get(key) != value:
logging.info(f"Updating {str(config_file_path)} with: {key} = {value}")
config_data[key] = value
try:
with config_file_path.open(mode='w') as f:
json.dump(config_data, f, indent=4, sort_keys=True)
f.write('\n')
except IOError as e:
msg.logos_error(f"Error writing to config file {config_file_path}: {e}") # noqa: E501
def die_if_running():
PIDF = '/tmp/LogosLinuxInstaller.pid'
def remove_pid_file():
if os.path.exists(PIDF):
os.remove(PIDF)
if os.path.isfile(PIDF):
with open(PIDF, 'r') as f:
pid = f.read().strip()
message = f"The script is already running on PID {pid}. Should it be killed to allow this instance to run?" # noqa: E501
if config.DIALOG == "tk":
# TODO: With the GUI this runs in a thread. It's not clear if
# the messagebox will work correctly. It may need to be
# triggered from here with an event and then opened from the
# main thread.
tk_root = tk.Tk()
tk_root.withdraw()
confirm = tk.messagebox.askquestion("Confirmation", message)
tk_root.destroy()
elif config.DIALOG == "curses":
confirm = tui.confirm("Confirmation", message)
else:
confirm = msg.cli_question(message)
if confirm:
os.kill(int(pid), signal.SIGKILL)
atexit.register(remove_pid_file)
with open(PIDF, 'w') as f:
f.write(str(os.getpid()))
def die_if_root():
if os.getuid() == 0 and not config.LOGOS_FORCE_ROOT:
msg.logos_error("Running Wine/winetricks as root is highly discouraged. Use -f|--force-root if you must run as root. See https://wiki.winehq.org/FAQ#Should_I_run_Wine_as_root.3F") # noqa: E501
def die(message):
logging.critical(message)
sys.exit(1)
def run_command(command):
result = subprocess.run(command, check=True, text=True, capture_output=True)
return result.stdout
def reboot():
logging.info("Rebooting system.")
command = f"{config.SUPERUSER_COMMAND} reboot now"
subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True
)
sys.exit(0)
def restart_lli():
logging.debug("Restarting Logos Linux Installer.")
pidfile = Path('/tmp/LogosLinuxInstaller.pid')
if pidfile.is_file():
pidfile.unlink()
os.execv(sys.executable, [sys.executable])
sys.exit()
def set_verbose():
config.LOG_LEVEL = logging.INFO
config.WINEDEBUG = ''
def set_debug():
config.LOG_LEVEL = logging.DEBUG
config.WINEDEBUG = ""
def t(command):
if shutil.which(command) is not None:
return True
else:
return False
def tl(library):
try:
__import__(library)
return True
except ImportError:
return False
def get_dialog():
if not os.environ.get('DISPLAY'):
msg.logos_error("The installer does not work unless you are running a display") # noqa: E501
DIALOG = os.getenv('DIALOG')
config.GUI = False
# Set config.DIALOG.
if DIALOG is not None:
DIALOG = DIALOG.lower()
if DIALOG not in ['curses', 'tk']:
msg.logos_error("Valid values for DIALOG are 'curses' or 'tk'.")
config.DIALOG = DIALOG
elif sys.__stdin__.isatty():
config.DIALOG = 'curses'
else:
config.DIALOG = 'tk'
# Set config.GUI.
if config.DIALOG == 'tk':
config.GUI = True
def get_os():
# TODO: Remove if we can verify these are no longer needed commented code.
# Try reading /etc/os-release
# try:
# with open('/etc/os-release', 'r') as f:
# os_release_content = f.read()
# match = re.search(
# r'^ID=(\S+).*?VERSION_ID=(\S+)',
# os_release_content, re.MULTILINE
# )
# if match:
# config.OS_NAME = match.group(1)
# config.OS_RELEASE = match.group(2)
# return config.OS_NAME, config.OS_RELEASE
# except FileNotFoundError:
# pass
# Try using lsb_release command
# try:
# config.OS_NAME = platform.linux_distribution()[0]
# config.OS_RELEASE = platform.linux_distribution()[1]
# return config.OS_NAME, config.OS_RELEASE
# except AttributeError:
# pass
# Try reading /etc/lsb-release
# try:
# with open('/etc/lsb-release', 'r') as f:
# lsb_release_content = f.read()
# match = re.search(
# r'^DISTRIB_ID=(\S+).*?DISTRIB_RELEASE=(\S+)',
# lsb_release_content,
# re.MULTILINE
# )
# if match:
# config.OS_NAME = match.group(1)
# config.OS_RELEASE = match.group(2)
# return config.OS_NAME, config.OS_RELEASE
# except FileNotFoundError:
# pass
# Try reading /etc/debian_version
# try:
# with open('/etc/debian_version', 'r') as f:
# config.OS_NAME = 'Debian'
# config.OS_RELEASE = f.read().strip()
# return config.OS_NAME, config.OS_RELEASE
# except FileNotFoundError:
# pass
# Add more conditions for other distributions as needed
# Fallback to platform module
config.OS_NAME = distro.id() # FIXME: Not working. Returns "Linux".
logging.info(f"OS name: {config.OS_NAME}")
config.OS_RELEASE = distro.version()
logging.info(f"OS release: {config.OS_RELEASE}")
return config.OS_NAME, config.OS_RELEASE
def get_superuser_command():
if config.DIALOG == 'tk':
if shutil.which('pkexec'):
config.SUPERUSER_COMMAND = "pkexec"
else:
msg.logos_error("No superuser command found. Please install pkexec.") # noqa: E501
else:
if shutil.which('sudo'):
config.SUPERUSER_COMMAND = "sudo"
elif shutil.which('doas'):
config.SUPERUSER_COMMAND = "doas"
else:
msg.logos_error("No superuser command found. Please install sudo or doas.") # noqa: E501
logging.debug(f"{config.SUPERUSER_COMMAND=}")
def get_package_manager():
# Check for package manager and associated packages
if shutil.which('apt') is not None: # debian, ubuntu
config.PACKAGE_MANAGER_COMMAND_INSTALL = "apt install -y"
config.PACKAGE_MANAGER_COMMAND_REMOVE = "apt remove -y"
# IDEA: Switch to Python APT library?
# See https://github.com/FaithLife-Community/LogosLinuxInstaller/pull/33#discussion_r1443623996 # noqa: E501
config.PACKAGE_MANAGER_COMMAND_QUERY = "dpkg -l | grep -E '^.i '"
config.PACKAGES = "coreutils patch lsof wget findutils sed grep gawk winbind cabextract x11-apps binutils fuse3"
config.L9PACKAGES = "" # FIXME: Missing Logos 9 Packages
config.BADPACKAGES = "appimagelauncher"
elif shutil.which('dnf') is not None: # rhel, fedora
config.PACKAGE_MANAGER_COMMAND_INSTALL = "dnf install -y"
config.PACKAGE_MANAGER_COMMAND_REMOVE = "dnf remove -y"
config.PACKAGE_MANAGER_COMMAND_QUERY = "dnf list installed | grep -E ^"
config.PACKAGES = "patch mod_auth_ntlm_winbind samba-winbind samba-winbind-clients cabextract" # noqa: E501
config.L9PACKAGES = "" # FIXME: Missing Logos 9 Packages
config.BADPACKAGES = "appiamgelauncher"
elif shutil.which('pamac') is not None: # manjaro
config.PACKAGE_MANAGER_COMMAND_INSTALL = "pamac install --no-upgrade --no-confirm" # noqa: E501
config.PACKAGE_MANAGER_COMMAND_REMOVE = "pamac remove --no-confirm"
config.PACKAGE_MANAGER_COMMAND_QUERY = "pamac list -i | grep -E ^"
config.PACKAGES = "wget sed grep gawk cabextract samba" # noqa: E501
config.L9PACKAGES = "" # FIXME: Missing Logos 9 Packages
config.BADPACKAGES = "appimagelauncher"
elif shutil.which('pacman') is not None: # arch, steamOS
config.PACKAGE_MANAGER_COMMAND_INSTALL = r"pacman -Syu --overwrite * --noconfirm --needed" # noqa: E501
config.PACKAGE_MANAGER_COMMAND_REMOVE = r"pacman -R --no-confirm"
config.PACKAGE_MANAGER_COMMAND_QUERY = "pacman -Q | grep -E ^"
if config.OS_NAME == "steamos": # steamOS
config.PACKAGES = "patch wget sed grep gawk cabextract samba bc libxml2 curl print-manager system-config-printer cups-filters nss-mdns foomatic-db-engine foomatic-db-ppds foomatic-db-nonfree-ppds ghostscript glibc samba extra-rel/apparmor core-rel/libcurl-gnutls winetricks appmenu-gtk-module lib32-libjpeg-turbo qt5-virtualkeyboard wine-staging giflib lib32-giflib libpng lib32-libpng libldap lib32-libldap gnutls lib32-gnutls mpg123 lib32-mpg123 openal lib32-openal v4l-utils lib32-v4l-utils libpulse lib32-libpulse libgpg-error lib32-libgpg-error alsa-plugins lib32-alsa-plugins alsa-lib lib32-alsa-lib libjpeg-turbo lib32-libjpeg-turbo sqlite lib32-sqlite libxcomposite lib32-libxcomposite libxinerama lib32-libgcrypt libgcrypt lib32-libxinerama ncurses lib32-ncurses ocl-icd lib32-ocl-icd libxslt lib32-libxslt libva lib32-libva gtk3 lib32-gtk3 gst-plugins-base-libs lib32-gst-plugins-base-libs vulkan-icd-loader lib32-vulkan-icd-loader"
else: # arch
config.PACKAGES = "patch wget sed grep cabextract samba glibc samba apparmor libcurl-gnutls winetricks appmenu-gtk-module lib32-libjpeg-turbo wine giflib lib32-giflib libpng lib32-libpng libldap lib32-libldap gnutls lib32-gnutls mpg123 lib32-mpg123 openal lib32-openal v4l-utils lib32-v4l-utils libpulse lib32-libpulse libgpg-error lib32-libgpg-error alsa-plugins lib32-alsa-plugins alsa-lib lib32-alsa-lib libjpeg-turbo lib32-libjpeg-turbo sqlite lib32-sqlite libxcomposite lib32-libxcomposite libxinerama lib32-libgcrypt libgcrypt lib32-libxinerama ncurses lib32-ncurses ocl-icd lib32-ocl-icd libxslt lib32-libxslt libva lib32-libva gtk3 lib32-gtk3 gst-plugins-base-libs lib32-gst-plugins-base-libs vulkan-icd-loader lib32-vulkan-icd-loader"
config.L9PACKAGES = "" # FIXME: Missing Logos 9 Packages
config.BADPACKAGES = "appimagelauncher"
# Add more conditions for other package managers as needed
# Add logging output.
logging.debug(f"{config.PACKAGE_MANAGER_COMMAND_INSTALL=}")
logging.debug(f"{config.PACKAGE_MANAGER_COMMAND_QUERY=}")
logging.debug(f"{config.PACKAGES=}")
logging.debug(f"{config.L9PACKAGES=}")
def get_runmode():
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
return 'binary'
else:
return 'script'
def query_packages(packages, mode="install"):
if config.SKIP_DEPENDENCIES:
return
missing_packages = []
conflicting_packages = []
for p in packages:
command = f"{config.PACKAGE_MANAGER_COMMAND_QUERY}{p}"
logging.debug(f"pkg query command: \"{command}\"")
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True
)
logging.debug(f"pkg query result: {result.returncode}")
if result.returncode != 0 and mode == "install":
missing_packages.append(p)
elif result.returncode == 0 and mode == "remove":
conflicting_packages.append(p)
msg = 'None'
if mode == "install":
if missing_packages:
msg = f"Missing packages: {' '.join(missing_packages)}"
logging.info(f"Missing packages: {msg}")
return missing_packages
if mode == "remove":
if conflicting_packages:
msg = f"Conflicting packages: {' '.join(conflicting_packages)}"
logging.info(f"Conflicting packages: {msg}")
return conflicting_packages
def install_packages(packages):
if config.SKIP_DEPENDENCIES:
return
if packages:
command = f"{config.SUPERUSER_COMMAND} {config.PACKAGE_MANAGER_COMMAND_INSTALL} {' '.join(packages)}" # noqa: E501
logging.debug(f"install_packages cmd: {command}")
result = run_command(command)
def remove_packages(packages):
if config.SKIP_DEPENDENCIES:
return
if packages:
command = f"{config.SUPERUSER_COMMAND} {config.PACKAGE_MANAGER_COMMAND_REMOVE} {' '.join(packages)}" # noqa: E501
logging.debug(f"remove_packages cmd: {command}")
result = run_command(command)
def have_dep(cmd):
if shutil.which(cmd) is not None:
return True
else:
return False
def clean_all():
logging.info("Cleaning all temp files…")
os.system("rm -fr /tmp/LBS.*")
os.system(f"rm -fr {config.WORKDIR}")
os.system(f"rm -f {config.PRESENT_WORKING_DIRECTORY}/wget-log*")
logging.info("done")
def mkdir_critical(directory):
try:
os.mkdir(directory)
except OSError:
msg.logos_error(f"Can't create the {directory} directory")
def get_user_downloads_dir():
home = Path.home()
xdg_config = Path(os.getenv('XDG_CONFIG_HOME', home / '.config'))
user_dirs_file = xdg_config / 'user-dirs.dirs'
downloads_path = str(home / 'Downloads')
if user_dirs_file.is_file():
with user_dirs_file.open() as f:
for line in f.readlines():
if 'DOWNLOAD' in line:
downloads_path = line.rstrip().split('=')[1].replace(
'$HOME',
str(home)
).strip('"')
break
return downloads_path
def cli_download(uri, destination):
message = f"Downloading '{uri}' to '{destination}'"
logging.info(message)
msg.cli_msg(message)
# Set target.
if destination != destination.rstrip('/'):
target = os.path.join(destination, os.path.basename(uri))
if not os.path.isdir(destination):
os.makedirs(destination)
elif os.path.isdir(destination):
target = os.path.join(destination, os.path.basename(uri))
else:
target = destination
dirname = os.path.dirname(destination)
if not os.path.isdir(dirname):
os.makedirs(dirname)
# Download from uri in thread while showing progress bar.
cli_queue = queue.Queue()
args = [uri]
kwargs = {'q': cli_queue, 'target': target}
t = threading.Thread(target=net_get, args=args, kwargs=kwargs, daemon=True)
t.start()
try:
while t.is_alive():
if cli_queue.empty():
continue
write_progress_bar(cli_queue.get())
print()
except KeyboardInterrupt:
print()
msg.logos_error('Interrupted with Ctrl+C')
def logos_reuse_download(
SOURCEURL,
FILE,
TARGETDIR,
app=None,
):
DIRS = [
config.INSTALLDIR,
os.getcwd(),
config.MYDOWNLOADS,
]
FOUND = 1
for i in DIRS:
if i is not None:
logging.debug(f"Checking {i} for {FILE}.")
file_path = Path(i) / FILE
if os.path.isfile(file_path):
logging.info(f"{FILE} exists in {i}. Verifying properties.")
if verify_downloaded_file(
SOURCEURL,
file_path,
app=app,
):
logging.info(f"{FILE} properties match. Using it…")
msg.cli_msg(f"Copying {FILE} into {TARGETDIR}")
try:
shutil.copy(os.path.join(i, FILE), TARGETDIR)
except shutil.SameFileError:
pass
FOUND = 0
break
else:
logging.info(f"Incomplete file: {file_path}.")
if FOUND == 1:
file_path = os.path.join(config.MYDOWNLOADS, FILE)
if config.DIALOG == 'tk' and app:
# Ensure progress bar.
app.stop_indeterminate_progress()
# Start download.
net_get(
SOURCEURL,
target=file_path,
app=app,
)
else:
cli_download(SOURCEURL, file_path)
if verify_downloaded_file(
SOURCEURL,
file_path,
app=app,
):
msg.cli_msg(f"Copying: {FILE} into: {TARGETDIR}")
try:
shutil.copy(os.path.join(config.MYDOWNLOADS, FILE), TARGETDIR)
except shutil.SameFileError:
pass
else:
msg.logos_error(f"Bad file size or checksum: {file_path}")
def delete_symlink(symlink_path):
symlink_path = Path(symlink_path)
if symlink_path.is_symlink():
try:
symlink_path.unlink()
logging.info(f"Symlink at {symlink_path} removed successfully.")
except Exception as e:
logging.error(f"Error removing symlink: {e}")
def preinstall_dependencies_ubuntu():
try:
run_command(["sudo", "dpkg", "--add-architecture", "i386"])
run_command(["sudo", "mkdir", "-pm755", "/etc/apt/keyrings"])
run_command(
["sudo", "wget", "-O", "/etc/apt/keyrings/winehq-archive.key", "https://dl.winehq.org/wine-builds/winehq.key"])
lsboutput = run_command(["lsb_release", "-a"])
codename = [line for line in lsboutput.split('\n') if "Description" in line][0].split()[1].strip()
run_command(["sudo", "wget", "-NP", "/etc/apt/sources.list.d/",
f"https://dl.winehq.org/wine-builds/ubuntu/dists/{codename}/winehq-{codename}.sources"])
run_command(["sudo", "apt", "update"])
run_command(["sudo", "apt", "install", "--install-recommends", "winehq-staging"])
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e}")
print(f"Command output: {e.output}")
def preinstall_dependencies_steamos():
command = [config.SUPERUSER_COMMAND, "steamos-readonly", "disable"]
result = run_command(command)
command = [config.SUPERUSER_COMMAND, "pacman-key", "--init"]
result = run_command(command)
command = [config.SUPERUSER_COMMAND, "pacman-key", "--populate", "archlinux"]
result = run_command(command)
def postinstall_dependencies_steamos():
command =[
config.SUPERUSER_COMMAND,
"sed", '-i',
's/mymachines resolve/mymachines mdns_minimal [NOTFOUND=return] resolve/', # noqa: E501
'/etc/nsswitch.conf'
]
result = run_command(command)
command =[config.SUPERUSER_COMMAND, "locale-gen"]
result = run_command(command)
command =[
config.SUPERUSER_COMMAND,
"systemctl",
"enable",
"--now",
"avahi-daemon"
]
result = run_command(command)
command =[config.SUPERUSER_COMMAND, "systemctl", "enable", "--now", "cups"]
result = run_command(command)
command = [config.SUPERUSER_COMMAND, "steamos-readonly", "enable"]
result = run_command(command)
def preinstall_dependencies():
if config.OS_NAME == "Ubuntu" or config.OS_NAME == "Linux Mintn":
preinstall_dependencies_ubuntu()
elif config.OS_NAME == "Steam":
preinstall_dependencies_steamos()
def postinstall_dependencies():
if config.OS_NAME == "Steam":
postinstall_dependencies_steamos()
def install_dependencies(packages, badpackages, logos9_packages=None):
missing_packages = []
conflicting_packages = []
package_list = []
if packages:
package_list = packages.split()
bad_package_list = []
if badpackages:
bad_package_list = badpackages.split()
if logos9_packages:
package_list.extend(logos9_packages.split())
if config.PACKAGE_MANAGER_COMMAND_QUERY:
missing_packages = query_packages(package_list)
conflicting_packages = query_packages(bad_package_list, "remove")
if config.PACKAGE_MANAGER_COMMAND_INSTALL:
if missing_packages and conflicting_packages:
message = f"Your {config.OS_NAME} computer requires installing and removing some software. To continue, the program will attempt to install the package(s): {missing_packages} by using ({config.PACKAGE_MANAGER_COMMAND_INSTALL}) and will remove the package(s): {conflicting_packages} by using ({config.PACKAGE_MANAGER_COMMAND_REMOVE}). Proceed?" # noqa: E501
logging.critical(message)
elif missing_packages:
message = f"Your {config.OS_NAME} computer requires installing some software. To continue, the program will attempt to install the package(s): {missing_packages} by using ({config.PACKAGE_MANAGER_COMMAND_INSTALL}). Proceed?" # noqa: E501
logging.critical(message)
elif conflicting_packages:
message = f"Your {config.OS_NAME} computer requires removing some software. To continue, the program will attempt to remove the package(s): {conflicting_packages} by using ({config.PACKAGE_MANAGER_COMMAND_REMOVE}). Proceed?" # noqa: E501
logging.critical(message)
else:
logging.debug("No missing or conflicting dependencies found.")
# TODO: Need to send continue question to user based on DIALOG.
# All we do above is create a message that we never send.
# Do we need a TK continue question? I see we have a CLI and curses one
# in msg.py
preinstall_dependencies()
# libfuse: for AppImage use. This is the only known needed library.
check_libs(["libfuse"])
if missing_packages:
install_packages(missing_packages)
if conflicting_packages:
# AppImage Launcher is the only known conflicting package.
remove_packages(conflicting_packages)
config.REBOOT_REQUIRED = True
postinstall_dependencies()
if config.REBOOT_REQUIRED:
# TODO: Add resumable install functionality to speed up running the
# program after reboot. See #19.
reboot()
else:
msg.logos_error(
f"The script could not determine your {config.OS_NAME} install's package manager or it is unsupported. Your computer is missing the command(s) {missing_packages}. Please install your distro's package(s) associated with {missing_packages} for {config.OS_NAME}.") # noqa: E501
def have_lib(library, ld_library_path):
roots = ['/usr/lib', '/lib']
if ld_library_path is not None:
roots = [*ld_library_path.split(':'), *roots]
for root in roots:
libs = [lib for lib in Path(root).rglob(f"{library}*")]
if len(libs) > 0:
logging.debug(f"'{library}' found at '{libs[0]}'")
return True
return False
def check_libs(libraries):
ld_library_path = os.environ.get('LD_LIBRARY_PATH', '')
for library in libraries:
have_lib_result = have_lib(library, ld_library_path)
if have_lib_result:
logging.info(f"* {library} is installed!")
else:
if config.PACKAGE_MANAGER_COMMAND_INSTALL:
message = f"Your {config.OS_NAME} install is missing the library: {library}. To continue, the script will attempt to install the library by using {config.PACKAGE_MANAGER_COMMAND_INSTALL}. Proceed?" # noqa: E501
if msg.cli_continue_question(message, "", ""):
install_packages(config.PACKAGES)
else:
msg.logos_error(
f"The script could not determine your {config.OS_NAME} install's package manager or it is unsupported. Your computer is missing the library: {library}. Please install the package associated with {library} for {config.OS_NAME}.") # noqa: E501
def check_dependencies(app=None):
if config.TARGETVERSION:
targetversion = int(config.TARGETVERSION)
else:
targetversion = 10
logging.info(f"Checking Logos {str(targetversion)} dependencies…")
if app:
app.status_q.put(f"Checking Logos {str(targetversion)} dependencies…")
app.root.event_generate('<<UpdateStatus>>')
if targetversion == 10:
install_dependencies(config.PACKAGES, config.BADPACKAGES)
elif targetversion == 9:
install_dependencies(
config.PACKAGES,
config.BADPACKAGES,
config.L9PACKAGES
)
else:
logging.error(f"TARGETVERSION not found: {config.TARGETVERSION}.")
if app:
app.root.event_generate('<<StopIndeterminateProgress>>')
def file_exists(file_path):
if file_path is not None:
expanded_path = os.path.expanduser(file_path)
return os.path.isfile(expanded_path)
else:
return False
def check_logos_release_version(version, threshold, check_version_part):
version_parts = list(map(int, version.split('.')))
return version_parts[check_version_part - 1] < threshold
def filter_versions(versions, threshold, check_version_part):
return [version for version in versions if check_logos_release_version(version, threshold, check_version_part)] # noqa: E501
def get_logos_releases(app=None):
# Use already-downloaded list if requested again.
downloaded_releases = None
if config.TARGETVERSION == '9' and config.LOGOS9_RELEASES:
downloaded_releases = config.LOGOS9_RELEASES
elif config.TARGETVERSION == '10' and config.LOGOS10_RELEASES:
downloaded_releases = config.LOGOS10_RELEASES
if downloaded_releases:
logging.debug(f"Using already-downloaded list of v{config.TARGETVERSION} releases") # noqa: E501
if app:
app.releases_q.put(downloaded_releases)
app.root.event_generate(app.release_evt)
return downloaded_releases
msg.cli_msg(f"Downloading release list for {config.FLPRODUCT} {config.TARGETVERSION}…") # noqa: E501
# NOTE: This assumes that Verbum release numbers continue to mirror Logos.
url = f"https://clientservices.logos.com/update/v1/feed/logos{config.TARGETVERSION}/stable.xml" # noqa: E501
response_xml_bytes = net_get(url)
# if response_xml is None and None not in [q, app]:
if response_xml_bytes is None:
if app:
app.releases_q.put(None)
app.root.event_generate(app.release_evt)
return None
# Parse XML
root = ET.fromstring(response_xml_bytes.decode('utf-8-sig'))
# Define namespaces
namespaces = {
'ns0': 'http://www.w3.org/2005/Atom',
'ns1': 'http://services.logos.com/update/v1/'
}
# Extract versions
releases = []
# Obtain all listed releases.
for entry in root.findall('.//ns1:version', namespaces):
release = entry.text
releases.append(release)
# if len(releases) == 5:
# break
filtered_releases = filter_versions(releases, 30, 1)
logging.debug(f"Available releases: {', '.join(releases)}")
logging.debug(f"Filtered releases: {', '.join(filtered_releases)}")
if app:
app.releases_q.put(filtered_releases)
app.root.event_generate(app.release_evt)
return filtered_releases
def get_winebin_code_and_desc(binary):
# Set binary code, description, and path based on path
codes = {
"Recommended": "Use the recommended AppImage",
"AppImage": "AppImage of Wine64",
"System": "Use the system binary (i.e., /usr/bin/wine64). WINE must be 7.18-staging or later, or 8.16-devel or later, and cannot be version 8.0.", # noqa: E501
"Proton": "Install using the Steam Proton fork of WINE.",
"PlayOnLinux": "Install using a PlayOnLinux WINE64 binary.",
"Custom": "Use a WINE64 binary from another directory.",
}
# TODO: The GUI currently cannot distinguish between the recommended
# AppImage and another on the system. We need to add some manner of making
# this distinction in the GUI, which is why the wine binary codes exist.
# Currently the GUI only accept an array with a single element, the binary
# itself; this will need to be modified to a two variable array, at the
# least, even if we hide the wine binary code, but it might be useful to
# tell the GUI user that a particular AppImage/binary is recommended.
# Below is my best guess for how to do this with the single element array…
# Does it work?
if binary == f"{config.APPDIR_BINDIR}/{config.RECOMMENDED_WINE64_APPIMAGE_FULL_FILENAME}": # noqa: E501
code = "Recommended"
elif binary.lower().endswith('.appimage'):
code = "AppImage"
elif "/usr/bin/" in binary:
code = "System"
elif "Proton" in binary:
code = "Proton"
elif "PlayOnLinux" in binary:
code = "PlayOnLinux"
else:
code = "Custom"
desc = codes.get(code)
logging.debug(f"{binary} code & desc: {code}; {desc}")
return code, desc
def get_wine_options(appimages, binaries, app=None) -> Union[List[List[str]], List[str]]: # noqa: E501
logging.debug(f"{appimages=}")
logging.debug(f"{binaries=}")
wine_binary_options = []
# Add AppImages to list
if config.DIALOG == 'tk':
wine_binary_options.append(f"{config.APPDIR_BINDIR}/{config.RECOMMENDED_WINE64_APPIMAGE_FULL_FILENAME}") # noqa: E501
wine_binary_options.extend(appimages)
else:
appimage_entries = [["AppImage", filename, "AppImage of Wine64"] for filename in appimages] # noqa: E501
wine_binary_options.append([
"Recommended", # Code
f'{config.APPDIR_BINDIR}/{config.RECOMMENDED_WINE64_APPIMAGE_FULL_FILENAME}', # noqa: E501
f"AppImage of Wine64 {config.RECOMMENDED_WINE64_APPIMAGE_FULL_VERSION}" # noqa: E501
])
wine_binary_options.extend(appimage_entries)
sorted_binaries = sorted(list(set(binaries)))
logging.debug(f"{sorted_binaries=}")
for WINEBIN_PATH in sorted_binaries:
WINEBIN_CODE, WINEBIN_DESCRIPTION = get_winebin_code_and_desc(WINEBIN_PATH) # noqa: E501
# Create wine binary option array
if config.DIALOG == 'tk':
wine_binary_options.append(WINEBIN_PATH)
else:
wine_binary_options.append(
[WINEBIN_CODE, WINEBIN_PATH, WINEBIN_DESCRIPTION]
)
if config.DIALOG != 'tk':
wine_binary_options.append(["Exit", "Exit", "Cancel installation."])
logging.debug(f"{wine_binary_options=}")
if app:
app.wines_q.put(wine_binary_options)
app.root.event_generate(app.wine_evt)
return wine_binary_options
def get_winetricks_options():
local_winetricks_path = shutil.which('winetricks')
winetricks_options = ['Download']
if local_winetricks_path is not None:
# Check if local winetricks version is up-to-date.
cmd = ["winetricks", "--version"]
local_winetricks_version = subprocess.check_output(cmd).split()[0]
if str(local_winetricks_version) >= "20220411":
winetricks_options.insert(0, local_winetricks_path)
else:
logging.info("Local winetricks is too old.")
else:
logging.info("Local winetricks not found.")
return winetricks_options
def install_winetricks(
installdir,
app=None,
version=config.WINETRICKS_VERSION,
):
msg.cli_msg(f"Installing winetricks v{version}…")
base_url = "https://codeload.github.com/Winetricks/winetricks/zip/refs/tags" # noqa: E501
zip_name = f"{version}.zip"
logos_reuse_download(
f"{base_url}/{version}",
zip_name,
config.MYDOWNLOADS,
app=app,
)
wtzip = f"{config.MYDOWNLOADS}/{zip_name}"
logging.debug(f"Extracting winetricks script into {installdir}…")
with zipfile.ZipFile(wtzip) as z:
for zi in z.infolist():
if zi.is_dir():
continue
zi.filename = Path(zi.filename).name
if zi.filename == 'winetricks':
z.extract(zi, path=installdir)
break
os.chmod(f"{installdir}/winetricks", 0o755)
logging.debug("Winetricks installed.")
def get_pids_using_file(file_path, mode=None):
pids = set()
for proc in psutil.process_iter(['pid', 'open_files']):
try: