-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSLScheevo.py
More file actions
2590 lines (2342 loc) · 87.5 KB
/
SLScheevo.py
File metadata and controls
2590 lines (2342 loc) · 87.5 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 json
import vdf
import os
import re
import shutil
import sys
import time
import traceback
import platform
import itertools
import base64
import subprocess
import getpass
import hashlib
import argparse
import logging
from gevent import Timeout
from pathlib import Path
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from steam.client import SteamClient
from steam.core.msg import MsgProto
from steam.enums.common import EResult
from steam.enums.emsg import EMsg
from steam.webauth import WebAuth
# Exit codes
EXIT_SUCCESS = 0
EXIT_GENERAL_ERROR = 1
EXIT_LOGIN_FAILED = 2
EXIT_NO_ACCOUNT_ID = 3
EXIT_NO_APP_IDS = 4
EXIT_INPUT_REQUIRED = 5
EXIT_NO_SCHEMA_FOUND = 6
EXIT_FILE_ERROR = 7
EXIT_STEAM_NOT_FOUND = 8
EXIT_TOKEN_ERROR = 9
EXIT_NO_ACTIONS = 10
EXIT_NOT_SUPPORTED = 11
EXIT_FAILED_TO_GET_HWID = 12
EXIT_NO_ACCOUNT_SPECIFIED = 13
EXIT_FAILED_TO_PARSE_ID = 14
class ConsoleFormatter(logging.Formatter):
"""Formatter for console without timestamps"""
SYMBOLS = {
"SUCCESS": "[OK] ",
"INFO": "[->] ",
"WARNING": "[!!] ",
"ERROR": "[XX] ",
}
def format(self, record):
symbol = ""
if hasattr(record, "custom_level"):
symbol = self.SYMBOLS.get(record.custom_level, "")
elif record.levelname == "INFO":
symbol = "[→] "
return f"{symbol}{record.getMessage()}"
class Logger:
"""Logger class to handle all logging operations"""
def __init__(self, main_instance):
self.main = main_instance
def setup_logging(self):
"""Setup logging to both console and file"""
self.main.DATA_DIR.mkdir(exist_ok=True, parents=True)
# Create logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Clear any existing handlers
for handler in logger.handlers[:]:
logger.removeHandler(handler)
# File handler with timestamps
file_handler = logging.FileHandler(self.main.LOG_FILE, encoding="utf-8")
file_handler.setLevel(logging.INFO)
file_formatter = logging.Formatter(
"%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
)
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
# Console handler without timestamps and UTF-8 encoding
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
console_formatter = ConsoleFormatter()
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
def log_base(self, message):
"""Log message without any symbols"""
self._log_with_level("BASE", message, logging.INFO)
def log_info(self, message):
"""Log info message with [->] symbol"""
self._log_with_level("INFO", message, logging.INFO)
def log_success(self, message):
"""Log success message with [OK] symbol"""
self._log_with_level("SUCCESS", message, logging.INFO)
def log_error(self, message):
"""Log error message with [XX] symbol"""
self._log_with_level("ERROR", message, logging.ERROR)
def log_warning(self, message):
"""Log warning message with [!!] symbol"""
self._log_with_level("WARNING", message, logging.WARNING)
@staticmethod
def _log_with_level(custom_level, message, level):
logger = logging.getLogger()
if logger.isEnabledFor(level):
record = logging.LogRecord(
name=__name__,
level=level,
pathname=__file__,
lineno=0,
msg=message,
args=None,
exc_info=None,
)
record.custom_level = custom_level
logger.handle(record)
def install_global_exception_logger(self):
"""Catch all unhandled exceptions and log them before exiting."""
def handle_exception(exc_type, exc_value, exc_traceback):
logger = logging.getLogger()
if issubclass(exc_type, KeyboardInterrupt):
# Don't log Ctrl+C as an error
logger.info("Interrupted by user (KeyboardInterrupt).")
return
# Log full traceback to file
logger.error(
"UNHANDLED EXCEPTION OCCURRED!",
exc_info=(exc_type, exc_value, exc_traceback),
)
# Also log a clean message to the console
self.log_error(f"Unhandled crash: {exc_value}")
sys.excepthook = handle_exception
@staticmethod
def prompt(msg: str) -> str:
"""Log a prompt with [→] but keep input on same line."""
prefix = ConsoleFormatter.SYMBOLS.get("INFO", "[->] ")
# Print prefix and message WITHOUT newline
print(f"{prefix}{msg} ", end="", flush=True)
# Now take input
return input()
@staticmethod
def promptwarn(msg: str) -> str:
"""Log a prompt with [→] but keep input on same line."""
prefix = ConsoleFormatter.SYMBOLS.get("WARNING", "[!!] ")
# Print prefix and message WITHOUT newline
print(f"{prefix}{msg} ", end="", flush=True)
# Now take input
return input()
class SteamLogin:
"""Class to handle Steam login operations"""
def __init__(self, main_instance):
self.main = main_instance
self.logger = main_instance.logger
self.saved_logins = {}
self.login_input = None
self.target_username = None
self.target_account_id = None
self.target_steam_id64 = None
self.env_username = ""
self.env_password = ""
self.saved_username = None
self.saved_refresh_token = None
self.username = None
self.refresh_token = None
self.client = None
self.steam_id64 = None
self.account_id = None
def setup_login_credentials(self, login_input=None):
"""Setup all login credentials and target information"""
self.saved_logins = self.load_saved_logins()
self.login_input = login_input
# Parse target account info
self.target_username, self.target_account_id, self.target_steam_id64 = (
self.get_target_account_info(login_input)
)
# Get environment credentials
self.env_username = os.environ.get("STEAMUSERNAME", "")
self.env_password = os.environ.get("STEAMPASSWORD", "")
# Find saved login
self.saved_username, self.saved_refresh_token = self.find_saved_login()
# Determine final username
self.username = self.determine_username()
# Find refresh token
self.refresh_token = self.find_refresh_token()
def login(self, login_input=None):
"""Login to Steam using saved logins or interactive login"""
# Step 1: Setup all login credentials
self.setup_login_credentials(login_input)
# Step 2: Perform login cycle
result = self.attempt_login()
# Step 3: Handle login result
if result != EResult.OK:
self.logger.log_error("Steam login failed, exiting")
self.client.logout()
sys.exit(EXIT_LOGIN_FAILED)
# Extract account info
self.steam_id64 = self.client.steam_id.as_64
self.account_id = self.client.steam_id.account_id
# Step 4: Save successful login data
self.save_successful_login()
self.logger.log_success("Logged into Steam successfully")
return self.client, self.steam_id64, self.account_id
def get_username_silent_mode(self):
"""Handle silent mode when no username is available"""
last_account = self.load_last_account()
if last_account:
self.logger.log_info(f"Using last account: {last_account}")
# Just return the username, not the full login result
# The login() method will be called again with this username
return last_account
else:
self.logger.log_error(
"No username provided, please select a user with --login. Read more with --help"
)
sys.exit(EXIT_NO_ACCOUNT_SPECIFIED)
def determine_username(self):
"""Determine the final username through various methods"""
username = (
self.saved_username
or self.target_username
or self.target_steam_id64
or self.env_username
)
if not username:
username = self.get_username_from_user()
return username
def get_username_from_user(self):
"""Get username through interactive selection or input"""
# In silent mode, directly use the last saved account instead of interactive selection
if self.main.SILENT_MODE:
return self.get_username_silent_mode()
# Try interactive selection first (interactive mode only)
selected_username = self.select_account_interactively()
if selected_username:
return selected_username
# Fallback to manual input
self.logger.log_base("No Steam accounts found, please log in manually")
return input("Steam Username: ").strip()
def select_account_interactively(self):
"""Let user select an account from available options"""
available_accounts = self.get_available_accounts()
if not available_accounts:
return None
self.logger.log_info("Available accounts:")
for i, user in enumerate(available_accounts, 1):
self.logger.log_base(f"[{i}]: {user}")
try:
num = int(
self.logger.prompt("Choose an account to login (0 for new account):")
)
if 0 < num <= len(available_accounts):
return available_accounts[num - 1]
except ValueError:
pass
return None
def get_available_accounts(self):
"""Get list of available account names from various sources"""
accounts = []
# Accounts from loginusers.vdf (dict keyed by steamid)
vdf_accounts = self.parse_loginusers_vdf()
for user in vdf_accounts.values():
name = user.get("AccountName")
if name:
accounts.append(name)
# Accounts from saved logins
saved_logins = self.load_saved_logins()
for login_data in saved_logins.values():
name = login_data.get("username")
if name:
accounts.append(name)
# Remove duplicates while preserving order
seen = set()
unique_accounts = []
for name in accounts:
if name not in seen:
seen.add(name)
unique_accounts.append(name)
return unique_accounts
def attempt_login(self):
"""Perform the main login"""
result = None
prompt_disabled = False
login_timeout = 60
retry_count = 1
max_tries = 10
self.client = SteamClient()
while True:
try:
print("")
if retry_count == 1:
self.logger.log_info("Logging in...")
else:
self.logger.log_info(f"Login attempt {retry_count}...")
with Timeout(login_timeout):
if not self.refresh_token:
if not self.perform_web_authentication():
self.client.logout()
sys.exit(EXIT_LOGIN_FAILED)
if self.env_password or self.refresh_token:
result = self.client.login(
self.username, self.env_password, self.refresh_token
)
except Timeout:
self.logger.log_warning(
f"Login timed out after {login_timeout} seconds"
)
result = EResult.Timeout
except Exception as e:
self.logger.log_error(f"Login error: {e}")
result = None
extra_wait_time = 0
if result == EResult.OK:
break
elif result == EResult.InvalidPassword:
if self.refresh_token or self.main.SILENT_MODE:
self.logger.log_error(
"Looks like the token wasn't accepted or the password is wrong"
)
self.logger.log_error(
f"Try deleting '{self.main.SAVED_LOGINS_FILE}' and then try again."
)
sys.exit(EXIT_LOGIN_FAILED)
else:
self.logger.log_error(
"Invalid password. Please try again with the correct one"
)
self.client.logout()
self.client.disconnect()
continue
elif result == EResult.TryAnotherCM:
self.logger.log_error(
"The Steam Servers aren't letting us login (TryAnotherCM) - Waiting longer before contacting the servers again"
)
extra_wait_time = 20
elif result == EResult.Timeout:
self.logger.log_error("The login attempt timed out (Timeout)")
elif result == EResult.ServiceUnavailable:
self.logger.log_error(
"The Steam Servers aren't available right now (ServiceUnavailable)"
)
else:
self.logger.log_error(
f"An unrecognized error occurred when trying to login: {result}"
)
if (
self.main.SILENT_MODE
and not self.main.INFINITE_RETRY
and prompt_disabled
):
sys.exit(EXIT_LOGIN_FAILED)
if not self.main.SILENT_MODE and not prompt_disabled:
self.handle_service_unavailable()
prompt_disabled = True
# Ask if we should continue
if (
not self.main.INFINITE_RETRY
and not self.main.SILENT_MODE
and retry_count >= max_tries
):
self.handle_service_unavailable()
max_tries += 5
base_wait = min(5 * (2 ** (retry_count - 1)), 60)
jitter = base_wait * 0.1 # Add 10% random jitter
wait_time = base_wait + (time.time() % jitter) + extra_wait_time
self.logger.log_info(
f"Waiting {wait_time:.1f} seconds before retrying ({retry_count}/{'infinity' if self.main.INFINITE_RETRY else max_tries})"
)
self.client.logout()
self.client.disconnect()
time.sleep(wait_time * 0.3)
self.client = SteamClient()
time.sleep(wait_time * 0.7)
retry_count += 1
continue
return result
def handle_service_unavailable(self):
"""Handle Steam service unavailable scenario with y/n/i options"""
while True:
answer = self.logger.promptwarn(
"Keep retrying? (y=yes, n=no, i=infinite): "
).lower()
if answer == "i":
self.main.INFINITE_RETRY = True
self.logger.log_info("Retrying infinitely. Press CTRL+C to cancel")
return
elif answer == "y":
self.main.INFINITE_RETRY = False
self.logger.log_info("Retrying.")
return
else:
self.logger.log_info("No retry selected, exiting.")
sys.exit(EXIT_LOGIN_FAILED)
def perform_web_authentication(self):
"""Perform web-based authentication when no refresh token exists"""
if not self.env_password and self.main.SILENT_MODE:
return False
try:
webauth = WebAuth()
webauth.cli_login(self.username, self.env_password)
self.username = webauth.username
self.env_password = webauth.password
self.refresh_token = webauth.refresh_token
return True
except Exception as e:
self.logger.log_error(f"Web authentication failed: {e}")
return False
def save_successful_login(self):
"""Save login data after successful authentication"""
if self.refresh_token:
self.saved_logins[self.steam_id64] = {
"username": self.username,
"refresh_token": self.refresh_token,
"account_id": self.account_id,
"steam_id64": self.steam_id64,
}
if self.save_saved_logins(self.saved_logins):
self.logger.log_success(
f"Saved encrypted login token for {self.username}"
)
# Save last used account
account_identifier = self.login_input if self.login_input else self.username
self.save_last_account(account_identifier)
# Add our account to owner list
if self.steam_id64 not in self.main.TOP_OWNER_IDS:
self.main.TOP_OWNER_IDS.insert(0, self.steam_id64)
self.logger.log_info(
f"Added your account ({self.steam_id64}) to owner list"
)
def get_target_account_info(self, login_input):
"""Parse login input to determine target account"""
if not login_input:
return None, None, None
target_account_id, target_steam_id64 = self.parse_steam_id(login_input)
target_username = login_input if not target_account_id else None
return target_username, target_account_id, target_steam_id64
def find_saved_login(self):
"""Find matching login in saved logins database"""
if self.target_steam_id64 and self.target_steam_id64 in self.saved_logins:
login_data = self.saved_logins[self.target_steam_id64]
return login_data.get("username", ""), login_data.get("refresh_token")
elif self.target_username and self.target_username in self.saved_logins:
login_data = self.saved_logins[self.target_username]
return login_data.get("username", ""), login_data.get("refresh_token")
return "", None
def find_refresh_token(self):
"""Find refresh token for the current username"""
if self.saved_refresh_token:
return self.saved_refresh_token
# Search all saved logins for this username
for login_data in self.saved_logins.values():
if login_data.get("username") == self.username:
return login_data.get("refresh_token")
return None
def steamid64_from_account_id(self, account_id: int) -> int:
"""Convert AccountID (32-bit) to public SteamID64"""
return self.main.STEAMID64_BASE + account_id
def account_id_from_steamid64(self, steamid64: int) -> int:
"""Extract 32-bit AccountID from public Steam64"""
return steamid64 - self.main.STEAMID64_BASE
def parse_steam_id(self, identifier: str):
identifier = identifier.strip()
account_id = None
steam_id64 = None
# Steam2 ID: STEAM_X:Y:Z
if identifier.upper().startswith("STEAM_"):
try:
steam_prefix, y, z = identifier.split(":")
int(steam_prefix.split("_")[1])
y = int(y)
z = int(z)
account_id = (z << 1) | y
steam_id64 = self.steamid64_from_account_id(account_id)
except (ValueError, IndexError) as e:
self.logger.log_error(f"Failed to parse Steam2 ID ({identifier}): {e}")
sys.exit(EXIT_FAILED_TO_PARSE_ID)
# Steam3 ID: [U:1:ACCOUNT_ID]
elif identifier.startswith("[U:") and identifier.endswith("]"):
try:
parts = identifier[1:-1].split(":")
account_id = int(parts[-1])
steam_id64 = self.steamid64_from_account_id(account_id)
except (ValueError, IndexError) as e:
self.logger.log_error(f"Failed to parse Steam3 ID ({identifier}): {e}")
sys.exit(EXIT_FAILED_TO_PARSE_ID)
# Pure numeric input
elif identifier.isdigit():
num = int(identifier)
try:
if num >= 76561197960265728: # Steam64 (public)
account_id = self.account_id_from_steamid64(num)
steam_id64 = num
elif num <= 4294967295: # 32-bit AccountID
account_id = num
steam_id64 = self.steamid64_from_account_id(num)
else:
self.logger.log_error(f"Invalid numeric Steam ID range: {num}")
sys.exit(EXIT_FAILED_TO_PARSE_ID)
except ValueError as e:
self.logger.log_error(f"Failed to parse numeric ID ({identifier}): {e}")
sys.exit(EXIT_FAILED_TO_PARSE_ID)
return (
str(account_id) if account_id is not None else None,
str(steam_id64) if steam_id64 is not None else None,
)
def get_hwid(self):
"""Get Hardware ID that works on both Linux and Windows, with robust fallbacks."""
system = platform.system()
if system == "Windows":
wmic_path = Path(r"C:\Windows\System32\wbem\wmic.exe")
# Try WMIC if it exists
if wmic_path.exists():
try:
result = subprocess.check_output(
"wmic csproduct get UUID",
shell=True,
stderr=subprocess.DEVNULL,
text=True,
)
lines = [
line.strip() for line in result.split("\n") if line.strip()
]
if len(lines) > 1 and lines[1]:
return lines[1]
except subprocess.SubprocessError:
pass # fallback to PowerShell if WMIC fails
# Fallback: PowerShell
try:
result = subprocess.check_output(
'powershell -Command "Get-CimInstance Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID"',
shell=True,
stderr=subprocess.DEVNULL,
text=True,
).strip()
if result:
return result
except subprocess.SubprocessError:
pass
self.logger.log_error("Failed to retrieve HWID on Windows.")
sys.exit(EXIT_FAILED_TO_GET_HWID)
elif system == "Linux":
# Linux: Try machine-id first
try:
with open("/etc/machine-id", "r") as f:
machine_id = f.read().strip()
if machine_id:
return machine_id
except OSError:
pass
self.logger.log_error("Failed to retrieve machine ID on Linux.")
sys.exit(EXIT_FAILED_TO_GET_HWID)
else:
self.logger.log_error(f"Unsupported platform: {system}")
sys.exit(EXIT_NOT_SUPPORTED)
def derive_key(self):
"""Derive a Fernet key for encryption"""
system_user = getpass.getuser()
hwid = self.get_hwid()
combined_secret = f"{system_user}:{hwid}"
salt_prefix = b"steam_stats_salt_"
salt = hashlib.sha256(salt_prefix + hwid.encode("utf-8")).digest() # 32 bytes
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100_000,
)
key = base64.urlsafe_b64encode(kdf.derive(combined_secret.encode("utf-8")))
return key
def encrypt_saved_logins(self, logins_dict):
"""Encrypt saved logins"""
try:
key = self.derive_key()
fernet = Fernet(key)
# Convert dict to JSON string and encrypt
logins_json = json.dumps(logins_dict)
encrypted_data = fernet.encrypt(logins_json.encode())
return encrypted_data
except Exception as e:
self.logger.log_error(f"Error encrypting logins: {e}")
return None
def decrypt_saved_logins(self, encrypted_data):
"""Decrypt saved logins"""
try:
key = self.derive_key()
fernet = Fernet(key)
# Decrypt and parse JSON
decrypted_data = fernet.decrypt(encrypted_data)
logins_dict = json.loads(decrypted_data.decode())
return logins_dict
except Exception as e:
self.logger.log_error(f"Error decrypting logins: {e}")
return {}
def migrate_old_tokens_to_new_format(self):
"""Migrate old token files to new saved_logins format"""
old_files = [
self.main.DATA_DIR / "refresh_tokens.encrypted",
self.main.DATA_DIR / "refresh_tokens.json",
]
migrated = False
new_logins = {}
for old_file in old_files:
if old_file.exists():
try:
if old_file.suffix == ".encrypted":
# Try to decrypt old format
with open(old_file, "rb") as f:
encrypted_data = f.read()
# Use old derive_key function (same as before)
key = self.derive_key()
fernet = Fernet(key)
decrypted_data = fernet.decrypt(encrypted_data)
old_tokens = json.loads(decrypted_data.decode())
# Convert to new format
self._convert_tokens_to_new_format(old_tokens, new_logins)
elif old_file.suffix == ".json":
# Plaintext JSON
with open(old_file, "r") as f:
old_tokens = json.load(f)
# Convert to new format
self._convert_tokens_to_new_format(old_tokens, new_logins)
# Delete old file after migration
old_file.unlink()
migrated = True
self.logger.log_info(f"Migrated {old_file} to new format")
except (OSError, json.JSONDecodeError) as e:
self.logger.log_error(f"Error migrating {old_file}: {e}")
# Save migrated data
if migrated and new_logins:
if self.save_saved_logins(new_logins):
self.logger.log_success(
"Successfully migrated old tokens to saved_logins.encrypted"
)
else:
self.logger.log_error("Failed to save migrated tokens")
return migrated
def _convert_tokens_to_new_format(self, old_tokens, new_logins):
for username, refresh_token in old_tokens.items():
account_id, steam_id64 = self.parse_steam_id(username)
if account_id and steam_id64:
new_logins[steam_id64] = {
"username": username,
"refresh_token": refresh_token,
"account_id": account_id,
"steam_id64": steam_id64,
}
else:
# If we can't parse as ID, keep as username
new_logins[username] = {
"username": username,
"refresh_token": refresh_token,
"account_id": None,
"steam_id64": None,
}
def load_saved_logins(self):
"""Load saved logins, handling migration from old format if needed"""
# Check if migration is needed
old_files_exist = any(
[
(self.main.DATA_DIR / "refresh_tokens.encrypted").exists(),
(self.main.DATA_DIR / "refresh_tokens.json").exists(),
]
)
if old_files_exist:
self.migrate_old_tokens_to_new_format()
# Load from new encrypted file
if self.main.SAVED_LOGINS_FILE.exists():
try:
with open(self.main.SAVED_LOGINS_FILE, "rb") as f:
encrypted_data = f.read()
# Try to decrypt
logins = self.decrypt_saved_logins(encrypted_data)
if logins:
return logins
else:
self.logger.log_error(
"Failed to decrypt logins with current system"
)
self.logger.log_error(
"This might happen if you changed hardware or system user"
)
except OSError as e:
self.logger.log_error(f"Error loading encrypted logins: {e}")
return {}
def save_saved_logins(self, logins_dict):
"""Save logins in encrypted format"""
encrypted_data = self.encrypt_saved_logins(logins_dict)
if encrypted_data:
try:
with open(self.main.SAVED_LOGINS_FILE, "wb") as f:
f.write(encrypted_data)
return True
except OSError as e:
self.logger.log_error(f"Error saving encrypted logins: {e}")
sys.exit(EXIT_TOKEN_ERROR)
return False
def save_last_account(self, account_identifier):
"""Save the last used account identifier to a file"""
try:
with open(self.main.LAST_ACCOUNT_FILE, "w") as f:
f.write(account_identifier)
return True
except OSError as e:
self.logger.log_error(f"Error saving last account: {e}")
return False
def load_last_account(self):
"""Load the last used account identifier from file"""
try:
if self.main.LAST_ACCOUNT_FILE.exists():
with open(self.main.LAST_ACCOUNT_FILE, "r") as f:
return f.read().strip()
except OSError as e:
self.logger.log_error(f"Error loading last account: {e}")
return None
def get_account_id(self, client):
"""Get Steam Account ID directly from logged-in client"""
if client and hasattr(client, "steam_id") and client.steam_id:
account_id = client.steam_id.account_id
self.logger.log_success(
f"Using Account ID from logged-in client: {account_id}"
)
return str(account_id)
self.logger.log_error("No logged-in client available for Account ID")
return None
def get_steam_id64(self, client):
"""Get Steam Steam ID64 directly from logged-in client"""
if client and hasattr(client, "steam_id") and client.steam_id:
steam_id64 = client.steam_id.as_64
self.logger.log_success(
f"Using Steam ID64 from logged-in client: {steam_id64}"
)
return str(steam_id64)
self.logger.log_error("No logged-in client available for Steam ID64")
return None
def parse_loginusers_vdf(self):
if not self.main.LOGIN_FILE or not self.main.LOGIN_FILE.exists():
return {}
with self.main.LOGIN_FILE.open("r", encoding="utf-8", errors="ignore") as f:
data = vdf.load(f)
# data["users"] is keyed by SteamID
users = {
steamid: {
"AccountName": info.get("AccountName"),
"PersonaName": info.get("PersonaName"),
"MostRecent": info.get("MostRecent") == "1",
"Timestamp": int(info.get("Timestamp", 0)),
}
for steamid, info in data.get("users", {}).items()
}
return users
class SteamUtils:
"""Class to handle Steam utility operations"""
def __init__(self, main_instance):
self.main = main_instance
self.logger = main_instance.logger
self.steam_login = main_instance.steam_login
def determine_steam_directory(self):
if platform.system() == "Windows":
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam")
steam_path, _ = winreg.QueryValueEx(key, "SteamPath")
winreg.CloseKey(key)
self.logger.log_info(f"Found Steam installation at: {steam_path}")
self.main.STEAM_DIR = Path(os.path.normpath(steam_path))
except OSError:
self.logger.log_error("Failed to read Steam path from registry.")
sys.exit(EXIT_STEAM_NOT_FOUND)
else:
native_path = Path.home() / ".local/share/Steam"
symlink_path = Path.home() / ".steam/steam"
flatpak_path = Path.home() / ".var/app/com.valvesoftware.Steam/data/Steam"
if native_path.exists():
self.main.STEAM_DIR = native_path
self.logger.log_base(f"Using native Steam installation: {native_path}")
elif symlink_path.exists():
self.main.STEAM_DIR = symlink_path
self.logger.log_base(
f"Using symlink Steam installation: {symlink_path}"
)
elif flatpak_path.exists():
self.main.STEAM_DIR = flatpak_path
self.logger.log_base(
f"Using Flatpak Steam installation: {flatpak_path}"
)
else:
self.logger.log_error(
"No Steam installation found in ~/.local/share/Steam, ~/.steam/steam, ~/.var/app/com.valvesoftware.Steam/data/Steam"
)
sys.exit(EXIT_STEAM_NOT_FOUND)
if not self.main.STEAM_DIR.exists():
self.logger.log_error(
f"Steam directory does not exist at '{self.main.STEAM_DIR}'. Please report this issue"
)
sys.exit(EXIT_STEAM_NOT_FOUND)
# Set the dependent paths
self.main.LIBRARY_FILE = self.main.STEAM_DIR / "config/libraryfolders.vdf"
self.main.LOGIN_FILE = self.main.STEAM_DIR / "config/loginusers.vdf"
self.main.DEST_DIR = self.main.STEAM_DIR / "appcache/stats"
def parse_libraryfolders_vdf(self):
"""Parse libraryfolders.vdf to extract app IDs"""
if not self.main.LIBRARY_FILE or not self.main.LIBRARY_FILE.exists():
self.logger.log_error(
f"Steam library file not found at {self.main.LIBRARY_FILE}"
)
sys.exit(EXIT_STEAM_NOT_FOUND)
self.logger.log_info(f"Reading Steam library from: {self.main.LIBRARY_FILE}")
content = self.main.LIBRARY_FILE.read_text()
# Extract all app IDs using regex
app_ids = set(re.findall(r'"apps"\s*{([^}]+)}', content, re.DOTALL))
app_ids = set(re.findall(r'"(\d+)"\s*"', "".join(app_ids)))
return sorted([int(app_id) for app_id in app_ids if app_id.isdigit()])
@staticmethod
def read_tracking_file(file_path):
"""Read tracking file and return set of app IDs"""
if not file_path.exists():
return set()
return set(
int(line.strip())
for line in file_path.read_text().splitlines()
if line.strip().isdigit()
)
@staticmethod
def get_stats_schema(client, game_id, owner_id):
"""Request the stats schema for a game from a specific owner"""
msg = MsgProto(EMsg.ClientGetUserStats)
msg.body.game_id = game_id
msg.body.schema_local_version = -1
msg.body.crc_stats = 0
msg.body.steam_id_for_user = owner_id
client.send(msg)
return client.wait_msg(EMsg.ClientGetUserStatsResponse, timeout=5)
def check_single_owner(self, game_id, owner_id, client):
"""Return schema bytes or None"""
try:
out = self.get_stats_schema(client, game_id, owner_id)
if out and hasattr(out.body, "schema") and out.body.schema:
if len(out.body.schema) > 0:
return out.body.schema