-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModioDirect_v1.0.2.py
More file actions
3452 lines (2999 loc) · 124 KB
/
ModioDirect_v1.0.2.py
File metadata and controls
3452 lines (2999 loc) · 124 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
# ModioDirect — v1.0.2
# Original by TheRootExec | Extended with advanced mod management features
# Architecture: Single-file CLI, mod.io API v1. Mod Downloader
# New users
import subprocess
import sys
import os
import time
REQUIRED_PACKAGES = ['requests', 'rich', 'tqdm']
def restart_script():
print("\033[93m[●]\033[0m Press Enter and launch ModioDirect...", end=" ")
input()
os.system('cls' if os.name == 'nt' else 'clear')
os.execv(sys.executable, [sys.executable] + sys.argv)
def check_and_install_dependencies():
missing = []
for package in REQUIRED_PACKAGES:
try:
if package == 'requests':
__import__('requests')
elif package == 'rich':
__import__('rich')
elif package == 'tqdm':
__import__('tqdm')
except ImportError:
missing.append(package)
if not missing:
return True
os.system('cls' if os.name == 'nt' else 'clear')
print("\033[96m" + r" __ __ _ _ _____ _ _ ")
print("\033[96m" + r"| \/ | ___ __| (_) ___ | __ \(_)_ __ ___ ___| |_ ")
print("\033[96m" + r"| |\/| |/ _ \ / _` | |/ _ \| | | | | '__/ _ \/ __| __|")
print("\033[96m" + r"| | | | (_) | (_| | | (_) | |__| | | | | __/ (__| |_ ")
print("\033[96m" + r"|_| |_|\___/ \__,_|_|\___/|_____/|_|_| \___|\___|\__|")
print("\033[96m" + " " * 15 + "ModioDirect Downloader Tool" + " " * 16)
print("\033[96m" + " " * 18 + "by TheRootExec v1.0.2" + " " * 19)
print("\033[93m" + "=" * 57)
print("\033[93m[!]\033[0m ModioDirect requires the following packages:")
for pkg in missing:
print(" \033[93m•\033[0m " + pkg)
print("\033[93m[!]\033[0m Install missing dependencies? \033[92m[y]\033[0m or \033[91m[n]\033[0m :", end=" ")
choice = input().strip().lower()
if choice != 'y':
print("\033[91m[!] Setup cancelled. Exiting...\033[0m")
time.sleep(2)
return False
print("\033[93m[●]\033[0m Installing dependencies...")
success = True
for pkg in missing:
print(" \033[93m[✔]\033[0m " + pkg + "...", end=" ", flush=True)
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", pkg],
capture_output=True,
timeout=120
)
if result.returncode == 0:
print("\033[92mOK\033[0m")
else:
print("\033[91mFAILED\033[0m")
success = False
time.sleep(0.2)
except Exception:
print("\033[91mFAILED\033[0m")
success = False
if not success:
print("\033[91m[!] Some packages failed to install.\033[0m")
print(" Please install manually: pip install " + ' '.join(missing))
input(" Press Enter to exit...")
return False
print("\033[92m[✔] All dependencies installed!\033[0m")
print("\033[93m[●]\033[0m Installation complete!")
restart_script()
return True
if not check_and_install_dependencies():
sys.exit(1)
import json
import os
import re
import sys
import time
import subprocess
import argparse
import shutil
import zipfile
import tempfile
import traceback
import threading
import hashlib
from urllib.parse import urlparse, unquote
from datetime import datetime, timezone
# Optional dependency
try:
from tqdm import tqdm # type: ignore
except Exception:
tqdm = None
try:
import requests # type: ignore
except Exception:
requests = None
try:
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.align import Align
from rich.table import Table
import rich.box
from rich.progress import (
Progress,
BarColumn,
DownloadColumn,
TransferSpeedColumn,
TimeRemainingColumn,
TaskProgressColumn,
TextColumn,
)
_RICH_OK = True
except Exception:
Console = Panel = Text = Align = Table = Progress = None
BarColumn = DownloadColumn = TransferSpeedColumn = None
TimeRemainingColumn = TaskProgressColumn = TextColumn = None
rich = None
_RICH_OK = False
# Constants
API_BASE = "https://api.mod.io/v1"
VERSION = "1.0.2"
CONFIG_NAME = "config.json"
USER_AGENT = f"ModioDirect/{VERSION} (TheRootExec)"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOWNLOAD_DIR = os.path.join(BASE_DIR, "downloads")
BACKUP_DIR = os.path.join(BASE_DIR, "backups")
CACHE_PATH = os.path.join(DOWNLOAD_DIR, "mod_cache.json")
PROFILES_PATH = os.path.join(BASE_DIR, "profiles.json")
LOCKED_PATH = os.path.join(BASE_DIR, "locked_mods.json")
LOCAL_LIBRARY_PATH = os.path.join(BASE_DIR, "local_library.json")
DEBUG = False
GAMES_DB_PATHS = [
os.path.join(BASE_DIR, "games.json"),
os.path.join(DOWNLOAD_DIR, "games.json"),
os.path.join(os.path.expanduser("~"), "Downloads", "games.json"),
]
URL_REGEX = re.compile(
r"^https?://(?:www\.)?mod\.io/g/([^/]+)/m/([^/?#]+)",
re.IGNORECASE,
)
PC_KEYWORDS = ["windows", "pc", "win64", "win32", "x64", "x86", "desktop"]
CONSOLE_KEYWORDS = ["xbox", "ps4", "ps5", "playstation", "switch", "console", "nintendo"]
console = Console() if Console is not None else None
# datetime ('-')
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def _from_timestamp(ts) -> datetime:
try:
return datetime.fromtimestamp(float(ts), tz=timezone.utc)
except Exception:
return _utcnow()
def get_timestamp() -> str:
return _utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
def format_date(ts) -> str:
try:
return _from_timestamp(ts).strftime("%Y-%m-%d")
except Exception:
return "—"
def format_datetime(ts) -> str:
try:
return _from_timestamp(ts).strftime("%Y-%m-%d %H:%M")
except Exception:
return "—"
def ts_for_filename() -> str:
return _utcnow().strftime("%Y%m%d_%H%M%S")
# Version label
def friendly_version(version, filename=None, index=None, is_latest=False) -> str:
if version and str(version).strip() and str(version).strip().lower() != "none":
return str(version).strip()
if filename and str(filename).strip():
stem = os.path.splitext(str(filename).strip())[0]
# Trim common noise suffixes
stem = re.sub(r"[-_]+(v\d.*)?$", "", stem, flags=re.IGNORECASE).strip("-_ ")
if stem:
label = stem[:40]
return f"{label} {'(Latest)' if is_latest else '(Older Build)'}"
if index is not None:
return f"Build #{index} {'(Latest)' if is_latest else '(Older)'}"
return "(Latest)" if is_latest else "(Older Build)"
# welp
def print_error(msg):
if console:
console.print(f"[bold red][Error][/bold red] {msg}")
else:
print(f"[Error] {msg}", file=sys.stderr)
def print_info(msg):
if console:
console.print(f"[bold cyan][Info][/bold cyan] {msg}")
else:
print(f"[Info] {msg}")
def print_status(msg):
if console:
console.print(f"[bold blue][Status][/bold blue] {msg}")
else:
print(f"[Status] {msg}")
def print_warning(msg):
if console:
console.print(f"[bold yellow][Warning][/bold yellow] {msg}")
else:
print(f"[Warning] {msg}")
def print_success(msg):
if console:
console.print(f"[bold green][OK][/bold green] {msg}")
else:
print(f"[OK] {msg}")
def print_plain(msg):
if console:
console.print(msg)
else:
print(msg)
def print_section(title: str):
if console:
console.rule(f"[bold cyan]{title}[/bold cyan]")
else:
width = 56
pad = max(0, (width - len(title) - 2) // 2)
print(f"{'─' * width}")
print(f"{'─' * pad} {title} {'─' * pad}")
print(f"{'─' * width}")
def print_saved_panel(path):
print_info(f"Saved as: {path}")
def print_download_complete(_filename, _path):
return
# Banner
def print_banner():
if console:
console.print("[bold cyan] __ __ _ _ _____ _ _ [/bold cyan]")
console.print("[bold cyan]| \\/ | ___ __| (_) ___ | __ \\(_)_ __ ___ ___| |_ [/bold cyan]")
console.print("[bold cyan]| |\\/| |/ _ \\ / _` | |/ _ \\| | | | | '__/ _ \\/ __| __|[/bold cyan]")
console.print("[bold cyan]| | | | (_) | (_| | | (_) | |__| | | | | __/ (__| |_ [/bold cyan]")
console.print("[bold cyan]|_| |_|\\___/ \\__,_|_|\\___/|_____/|_|_| \\___|\\___|\\__|[/bold cyan]")
console.print("[bold white] ModioDirect Downloader Tool[/bold white]")
console.print(f"[dim cyan] by TheRootExec v{VERSION}[/dim cyan]")
console.print("[cyan]=======================================================[/cyan]")
else:
print(r" __ __ _ _ _____ _ _ ")
print(r"| \/ | ___ __| (_) ___ | __ \(_)_ __ ___ ___| |_ ")
print(r"| |\/| |/ _ \ / _` | |/ _ \| | | | | '__/ _ \/ __| __|")
print(r"| | | | (_) | (_| | | (_) | |__| | | | | __/ (__| |_ ")
print(r"|_| |_|\___/ \__,_|_|\___/|_____/|_|_| \___|\___|\__|")
print(" ModioDirect Downloader Tool")
print(f" by TheRootExec v{VERSION}")
print("========================================================")
# Utility
def animate_status(base, dots=3, delay=0.15):
try:
for i in range(dots):
sys.stdout.write(f"\r{base}{'.' * (i + 1)}")
sys.stdout.flush()
time.sleep(delay)
sys.stdout.write(f"\r{base} ")
sys.stdout.flush()
except Exception:
print_plain(base)
def cleanup_temp_file(path):
try:
if not path:
return
parent = os.path.dirname(path)
if os.path.isfile(path):
os.remove(path)
if os.path.isdir(parent) and os.path.basename(parent).startswith("modiodirect_"):
shutil.rmtree(parent, ignore_errors=True)
except Exception:
pass
def clear_screen():
try:
os.system("cls" if os.name == "nt" else "clear")
except Exception:
pass
def friendly_error(err):
if not isinstance(err, str):
return "Unexpected error occurred."
s = err.lower()
if "401" in s or "403" in s or "unauthorized" in s or "private" in s:
return "Mod is private, inaccessible, or requires authentication."
if "404" in s or "not found" in s:
return "Mod is private, inaccessible, or requires authentication."
if "429" in s or "rate" in s:
return "Rate limited. Please try again later."
if "network" in s or "timeout" in s:
return "Network error occurred."
return "Unexpected error occurred."
def normalize_name(value):
if not isinstance(value, str):
return ""
return re.sub(r"[^a-z0-9]+", "", value.lower())
def normalize_path_input(value):
if not isinstance(value, str):
return ""
return value.strip().strip('"').strip("'")
def expand_path(value):
if not isinstance(value, str):
return ""
cleaned = value.replace("/", "\\")
cleaned = cleaned.replace("{USERNAME}", os.environ.get("USERNAME", ""))
cleaned = cleaned.replace("[Manual]", "").strip()
cleaned = os.path.expandvars(cleaned)
cleaned = os.path.expanduser(cleaned)
return cleaned
def format_bytes(num_bytes) -> str:
try:
n = float(num_bytes)
except (TypeError, ValueError):
return "Unknown"
if n < 0:
return "Unknown"
for unit in ("B", "KB", "MB", "GB", "TB"):
if n < 1024:
return f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} PB"
def compute_file_hash(path, algorithm="md5") -> str | None:
try:
h = hashlib.new(algorithm)
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 256), b""):
h.update(chunk)
return h.hexdigest()
except Exception:
return None
def safe_json(resp):
try:
return resp.json()
except Exception:
return None
def safe_request(method, url, **kwargs):
if requests is None:
print_error("'requests' library not installed.")
return None
try:
return requests.request(method, url, **kwargs)
except Exception:
print_error("Network error occurred.")
return None
def get_expected_size(file_obj):
if not isinstance(file_obj, dict):
return None
size = file_obj.get("filesize")
if isinstance(size, int):
return size
dl = file_obj.get("download")
if isinstance(dl, dict):
size = dl.get("filesize")
if isinstance(size, int):
return size
return None
# Auto-install dependencies
def try_auto_install_rich():
global Console, Panel, Text, Align, Table, Progress, console, _RICH_OK
if _RICH_OK:
return True
print_error("The 'rich' library is required but not installed.")
choice = input("Install now? (y/n): ").strip().lower()
if choice != "y":
return False
try:
subprocess.run([sys.executable, "-m", "pip", "install", "rich"], check=False)
except Exception as exc:
print_error(f"pip failed: {exc}")
return False
try:
from rich.console import Console as _C
from rich.panel import Panel as _P
from rich.text import Text as _T
from rich.align import Align as _A
from rich.table import Table as _Tb
from rich.progress import (
Progress as _Pr,
BarColumn as _BC,
DownloadColumn as _DC,
TransferSpeedColumn as _TS,
TimeRemainingColumn as _TR,
TaskProgressColumn as _TP,
TextColumn as _TxC,
)
Console = _C; Panel = _P; Text = _T; Align = _A; Table = _Tb
Progress = _Pr
globals().update({
"BarColumn": _BC, "DownloadColumn": _DC,
"TransferSpeedColumn": _TS, "TimeRemainingColumn": _TR,
"TaskProgressColumn": _TP, "TextColumn": _TxC,
})
console = Console()
_RICH_OK = True
return True
except Exception:
print_error("Rich still unavailable after install attempt.")
return False
def try_auto_install_requests():
global requests
if requests is not None:
return True
print_error("The 'requests' library is required but not installed.")
choice = input("Install now? (y/n): ").strip().lower()
if choice != "y":
return False
try:
subprocess.run([sys.executable, "-m", "pip", "install", "requests"], check=False)
except Exception as exc:
print_error(f"pip failed: {exc}")
return False
try:
import requests as _r
requests = _r
return True
except Exception:
print_error("Requests still unavailable after install attempt.")
return False
# JSON persistence
def load_json_file(path, default=None):
if default is None:
default = {}
try:
if os.path.isfile(path):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, type(default)) else default
except Exception:
pass
return default
def save_json_file(path, data) -> bool:
try:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
return True
except Exception as exc:
print_error(f"Failed to save {os.path.basename(path)}: {exc}")
return False
def load_config(config_path) -> dict:
return load_json_file(config_path, default={})
def save_config(config_path, data) -> bool:
return save_json_file(config_path, data)
def load_cache() -> dict:
try:
if os.path.isfile(CACHE_PATH):
with open(CACHE_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return data
except Exception:
pass
return {"mods": {}}
def save_cache(cache) -> bool:
try:
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
with open(CACHE_PATH, "w", encoding="utf-8") as f:
json.dump(cache, f, indent=2)
return True
except Exception:
return False
# API key validation
def validate_api_key(api_key):
url = f"{API_BASE}/games"
params = {"api_key": api_key, "limit": 1}
headers = {"User-Agent": USER_AGENT}
if console:
with console.status("[cyan]Connecting to Mod.io...[/cyan]", spinner="dots"):
time.sleep(0.4)
else:
animate_status("Connecting", dots=3, delay=0.12)
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return False, "Network error."
if resp.status_code == 401:
return False, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return False, "Rate limited (429). Try again later."
if resp.status_code >= 400:
return False, f"API error ({resp.status_code})."
data = safe_json(resp)
if not isinstance(data, dict):
return False, "Empty or invalid API response."
return True, "API key validated."
def prompt_api_key(config_path, use_config) -> str:
config = {}
api_key = ""
if use_config:
config = load_config(config_path)
api_key = str(config.get("api_key", "")).strip()
while True:
if not api_key:
api_key = input("Enter your mod.io API key: ").strip()
if not api_key:
print_error("API key cannot be empty.")
continue
ok, msg = validate_api_key(api_key)
if ok:
print_info(msg)
if use_config:
config["api_key"] = api_key
save_config(config_path, config)
return api_key
print_error(msg)
api_key = ""
# fallback
def match_slug(item, slug) -> bool:
if not isinstance(item, dict):
return False
for key in ("name_id", "slug"):
val = item.get(key)
if isinstance(val, str) and val.lower() == slug.lower():
return True
return False
def resolve_game_id(api_key, game_slug):
url = f"{API_BASE}/games"
params = {"api_key": api_key, "name_id": game_slug, "limit": 1}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error while resolving game."
if resp.status_code == 401:
return None, "Invalid API key (401)."
if resp.status_code == 429:
return None, "Rate limited (429)."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Invalid API response."
items = data.get("data")
if not isinstance(items, list) or not items:
return fallback_search_game_id(api_key, game_slug)
game = items[0]
if not isinstance(game, dict):
return None, "Unexpected game data format."
game_id = game.get("id")
if not isinstance(game_id, int):
return None, "Missing game_id."
return game_id, None
def fallback_search_game_id(api_key, game_slug):
url = f"{API_BASE}/games"
params = {"api_key": api_key, "_q": game_slug, "limit": 100}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error while searching game."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
items = data.get("data") if isinstance(data, dict) else []
if not isinstance(items, list) or not items:
return None, "Game not found."
for item in items:
if match_slug(item, game_slug):
gid = item.get("id") if isinstance(item, dict) else None
if isinstance(gid, int):
return gid, None
return None, "Game not found."
def resolve_mod_id(api_key, game_id, mod_slug):
url = f"{API_BASE}/games/{game_id}/mods"
params = {"api_key": api_key, "name_id": mod_slug, "limit": 1}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code == 401:
return None, "Invalid API key (401)."
if resp.status_code == 429:
return None, "Rate limited (429)."
if resp.status_code == 404:
fid, ferr = resolve_mod_id_global(api_key, game_id, mod_slug)
return (fid, None) if fid else (None, ferr or "Mod not found (404).")
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
items = data.get("data") if isinstance(data, dict) else []
if not isinstance(items, list) or not items:
fid, ferr = fallback_search_mod_id(api_key, game_id, mod_slug)
return (fid, None) if fid else (None, ferr or "Mod not found.")
mod = items[0]
if not isinstance(mod, dict):
return None, "Unexpected mod data format."
mid = mod.get("id")
if not isinstance(mid, int):
return None, "Missing mod_id."
return mid, None
def resolve_mod_id_global(api_key, game_id, mod_slug):
url = f"{API_BASE}/mods"
params = {"api_key": api_key, "game_id": game_id, "name_id": mod_slug, "limit": 1}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code == 404:
fid, ferr = resolve_mod_id_global_search(api_key, game_id, mod_slug)
if fid:
return fid, None
nid, nerr = resolve_mod_id_numeric(api_key, game_id, mod_slug)
return (nid, None) if nid else (None, ferr or nerr or "Mod not found.")
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
items = data.get("data") if isinstance(data, dict) else []
if not isinstance(items, list) or not items:
return None, "Mod not found."
mod = items[0]
mid = mod.get("id") if isinstance(mod, dict) else None
return (mid, None) if isinstance(mid, int) else (None, "Missing mod_id.")
def resolve_mod_id_global_search(api_key, game_id, mod_slug):
url = f"{API_BASE}/mods"
params = {"api_key": api_key, "_q": mod_slug, "limit": 100}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
items = data.get("data") if isinstance(data, dict) else []
if not isinstance(items, list):
return None, "No results."
for item in items:
if not isinstance(item, dict):
continue
if isinstance(item.get("game_id"), int) and item["game_id"] != game_id:
continue
if match_slug(item, mod_slug):
mid = item.get("id")
if isinstance(mid, int):
return mid, None
return None, "Mod not found."
def resolve_mod_id_numeric(api_key, game_id, mod_slug):
if not isinstance(mod_slug, str) or not mod_slug.isdigit():
return None, None
mod_id = int(mod_slug)
url = f"{API_BASE}/games/{game_id}/mods/{mod_id}"
params = {"api_key": api_key}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
mid = data.get("id") if isinstance(data, dict) else None
return (mid, None) if isinstance(mid, int) else (None, "Missing mod_id.")
def fallback_search_mod_id(api_key, game_id, mod_slug):
url = f"{API_BASE}/games/{game_id}/mods"
params = {"api_key": api_key, "_q": mod_slug, "limit": 100}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
items = data.get("data") if isinstance(data, dict) else []
if not isinstance(items, list):
return None, "No results."
for item in items:
if match_slug(item, mod_slug):
mid = item.get("id") if isinstance(item, dict) else None
if isinstance(mid, int):
return mid, None
return None, "Mod not found."
def fetch_game_details(api_key, game_id):
url = f"{API_BASE}/games/{game_id}"
params = {"api_key": api_key}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code == 404:
return None, "Game not accessible (404)."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
return (data, None) if isinstance(data, dict) else (None, "Invalid response.")
def fetch_mod_details(api_key, game_id, mod_id):
url = f"{API_BASE}/games/{game_id}/mods/{mod_id}"
params = {"api_key": api_key}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return None, "Network error."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
return (data, None) if isinstance(data, dict) else (None, "Invalid response.")
def fetch_mod_files(api_key, game_id, mod_id):
url = f"{API_BASE}/games/{game_id}/mods/{mod_id}/files"
params = {"api_key": api_key, "limit": 100}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=20)
if resp is None:
return None, "Network error."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code})."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Invalid response."
items = data.get("data")
if not isinstance(items, list) or not items:
return None, "No mod files found."
return items, None
# File selection
def select_latest_file(files):
if not isinstance(files, list) or not files:
return None
latest, latest_date = None, -1
for f in files:
if not isinstance(f, dict):
continue
d = f.get("date_added")
if isinstance(d, int) and d > latest_date:
latest_date = d
latest = f
return latest
def score_file_for_platform(file_obj) -> int:
if not isinstance(file_obj, dict):
return 0
combined = " ".join([
str(file_obj.get("filename", "")),
str(file_obj.get("version", "")),
str(file_obj.get("changelog", "")),
]).lower()
score = 0
for kw in PC_KEYWORDS:
if kw in combined:
score += 10
for kw in CONSOLE_KEYWORDS:
if kw in combined:
score -= 20
return score
def select_best_file_for_platform(files):
if not isinstance(files, list) or not files:
return None
scored = [
(score_file_for_platform(f), f.get("date_added", 0), f)
for f in files if isinstance(f, dict)
]
if not scored:
return None
scored.sort(key=lambda x: (x[0], x[1]), reverse=True)
return scored[0][2]
def extract_download_info(file_obj):
if not isinstance(file_obj, dict):
return None, None
dl = file_obj.get("download")
if not isinstance(dl, dict):
return None, None
binary_url = dl.get("binary_url")
if not isinstance(binary_url, str) or not binary_url.strip():
return None, None
binary_url = binary_url.replace("\\/", "/")
filename = file_obj.get("filename")
if not isinstance(filename, str) or not filename.strip():
try:
parsed = urlparse(binary_url)
basename = os.path.basename(parsed.path or "")
filename = unquote(basename) if basename else "modfile.bin"
except Exception:
filename = "modfile.bin"
return binary_url, filename
# File and Build Selector
def prompt_file_selector(files):
if not isinstance(files, list) or not files:
print_error("No files available to select.")
return None
sorted_files = sorted(
[f for f in files if isinstance(f, dict)],
key=lambda x: x.get("date_added", 0),
reverse=True,
)
print_section("Build Selector")
if console and Table:
table = Table(
title="Available Builds",
box=rich.box.SIMPLE_HEAD, # type: ignore
show_lines=True,
)
table.add_column("#", style="bold cyan", width=4)
table.add_column("Filename", style="white", min_width=24)
table.add_column("Version", style="green", width=22)
table.add_column("Size", style="yellow", width=10)
table.add_column("Date", style="dim", width=12)
table.add_column("Platform", style="magenta", width=12)
for idx, f in enumerate(sorted_files, start=1):
fname = f.get("filename", "unknown")
ver = friendly_version(
f.get("version"), fname, idx, is_latest=(idx == 1)
)
size = format_bytes(get_expected_size(f) or 0)
date_s = format_date(f.get("date_added", 0))
sc = score_file_for_platform(f)
if sc >= 10:
platform = "[green]PC / Windows[/green]"
elif sc <= -10:
platform = "[red]Console[/red]"
else:
platform = "[yellow]Unknown[/yellow]"
table.add_row(str(idx), fname, ver, size, date_s, platform)
console.print(table)
else:
print(f"{'#':<4} {'Filename':<36} {'Version':<22} {'Size':<10} {'Date':<12}")
print("─" * 88)
for idx, f in enumerate(sorted_files, start=1):
fname = f.get("filename", "unknown")[:34]
ver = friendly_version(
f.get("version"), f.get("filename"), idx, is_latest=(idx == 1)
)[:20]
size = format_bytes(get_expected_size(f) or 0)
date_s = format_date(f.get("date_added", 0))
print(f"{idx:<4} {fname:<36} {ver:<22} {size:<10} {date_s:<12}")
auto_best = select_best_file_for_platform(sorted_files)
auto_idx = (sorted_files.index(auto_best) + 1
if auto_best in sorted_files else 1)
print_info(f"Auto-recommended: #{auto_idx} (best PC match)")
print_plain(" [0] Use recommended")
raw = input("Select build number (0 = recommended, q = cancel): ").strip()
if raw.lower() in ("q", "quit", "cancel"):
return None
if raw in ("0", ""):
return auto_best
try:
num = int(raw)
if 1 <= num <= len(sorted_files):
return sorted_files[num - 1]
except ValueError:
pass
print_warning("Invalid selection — using recommended build.")
return auto_best
# Mod Rollback sys
def prompt_version_rollback(files):
if not isinstance(files, list) or len(files) <= 1:
print_info("Only one version available — no rollback options.")
return None
sorted_files = sorted(
[f for f in files if isinstance(f, dict)],
key=lambda x: x.get("date_added", 0),
reverse=True,
)