-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathNSLGameScanner.py
More file actions
6154 lines (4861 loc) · 237 KB
/
NSLGameScanner.py
File metadata and controls
6154 lines (4861 loc) · 237 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
import os
import re
import json
import shutil
import binascii
import ctypes
import gzip
import zipfile
import time
import sys
import subprocess
import sqlite3
import csv
import configparser
import certifi
import itertools
import shlex
import ssl
import socket
import base64
import http.client
from datetime import datetime
from base64 import b64encode
import xml.etree.ElementTree as ET
import urllib
import urllib.request
import urllib.error
from urllib.request import urlopen, urlretrieve
from urllib.parse import (
urlparse,
urlsplit,
urlunsplit,
quote
)
# Check the value of the DBUS_SESSION_BUS_ADDRESS environment variable
dbus_address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not dbus_address or not dbus_address.startswith('unix:path='):
# Set the value of the DBUS_SESSION_BUS_ADDRESS environment variable
dbus_address = f'unix:path=/run/user/{os.getuid()}/bus'
os.environ['DBUS_SESSION_BUS_ADDRESS'] = dbus_address
# Path to the env_vars file
env_vars_path = f"{os.environ['HOME']}/.config/systemd/user/env_vars"
env_vars_dir = os.path.dirname(env_vars_path)
if not os.path.exists(env_vars_dir):
os.makedirs(env_vars_dir)
# Check if the env_vars file exists
if not os.path.exists(env_vars_path):
# If it doesn't exist, create it as an empty file
with open(env_vars_path, 'w'):
pass
print(f"Env vars file path is: {env_vars_path}")
# Read variables from the file
with open(env_vars_path, 'r') as f:
lines = f.readlines()
separate_appids = None
for line in lines:
if line.startswith('export '):
line = line[7:] # Remove 'export '
# Parse the name and value
if '=' in line:
name, value = line.strip().split('=', 1)
os.environ[name] = value
# Track separate_appids if explicitly set to false
if name == 'separate_appids' and value.strip().lower() == 'false':
separate_appids = value.strip()
# Variables from NonSteamLaunchers.sh
steamid3 = os.environ['steamid3']
logged_in_home = os.environ['logged_in_home']
compat_tool_name = os.environ['compat_tool_name']
python_version = os.environ['python_version']
#Scanner Variables
epic_games_launcher = os.environ.get('epic_games_launcher', '')
ubisoft_connect_launcher = os.environ.get('ubisoft_connect_launcher', '')
ea_app_launcher = os.environ.get('ea_app_launcher', '')
gog_galaxy_launcher = os.environ.get('gog_galaxy_launcher', '')
bnet_launcher = os.environ.get('bnet_launcher', '')
amazon_launcher = os.environ.get('amazon_launcher', '')
itchio_launcher = os.environ.get('itchio_launcher', '')
legacy_launcher = os.environ.get('legacy_launcher', '')
vkplay_launcher = os.environ.get('vkplay_launcher', '')
hoyoplay_launcher = os.environ.get('hoyoplay_launcher', '')
gamejolt_launcher = os.environ.get('gamejolt_launcher', '')
minecraft_launcher = os.environ.get('minecraft_launcher', '')
indie_launcher = os.environ.get('indie_launcher', '')
stove_launcher = os.environ.get('stove_launcher', '')
humble_launcher = os.environ.get('humble_launcher', '')
gryphlink_launcher = os.environ.get('gryphlink_launcher', '')
#Variables of the Launchers
# Define the path of the Launchers
epicshortcutdirectory = os.environ.get('epicshortcutdirectory')
gogshortcutdirectory = os.environ.get('gogshortcutdirectory')
uplayshortcutdirectory = os.environ.get('uplayshortcutdirectory')
battlenetshortcutdirectory = os.environ.get('battlenetshortcutdirectory')
eaappshortcutdirectory = os.environ.get('eaappshortcutdirectory')
amazonshortcutdirectory = os.environ.get('amazonshortcutdirectory')
itchioshortcutdirectory = os.environ.get('itchioshortcutdirectory')
legacyshortcutdirectory = os.environ.get('legacyshortcutdirectory')
humbleshortcutdirectory = os.environ.get('humbleshortcutdirectory')
gryphlinkshortcutdirectory = os.environ.get('gryphlinkshortcutdirectory')
indieshortcutdirectory = os.environ.get('indieshortcutdirectory')
rockstarshortcutdirectory = os.environ.get('rockstarshortcutdirectory')
glyphshortcutdirectory = os.environ.get('glyphshortcutdirectory')
minecraftshortcutdirectory = os.environ.get('minecraftshortcutdirectory')
psplusshortcutdirectory = os.environ.get('psplusshortcutdirectory')
vkplayshortcutdirectory = os.environ.get('vkplayshortcutdirectory')
hoyoplayshortcutdirectory = os.environ.get('hoyoplayshortcutfirectory')
nexonshortcutdirectory = os.environ.get('nexonshortcutdirectory')
gamejoltshortcutdirectory = os.environ.get('gamejoltshortcutdirectory')
artixgameshortcutdirectory = os.environ.get('artixgameshortcutdirectory')
arcshortcutdirectory = os.environ.get('arcshortcutdirectory')
purpleshortcutdirectory = os.environ.get('purpleshortcutdirectory')
plariumshortcutdirectory = os.environ.get('plariumshortcutdirectory')
vfunshortcutdirectory = os.environ.get('vfunshortcutdirectory')
temposhortcutdirectory = os.environ.get('temposhortcutdirectory')
poketcgshortcutdirectory = os.environ.get('poketcgshortcutdirectory')
antstreamshortcutdirectory = os.environ.get('antstreamshortcutdirectory')
stoveshortcutdirectory = os.environ.get('stoveshortcutdirectory')
bigfishshortcutdirectory = os.environ.get('bigfishshortcutdirectory')
repaireaappshortcutdirectory = os.environ.get('repaireaappshortcutdirectory')
#Streaming
chromedirectory = os.environ.get('chromedirectory')
names_str = os.environ.get("custom_website_names_str", "")
websites_str = os.environ.get("custom_websites_str", "")
custom_names = [n.strip() for n in names_str.split(",") if n.strip()]
custom_websites = [w.strip() for w in websites_str.split(",") if w.strip()]
base_launch_options = os.environ.get("customchromelaunchoptions")
parent_folder = os.path.expanduser(f"{logged_in_home}/.config/systemd/user/Modules")
if parent_folder not in sys.path:
sys.path.insert(0, parent_folder)
print(sys.path)
# Now import your modules after the single insert
import vdf
#Set Up nslgamescanner.service
# Define the paths
service_path = f"{logged_in_home}/.config/systemd/user/nslgamescanner.service"
# Define the service file content
service_content = f"""
[Unit]
Description=NSL Game Scanner
[Service]
ExecStart=/usr/bin/python3 '{logged_in_home}/.config/systemd/user/NSLGameScanner.py'
Restart=always
RestartSec=20
StartLimitBurst=40
StartLimitInterval=240
[Install]
WantedBy=default.target
"""
# Check if the service file already exists
if not os.path.exists(service_path):
# Create the service file
with open(service_path, 'w') as f:
f.write(service_content)
print("Service file created.")
# Check if the service is already running
result = subprocess.run(['systemctl', '--user', 'is-active', 'nslgamescanner.service'], stdout=subprocess.PIPE)
if result.stdout.decode('utf-8').strip() != 'active':
# Reload the systemd manager configuration
subprocess.run(['systemctl', '--user', 'daemon-reload'])
# Enable the service to start on boot
subprocess.run(['systemctl', '--user', 'enable', 'nslgamescanner.service'])
# Start the service immediately
#subprocess.run(['systemctl', '--user', 'start', 'nslgamescanner.service'])
print("Service started.")
else:
print("Service is already running.")
#Code
def get_steam_shortcut_id(exe_path, display_name):
unique_id = "".join([exe_path, display_name])
id_int = binascii.crc32(str.encode(unique_id)) | 0x80000000
signed = ctypes.c_int(id_int)
# print(f"Signed ID: {signed.value}")
return signed.value
def get_unsigned_shortcut_id(signed_shortcut_id):
unsigned = ctypes.c_uint(signed_shortcut_id)
# print(f"Unsigned ID: {unsigned.value}")
return unsigned.value
# Initialize an empty dictionary to serve as the cache
api_cache = {}
#API KEYS FOR NONSTEAMLAUNCHER USE ONLY
BASE_URL = 'https://nonsteamlaunchers.onrender.com/api'
#GLOBAL VARS
created_shortcuts = []
new_shortcuts_added = False
shortcuts_updated = False
shortcut_id = None # Initialize shortcut_id
gridp64 = ""
grid64 = ""
logo64 = ""
hero64 = ""
def create_empty_shortcuts():
return {'shortcuts': {}}
def write_shortcuts_to_file(shortcuts_file, shortcuts):
with open(shortcuts_file, 'wb') as file:
file.write(vdf.binary_dumps(shortcuts))
os.chmod(shortcuts_file, 0o755)
# Define the path to the shortcuts file
shortcuts_file = f"{logged_in_home}/.steam/root/userdata/{steamid3}/config/shortcuts.vdf"
# Check if the file exists
if os.path.exists(shortcuts_file):
# If the file is not executable, write the shortcuts dictionary and make it executable
if not os.access(shortcuts_file, os.X_OK):
print("The file is not executable. Writing an empty shortcuts dictionary and making it executable.")
shortcuts = create_empty_shortcuts()
write_shortcuts_to_file(shortcuts_file, shortcuts)
else:
# Load the existing shortcuts
with open(shortcuts_file, 'rb') as file:
try:
shortcuts = vdf.binary_loads(file.read())
except vdf.VDFError as e:
print(f"Error reading file: {e}. The file might be corrupted or unreadable.")
print("Exiting the program. Please check the shortcuts.vdf file.")
sys.exit(1)
else:
print("The shortcuts.vdf file does not exist.")
sys.exit(1)
def get_sgdb_art(game_id, app_id):
global grid64
global gridp64
global logo64
global hero64
print(f"Downloading icons artwork...")
download_artwork(game_id, "icons", app_id)
print(f"Downloading logos artwork...")
logo64 = download_artwork(game_id, "logos", app_id)
print(f"Downloading heroes artwork...")
hero64 = download_artwork(game_id, "heroes", app_id)
print("Downloading grids artwork of size 600x900...")
gridp64 = download_artwork(game_id, "grids", app_id, "600x900")
print("Downloading grids artwork of size 920x430...")
grid64 = download_artwork(game_id, "grids", app_id, "920x430")
def download_artwork(game_id, art_type, shortcut_id, dimensions=None):
if game_id is None:
print("Invalid game ID. Skipping download.")
return
cache_key = (game_id, art_type, dimensions)
if dimensions is not None:
filename = get_file_name(art_type, shortcut_id, dimensions)
else:
filename = get_file_name(art_type, shortcut_id)
# Define the full path where artwork should be stored
file_path = f"{logged_in_home}/.steam/root/userdata/{steamid3}/config/grid/{filename}"
grid_folder_path = os.path.dirname(file_path) # Get the parent directory (grid folder)
# Ensure the grid folder exists
if not os.path.exists(grid_folder_path):
os.makedirs(grid_folder_path, exist_ok=True) # Create grid folder if it doesn't exist
print(f"Created grid folder at: {grid_folder_path}")
# Check if the file already exists
if file_exists_with_any_ext(file_path):
print(f"Artwork for {art_type} already exists. Skipping download.")
with open(file_path, 'rb') as image_file:
return b64encode(image_file.read()).decode('utf-8')
# If the artwork is not found locally, proceed with the download process
if cache_key in api_cache:
data = api_cache[cache_key]
else:
try:
print(f"Game ID: {game_id}")
url = f"{BASE_URL}/{art_type}/game/{game_id}"
if dimensions:
url += f"?dimensions={dimensions}"
print(f"Request URL: {url}")
with urllib.request.urlopen(url) as response:
if response.status != 200:
raise Exception(f"Failed to fetch data, status code {response.status}")
data = json.load(response)
api_cache[cache_key] = data
except (urllib.error.URLError, Exception) as e:
print(f"Error making API call: {e}")
api_cache[cache_key] = None
return
if not data or 'data' not in data:
print(f"No data available for {game_id}. Skipping download.")
return
# If no local file and no cache, start downloading artwork
for artwork in data['data']:
image_url = artwork['thumb']
print(f"Downloading image from: {image_url}")
# Try both .png and .ico formats
for ext in ['png', 'ico']:
try:
alt_file_path = file_path.replace('.png', f'.{ext}')
# Use urllib to download the image
req = urllib.request.Request(image_url)
req.add_header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64)")
req.add_header("Referer", "https://www.steamgriddb.com/")
with urllib.request.urlopen(req) as response:
if response.status == 200:
image_data = response.read()
# Save the image data to local file
with open(alt_file_path, 'wb') as file:
file.write(image_data)
print(f"Downloaded and saved {art_type} to: {alt_file_path}")
# Return base64 encoded image data
return b64encode(image_data).decode('utf-8')
except (urllib.error.URLError, Exception) as e:
print(f"Error downloading image in {ext}: {e}")
print(f"Artwork download failed for {game_id}. Neither PNG nor ICO was available.")
return None
def get_game_id(game_name):
print(f"Searching for game ID for: {game_name}")
try:
encoded_game_name = urllib.parse.quote(game_name)
url = f"{BASE_URL}/search/{encoded_game_name}"
print(f"Encoded game name: {encoded_game_name}")
print(f"Request URL: {url}")
# Open the URL and get the response
with urllib.request.urlopen(url) as response:
# Manually check if the status code is 200
if response.status == 200:
data = json.load(response)
if data.get('data'):
game_id = data['data'][0]['id']
print(f"Found game ID: {game_id}")
return game_id
else:
print(f"No game ID found for game name: {game_name}")
else:
print(f"Error: Unexpected status code {response.status}")
return None
except Exception as e:
print(f"Error searching for game ID: {e}")
return None
def get_file_name(art_type, shortcut_id, dimensions=None):
singular_art_type = art_type.rstrip('s')
if art_type == 'icons':
# Check for the existing .png file first
if os.path.exists(f"{logged_in_home}/.steam/root/userdata/{steamid3}/config/grid/{shortcut_id}-{singular_art_type}.png"):
return f"{shortcut_id}-{singular_art_type}.png"
# Fallback to .ico if .png doesn't exist
else:
return f"{shortcut_id}-{singular_art_type}.ico"
elif art_type == 'grids':
if dimensions == '600x900':
return f"{shortcut_id}p.png"
else:
return f"{shortcut_id}.png"
elif art_type == 'heroes':
return f"{shortcut_id}_hero.png"
elif art_type == 'logos':
return f"{shortcut_id}_logo.png"
else:
return f"{shortcut_id}.png"
def is_match(name1, name2):
if name1 and name2:
return name1.lower() in name2.lower() or name2.lower() in name1.lower()
else:
return False
steam_applist_cache = None
def get_steam_store_appid(steam_store_game_name):
search_url = f"{BASE_URL}/search/{steam_store_game_name}"
try:
with urllib.request.urlopen(search_url) as response:
data = json.load(response)
if 'data' in data and data['data']:
steam_store_appid = data['data'][0].get('steam_store_appid')
if steam_store_appid:
print(f"Found App ID for {steam_store_game_name} via primary source: {steam_store_appid}")
return steam_store_appid
except (urllib.error.URLError, Exception) as e:
print(f"Primary store App ID lookup failed for {steam_store_game_name}: {e}")
# Fallback using Steam AppList (cached)
global steam_applist_cache
if steam_applist_cache is None:
steam_applist_cache = {}
def normalize_name(name):
name = name.lower()
name = re.sub(r'[®™]', '', name)
name = ' '.join(name.split())
return name
if steam_store_game_name not in steam_applist_cache:
time.sleep(0.5) # Small delay to avoid spamming Steam
query = urllib.parse.quote(steam_store_game_name)
url = f"https://store.steampowered.com/api/storesearch/?term={query}&l=english&cc=US"
try:
with urllib.request.urlopen(url, timeout=10) as response:
data = json.load(response)
except (urllib.error.URLError, Exception) as e:
print(f"Fallback Steam lookup failed for {steam_store_game_name}: {e}")
return None
target = normalize_name(steam_store_game_name)
fallback_appid = None
for item in data.get("items", []):
if normalize_name(item.get("name", "")) == target:
fallback_appid = str(item.get("id"))
break
steam_applist_cache[steam_store_game_name] = fallback_appid
if steam_applist_cache[steam_store_game_name]:
print(f"Found App ID for {steam_store_game_name} via fallback Steam search API: {steam_applist_cache[steam_store_game_name]}")
return steam_applist_cache[steam_store_game_name]
print(f"No App ID found for {steam_store_game_name} in fallback Steam search API.")
return None
def create_steam_store_app_manifest_file(steam_store_appid, steam_store_game_name):
steamapps_dir = f"{logged_in_home}/.steam/root/steamapps/"
appmanifest_path = os.path.join(steamapps_dir, f"appmanifest_{steam_store_appid}.acf")
os.makedirs(steamapps_dir, exist_ok=True)
if os.path.exists(appmanifest_path):
print(f"Manifest file for {steam_store_appid} already exists.")
return
vdf_content = "\n".join([
'"AppState"',
"{",
f'\t"appid"\t\t"{steam_store_appid}"',
'\t"Universe"\t\t"1"',
f'\t"name"\t\t"{steam_store_game_name}"',
'\t"StateFlags"\t\t"0"',
f'\t"installdir"\t\t"{steam_store_game_name}"',
'\t"LastUpdated"\t\t""',
'\t"LastPlayed"\t\t""',
'\t"SizeOnDisk"\t\t""',
'\t"StagingSize"\t\t""',
'\t"buildid"\t\t""',
'\t"LastOwner"\t\t""',
'\t"DownloadType"\t\t""',
'\t"UpdateResult"\t\t""',
'\t"BytesToDownload"\t\t""',
'\t"BytesDownloaded"\t\t""',
'\t"BytesToStage"\t\t""',
'\t"BytesStaged"\t\t""',
'\t"TargetBuildID"\t\t""',
'\t"AutoUpdateBehavior"\t\t""',
'\t"AllowOtherDownloadsWhileRunning"\t\t""',
'\t"ScheduledAutoUpdate"\t\t""',
"",
'\t"InstalledDepots"',
"\t{",
"\t}",
"",
'\t"InstallScripts"',
"\t{",
"\t}",
"",
'\t"SharedDepots"',
"\t{",
"\t}",
"",
'\t"UserConfig"',
"\t{",
"\t}",
"",
'\t"MountedConfig"',
"\t{",
"\t}",
"}",
""
])
try:
with open(appmanifest_path, 'w', encoding='utf-8') as file:
file.write(vdf_content)
print(f"Created appmanifest file at: {appmanifest_path}")
except Exception as e:
print(f"Failed to write manifest for '{steam_store_game_name}': {e}")
def get_steam_fallback_url(steam_store_appid, art_type):
base_url = f"https://shared.steamstatic.com/store_item_assets/steam/apps/{steam_store_appid}/"
candidates = []
if art_type == "icons":
candidates = [base_url + "icon.png", base_url + "icon.ico"]
elif art_type == "logos":
candidates = [base_url + "logo_2x.png", base_url + "logo.png"]
elif art_type == "heroes":
candidates = [base_url + "library_hero_2x.jpg", base_url + "library_hero.jpg"]
elif art_type == "grids_600x900":
candidates = [base_url + "library_600x900_2x.jpg", base_url + "library_600x900.jpg"]
elif art_type == "grids_920x430":
candidates = [base_url + "header_2x.jpg", base_url + "header.jpg"]
else:
return None
for url in candidates:
try:
with urllib.request.urlopen(url) as response:
if response.status == 200:
return url
except (urllib.error.URLError, Exception) as e:
print(f"Error checking fallback URL: {url} — {e}")
continue
return None
def file_exists_with_any_ext(base_path):
for ext in ['png', 'jpg', 'ico']:
if os.path.exists(f"{base_path}.{ext}"):
return True
return False
def tag_artwork_files(shortcut_id, game_name, steamid3, logged_in_home):
grid_dir = f"{logged_in_home}/.steam/root/userdata/{steamid3}/config/grid"
base_name = str(shortcut_id)
patterns = [
f"{base_name}-icon",
f"{base_name}_logo",
f"{base_name}_hero",
f"{base_name}p",
f"{base_name}"
]
found_files = []
for pattern in patterns:
for ext in ['png', 'jpg', 'ico']:
file_path = os.path.join(grid_dir, f"{pattern}.{ext}")
if os.path.exists(file_path):
found_files.append(file_path)
for file_path in found_files:
try:
# Check if file already has the correct tag
result = subprocess.run(
['getfattr', '-n', 'user.xdg.tags', '--only-values', file_path],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True
)
existing_tags = result.stdout.strip().split(',') if result.returncode == 0 else []
if game_name in existing_tags:
print(f"Already tagged: {file_path}")
continue
subprocess.run(
['setfattr', '-n', 'user.xdg.tags', '-v', game_name, file_path],
check=True
)
print(f"Tagged {file_path} with '{game_name}'")
except subprocess.CalledProcessError as e:
print(f"Failed to tag {file_path}: {e}")
def delete_old_artwork_by_tag(appname, shortcut_id, steamid3, logged_in_home):
grid_path = os.path.join(logged_in_home, ".steam", "root", "userdata", str(steamid3), "config", "grid")
try:
for filename in os.listdir(grid_path):
filepath = os.path.join(grid_path, filename)
# Skip directories and .ico files
if os.path.isdir(filepath) or filename.endswith(".ico"):
continue
# Skip any files tagged for the current shortcut ID
if str(shortcut_id) in filename:
continue
try:
result = subprocess.run(
['getfattr', '-n', 'user.xdg.tags', '--only-values', filepath],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True
)
if result.returncode != 0:
continue # No tag present
tags = result.stdout.strip().split(',')
if appname in tags:
os.remove(filepath)
print(f"Deleted old artwork tagged '{appname}': {filepath}")
except Exception as e:
print(f"Failed to process {filepath}: {e}")
except FileNotFoundError:
print(f"Grid path not found: {grid_path}")
#for local check
def file_tagged_with_appname(filepath, appname):
try:
result = subprocess.run(
['getfattr', '-n', 'user.xdg.tags', '--only-values', filepath],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True
)
if result.returncode != 0:
return False
tags = result.stdout.strip().split(',')
return appname in tags
except Exception as e:
print(f"Failed to get tags for {filepath}: {e}")
return False
def scan_and_track_games(logged_in_home, steamid3):
def normalize_appname(name):
return name.strip().lower() if name else ""
shortcuts_path = f"{logged_in_home}/.steam/root/userdata/{steamid3}/config/shortcuts.vdf"
installed_apps_path = f"{logged_in_home}/.config/systemd/user/installedapps.json"
current_scan = {}
master_list = {}
previous_master_list = {}
def load_master_list():
nonlocal master_list, previous_master_list
if os.path.exists(installed_apps_path):
try:
with open(installed_apps_path, "r") as f:
master_list_raw = json.load(f)
if not isinstance(master_list_raw, dict):
raise ValueError("Expected dictionary.")
master_list = master_list_raw
previous_master_list = json.loads(json.dumps(master_list)) # deep copy
except Exception as e:
print(f"Failed to load master list: {e}")
master_list = {}
previous_master_list = {}
else:
master_list = {}
previous_master_list = {}
def track_game(appname, launcher):
now = datetime.utcnow().isoformat() + "Z"
if launcher not in current_scan:
current_scan[launcher] = {}
current_scan[launcher][appname] = {
"first_seen": master_list.get(launcher, {}).get(appname, {}).get("first_seen", now),
"last_seen": now,
"still_installed": True
}
def load_shortcuts_appid_map():
if not os.path.isfile(shortcuts_path):
print("shortcuts.vdf not found!")
return {}
try:
with open(shortcuts_path, "rb") as f:
data = vdf.binary_load(f)
shortcuts = data.get("shortcuts", data)
appid_map = {}
for key, entry in shortcuts.items():
appname = entry.get("AppName") or entry.get("appname")
appid = entry.get("appid") or entry.get("AppID")
if appname and appid:
norm_name = normalize_appname(appname)
appid_map[norm_name] = appid
return appid_map
except Exception as e:
print(f"Failed to load shortcuts.vdf: {e}")
return {}
def uninstall_removed_apps(removed_appnames, appid_map):
for appname in removed_appnames:
norm_name = normalize_appname(appname)
appid = appid_map.get(norm_name)
if appid:
try:
subprocess.run(["steam", f"steam://uninstall/{appid}"], check=True)
print(f"Uninstall command sent for '{appname}' (AppID: {appid})")
except subprocess.CalledProcessError:
print(f"Uninstall failed for '{appname}' (AppID: {appid})")
else:
print(f"AppID not found for '{appname}'")
def finalize_game_tracking():
now = datetime.utcnow().isoformat() + "Z"
removed_apps = {}
for launcher in list(master_list.keys()):
if launcher not in current_scan:
removed_apps[launcher] = list(master_list[launcher].keys())
del master_list[launcher]
else:
for appname in list(master_list[launcher].keys()):
if appname not in current_scan[launcher]:
was_installed = previous_master_list.get(launcher, {}).get(appname, {}).get("still_installed", True)
if was_installed:
removed_apps.setdefault(launcher, []).append(appname)
master_list[launcher][appname]["still_installed"] = False
master_list[launcher][appname]["last_seen"] = now
for launcher, games in current_scan.items():
if launcher not in master_list:
master_list[launcher] = {}
master_list[launcher].update(games)
# Remove volatile fields (like "last_seen") for comparison
def cleaned(data):
if isinstance(data, dict):
return {k: cleaned(v) for k, v in data.items() if k != "last_seen"}
elif isinstance(data, list):
return [cleaned(i) for i in data]
else:
return data
# Only write to file if the cleaned data has meaningful changes
if cleaned(master_list) != cleaned(previous_master_list):
os.makedirs(os.path.dirname(installed_apps_path), exist_ok=True)
with open(installed_apps_path, "w") as f:
json.dump(master_list, f, indent=4)
print("Master list updated and saved.")
else:
print("No meaningful changes to master list. Skipping write.")
if removed_apps:
print(f"Removed apps: {removed_apps}")
appid_map = load_shortcuts_appid_map()
for launcher, apps in removed_apps.items():
uninstall_removed_apps(apps, appid_map)
else:
print("No newly removed apps detected.")
return removed_apps
load_master_list()
return track_game, finalize_game_tracking
#.desktop file logic
def create_exec_line_from_entry(logged_in_home, new_entry, m_gameid):
try:
appname = new_entry.get('appname')
exe_path = new_entry.get('exe') # full quoted command
launch_options = new_entry.get('LaunchOptions')
launcher_name = new_entry.get('Launcher')
compattool = new_entry.get('CompatTool')
print(f"Launch Options: {launch_options}")
print(f"App Name: {appname}")
print(f"Exe Path: {exe_path}")
print(f"Launcher Name: {launcher_name}")
print(f"Compat Tool: {compattool}")
print(f"m_gameid: {m_gameid}")
# Extract GOG/Epic/Origin/Amazon game_id
game_id = None
m = re.search(r'/gameId=(\d+)', launch_options)
if m:
game_id = m.group(1)
print(f"Found GOG gameId: {game_id}")
# Optional DOSBox / extra GOG args (quoted block after /path)
extra_gog_args = None
m = re.search(r'/path="[^"]+"\s+"([^"]+)"', launch_options)
if m:
extra_gog_args = m.group(1)
print(f"desktopC: GOG Extra Args: {extra_gog_args}")
if not game_id:
m = re.search(r'com\.epicgames\.launcher://apps/([^/?&]+)', launch_options)
if m:
game_id = m.group(1)
print(f"Found Epic gameId: {game_id}")
if not game_id:
m = re.search(r'amazon-games://play/([a-zA-Z0-9\-\.]+)', launch_options)
if m:
game_id = m.group(1)
print(f"Found Amazon gameId: {game_id}")
if not game_id:
m = re.search(r'origin2://game/launch\?offerIds=([a-zA-Z0-9\-]+)', launch_options)
if m:
game_id = m.group(1)
print(f"Found Origin gameId: {game_id}")
# Ubisoft Connect
if not game_id:
m = re.search(r'uplay://launch/(\d+)', launch_options)
if m:
game_id = m.group(1)
print(f"desktopC: Found Ubisoft gameId: {game_id}")
if not game_id:
print("No gameId found, skipping game ID-related steps.")
else:
print(f"Final game_id: {game_id}")
# UMU GAMEID
m = re.search(r'GAMEID="(\d+)"', launch_options)
umugameid = m.group(1) if m else None
print(f"UMU GameID: {umugameid}")
# STEAM_COMPAT_DATA_PATH prefix
compat_match = re.search(r'STEAM_COMPAT_DATA_PATH="([^"]+)"', launch_options)
if not compat_match:
print("ERROR: no STEAM_COMPAT_DATA_PATH")
return None
compat_data_prefix = os.path.basename(compat_match.group(1).rstrip("/"))
print(f"Compat prefix: {compat_data_prefix}")
dir_path = os.path.expanduser("~/.steam/root/compatibilitytools.d")
pattern = re.compile(r"UMU-Proton-(\d+(?:\.\d+)*)(?:-(\d+(?:\.\d+)*))?")
try:
umu_folders = [
(tuple(map(int, (m.group(1) + '.' + (m.group(2) or '0')).split('.'))), name)
for name in os.listdir(dir_path)
if (m := pattern.match(name)) and os.path.isdir(os.path.join(dir_path, name))
]
if umu_folders:
compat_tool_name = max(umu_folders)[1] # Most recent version
print(f"Found UMU Proton: {compat_tool_name}")
else:
print("No valid UMU Proton compatibility tool folders found.")
compat_tool_name = None
except Exception as e:
print(f"Error reading UMU Proton folders: {e}")
compat_tool_name = None
if compat_tool_name:
proton_path = os.path.join(logged_in_home, f".local/share/Steam/compatibilitytools.d/{compat_tool_name}")
else:
proton_path = f"{logged_in_home}/.local/share/Steam/compatibilitytools.d/{compattool}"
print(f"Final Proton Path: {proton_path}")
desktop_dir = os.path.join(logged_in_home, "Desktop")
if not os.path.isdir(desktop_dir):
print("Desktop not found")
return None
for filename in os.listdir(desktop_dir):
if not filename.endswith(".desktop"):
continue
path = os.path.join(desktop_dir, filename)
try:
content = open(path).read()
except:
continue
if f"steam://rungameid/{m_gameid}" not in content:
continue
print(f"Found .desktop: {path}")
UMU = f"{logged_in_home}/bin/umu-run"
tokens = shlex.split(exe_path)
first = os.path.basename(tokens[0])
if first == "umu-run":
final_exe_path = exe_path
else:
# Prefix umu-run without quotes
final_exe_path = f'{UMU} {exe_path}'
# Remove quotes around umu-run only
final_exe_path = re.sub(r'^"(/.*?umu-run)"', r'\1', final_exe_path)
print(f"Final Exe Path: {final_exe_path}")
env_vars = (
f'STEAM_COMPAT_DATA_PATH="{logged_in_home}/.local/share/Steam/steamapps/compatdata/{compat_data_prefix}/" '
f'WINEPREFIX="{logged_in_home}/.local/share/Steam/steamapps/compatdata/{compat_data_prefix}/pfx"'
)
if umugameid:
env_vars += f' GAMEID={umugameid}'