-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModioDirect.py
More file actions
1330 lines (1202 loc) · 51.7 KB
/
ModioDirect.py
File metadata and controls
1330 lines (1202 loc) · 51.7 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 os
import re
import sys
import time
import subprocess
import argparse
import shutil
import zipfile
import tempfile
import traceback
from urllib.parse import urlparse, unquote
try:
from tqdm import tqdm # type: ignore
except Exception:
tqdm = None
try:
import requests # type: ignore
except Exception:
requests = None
API_BASE = "https://api.mod.io/v1"
VERSION = "1.0.1"
CONFIG_NAME = "config.json"
USER_AGENT = "ModioDirect/1.1 (TheRootExec)"
DOWNLOAD_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "downloads")
CACHE_PATH = os.path.join(DOWNLOAD_DIR, "mod_cache.json")
DEBUG = False
GAMES_DB_PATHS = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "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,
)
def print_error(msg):
print(f"[Error] {msg}")
def print_info(msg):
print(f"[Info] {msg}")
def print_status(msg):
print(f"[Status] {msg}")
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 load_cache():
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):
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
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
download = file_obj.get("download")
if isinstance(download, dict):
size = download.get("filesize")
if isinstance(size, int):
return size
return None
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 "oauth" 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 or game not found."
if "429" in s or "rate" in s:
return "Rate limited. Try again later."
if "network" in s or "timeout" in s:
return "Network error occurred."
return "Unexpected error occurred."
def print_banner():
print(r" __ __ _ _ _____ _ _ ")
print(r"| \/ | ___ __| (_) ___ | __ \(_)_ __ ___ ___| |_ ")
print(r"| |\/| |/ _ \ / _` | |/ _ \| | | | | '__/ _ \/ __| __|")
print(r"| | | | (_) | (_| | | (_) | |__| | | | | __/ (__| |_ ")
print(r"|_| |_|\___/ \__,_|_|\___/|_____/|_|_| \___|\___|\__|")
print("\n ModioDirect Downloader Tool")
print(" by TheRootExec v1.0.1")
print("-------------------------------------------------------")
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 requirements now? (y/n): ").strip().lower()
if choice != "y":
return False
try:
cmd = [sys.executable, "-m", "pip", "install", "requests"]
subprocess.run(cmd, check=False)
except Exception as exc:
print_error(f"Failed to run pip: {exc}")
return False
try:
import requests as _requests # type: ignore
requests = _requests
return True
except Exception:
print_error("Requests is still not available after install attempt.")
return False
def safe_json(resp):
try:
return resp.json()
except Exception:
return None
def safe_request(method, url, **kwargs):
if requests is None:
print_error("The 'requests' library is not installed. Install it with: pip install requests")
return None
try:
return requests.request(method, url, **kwargs)
except Exception:
print_error("Network error occurred.")
return None
def load_config(config_path):
if not os.path.isfile(config_path):
return {}
try:
with open(config_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return data
except Exception:
pass
return {}
def save_config(config_path, data):
try:
with open(config_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 config: {exc}")
return False
def validate_api_key(api_key):
url = f"{API_BASE}/games"
params = {"api_key": api_key, "limit": 1}
headers = {"User-Agent": USER_AGENT}
resp = safe_request("GET", url, params=params, headers=headers, timeout=15)
if resp is None:
return False, "Network error or requests missing."
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):
config = {}
api_key = ""
if use_config:
config = load_config(config_path)
if isinstance(config, dict):
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 = ""
def normalize_path_input(value):
if not isinstance(value, str):
return ""
return value.strip().strip("\"").strip("'")
def prompt_mod_url():
while True:
raw = input("Enter mod URL (or file:PATH, q to exit, help): ").strip()
install_requested = False
force_requested = False
if " --install" in raw:
raw = raw.replace(" --install", "").strip()
install_requested = True
if " --force" in raw:
raw = raw.replace(" --force", "").strip()
force_requested = True
if raw.lower() in ("help", "?"):
print("Usage:")
print(" Paste a mod.io URL")
print(" Or type file:C:\\path\\to\\mods.txt for batch")
print(" Add --install to auto-install if a mod folder is detected")
print(" Type q to exit")
continue
if raw.lower() in ("q", "quit", "exit"):
return None, None, install_requested, force_requested
if raw.lower().startswith("file:"):
path = normalize_path_input(raw[5:])
if not path:
print_error("Batch file path is empty.")
continue
return "BATCH_FILE", path, install_requested, force_requested
# Allow direct path to batch file without file: prefix
if raw.lower().endswith(".txt"):
path = normalize_path_input(raw)
if os.path.isfile(path):
return "BATCH_FILE", path, install_requested, force_requested
if not raw:
print_error("URL cannot be empty.")
continue
match = URL_REGEX.search(raw)
if not match:
print_error("Invalid mod.io URL. Expected: https://mod.io/g/<game_slug>/m/<mod_slug>")
continue
game_slug = match.group(1).strip()
mod_slug = match.group(2).strip()
if not game_slug or not mod_slug:
print_error("Could not parse game_slug or mod_slug from URL.")
continue
return game_slug, mod_slug, install_requested, force_requested
def load_batch_urls(file_path):
try:
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
except Exception as exc:
print_error(f"Failed to read batch file: {exc}")
return []
urls = []
for line in lines:
if not isinstance(line, str):
continue
line = line.strip()
if not line or line.startswith("#"):
continue
urls.append(line)
return urls
def parse_modio_url(url):
if not isinstance(url, str):
return None, None
raw = url.strip().split()[0]
match = URL_REGEX.search(raw)
if not match:
return None, None
game_slug = match.group(1).strip()
mod_slug = match.group(2).strip()
if not game_slug or not mod_slug:
return None, None
return game_slug, mod_slug
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 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while resolving game."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while resolving game."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while resolving game."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
fallback_id, fallback_err = fallback_search_game_id(api_key, game_slug)
if fallback_id is not None:
return fallback_id, None
return None, fallback_err or "Game not found for provided game_slug."
game = items[0] if len(items) > 0 else None
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 in API response."
return game_id, None
def match_slug(item, slug):
if not isinstance(item, dict):
return False
name_id = item.get("name_id")
if isinstance(name_id, str) and name_id.lower() == slug.lower():
return True
alt_slug = item.get("slug")
if isinstance(alt_slug, str) and alt_slug.lower() == slug.lower():
return True
return False
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 == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while searching game."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while searching game."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while searching game."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
return None, "Game not found for provided game_slug."
for item in items:
if match_slug(item, game_slug):
game_id = item.get("id") if isinstance(item, dict) else None
if isinstance(game_id, int):
return game_id, None
return None, "Game not found for provided game_slug."
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 while resolving mod."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while resolving mod."
if resp.status_code == 404:
fallback_id, fallback_err = resolve_mod_id_global(api_key, game_id, mod_slug)
if fallback_id is not None:
return fallback_id, None
return None, fallback_err or "API returned 404 while resolving mod. The game or mod may be inaccessible with this API key."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while resolving mod."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while resolving mod."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
fallback_id, fallback_err = fallback_search_mod_id(api_key, game_id, mod_slug)
if fallback_id is not None:
return fallback_id, None
return None, fallback_err or "Mod not found for provided mod_slug."
mod = items[0] if len(items) > 0 else None
if not isinstance(mod, dict):
return None, "Unexpected mod data format."
mod_id = mod.get("id")
if not isinstance(mod_id, int):
return None, "Missing mod_id in API response."
return mod_id, 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 while resolving mod (global)."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while resolving mod (global)."
if resp.status_code == 404:
search_id, search_err = resolve_mod_id_global_search(api_key, game_id, mod_slug)
if search_id is not None:
return search_id, None
numeric_id, numeric_err = resolve_mod_id_numeric(api_key, game_id, mod_slug)
if numeric_id is not None:
return numeric_id, None
return None, search_err or numeric_err or "API error (404) while resolving mod (global)."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while resolving mod (global)."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while resolving mod (global)."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
return None, "Mod not found for provided mod_slug."
mod = items[0] if len(items) > 0 else None
if not isinstance(mod, dict):
return None, "Unexpected mod data format."
mod_id = mod.get("id")
if not isinstance(mod_id, int):
return None, "Missing mod_id in API response."
return mod_id, None
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 while searching mod (global)."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while searching mod (global)."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while searching mod (global)."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while searching mod (global)."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
return None, "Mod not found for provided mod_slug."
for item in items:
if not isinstance(item, dict):
continue
item_game_id = item.get("game_id")
if isinstance(item_game_id, int) and item_game_id != game_id:
continue
if match_slug(item, mod_slug):
mod_id = item.get("id")
if isinstance(mod_id, int):
return mod_id, None
return None, "Mod not found for provided mod_slug."
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 while resolving mod by numeric ID."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while resolving mod by numeric ID."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while resolving mod by numeric ID."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while resolving mod by numeric ID."
mid = data.get("id")
if not isinstance(mid, int):
return None, "Missing mod_id in API response."
return mid, None
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 while searching mod."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while searching mod."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while searching mod."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while searching mod."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
return None, "Mod not found for provided mod_slug."
for item in items:
if match_slug(item, mod_slug):
mod_id = item.get("id") if isinstance(item, dict) else None
if isinstance(mod_id, int):
return mod_id, None
return None, "Mod not found for provided mod_slug."
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 while fetching game details."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while fetching game details."
if resp.status_code == 404:
return None, "Game not accessible (404). The game may be private, unpublished, or require OAuth access."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while fetching game details."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while fetching game details."
return data, None
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 while fetching mod details."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while fetching mod details."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while fetching mod details."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while fetching mod details."
return data, None
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 while fetching mod files."
if resp.status_code == 401:
return None, "Invalid API key (401 Unauthorized)."
if resp.status_code == 429:
return None, "Rate limited (429) while fetching mod files."
if resp.status_code >= 400:
return None, f"API error ({resp.status_code}) while fetching mod files."
data = safe_json(resp)
if not isinstance(data, dict):
return None, "Empty or invalid API response while fetching mod files."
items = data.get("data")
if not isinstance(items, list) or len(items) == 0:
return None, "No mod files found."
return items, None
def select_latest_file(files):
if not isinstance(files, list) or len(files) == 0:
return None
latest = None
latest_date = -1
for f in files:
if not isinstance(f, dict):
continue
date_added = f.get("date_added")
if isinstance(date_added, int) and date_added > latest_date:
latest_date = date_added
latest = f
return latest
def extract_download_info(file_obj):
if not isinstance(file_obj, dict):
return None, None
download = file_obj.get("download")
if not isinstance(download, dict):
return None, None
binary_url = download.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)
path = parsed.path or ""
basename = os.path.basename(path)
filename = unquote(basename) if basename else "modfile.bin"
except Exception:
filename = "modfile.bin"
return binary_url, filename
def download_file(url, filename, expected_size=None, allow_existing=True):
headers = {"User-Agent": USER_AGENT}
for attempt in range(1, 3):
try:
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
if os.path.isabs(filename) or os.path.dirname(filename):
target = filename
else:
target = os.path.join(DOWNLOAD_DIR, filename)
if allow_existing and os.path.exists(target):
print_info(f"File already exists, skipping: {target}")
print_info("Using existing file.")
return True, True, target
if os.path.exists(target):
try:
os.remove(target)
except Exception:
pass
except Exception as exc:
print_error(f"Failed to prepare download path: {exc}")
return False, False, ""
print_status("Downloading...")
resp = safe_request("GET", url, headers=headers, stream=True, timeout=30)
if resp is None:
print_error("Network error occurred.")
if attempt == 2:
return False, False, ""
time.sleep(1)
continue
if resp.status_code == 429:
print_error("Rate limited. Try again later.")
if attempt == 2:
return False, False, ""
time.sleep(2)
continue
if resp.status_code >= 400:
print_error("Unexpected error occurred.")
if attempt == 2:
return False, False, ""
time.sleep(1)
continue
total = resp.headers.get("Content-Length")
try:
total_bytes = int(total) if total is not None else None
except Exception:
total_bytes = None
try:
with open(target, "wb") as f:
if tqdm is not None and total_bytes is not None:
with tqdm(total=total_bytes, unit="B", unit_scale=True, desc="Downloading") as bar:
for chunk in resp.iter_content(chunk_size=1024 * 256):
if not chunk:
continue
f.write(chunk)
bar.update(len(chunk))
else:
downloaded = 0
last_print = 0
for chunk in resp.iter_content(chunk_size=1024 * 256):
if not chunk:
continue
f.write(chunk)
downloaded += len(chunk)
if total_bytes:
pct = int((downloaded / total_bytes) * 100)
if pct >= last_print + 5 or pct == 100:
print(f"Downloading... {pct}%")
last_print = pct
if total_bytes is None:
print_info("Download complete (size unknown).")
if expected_size is not None:
try:
actual = os.path.getsize(target)
if actual != expected_size:
try:
os.remove(target)
except Exception:
pass
print_error("Downloaded file size mismatch. Retrying.")
if attempt == 2:
return False, False, ""
time.sleep(1)
continue
except Exception:
pass
print_status("Download complete.")
return True, False, target
except Exception:
print_error("Unexpected error occurred.")
if attempt == 2:
return False, False, ""
time.sleep(1)
return False, False, ""
def download_mod(url, filename=None, expected_size=None, allow_existing=True):
if not isinstance(url, str) or not url.strip():
print_error("Download URL is invalid.")
return None
if not filename:
try:
parsed = urlparse(url)
path = parsed.path or ""
base = os.path.basename(path)
filename = unquote(base) if base else None
except Exception:
filename = None
if not filename:
filename = "modfile.bin"
ok, skipped, final_path = download_file(url, filename, expected_size=expected_size, allow_existing=allow_existing)
if not ok:
return None, False
return final_path, skipped
def extract_mod(zip_path):
if not isinstance(zip_path, str) or not zip_path:
print_error("No downloaded file to extract.")
return None
if not os.path.exists(zip_path):
print_error("Downloaded file does not exist.")
return None
if not zipfile.is_zipfile(zip_path):
print_error("Downloaded file is not a ZIP. Extraction skipped.")
return None
try:
extract_path = tempfile.mkdtemp(prefix="modiodirect_extract_")
print_status("Extracting...")
with zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(extract_path)
print_status("Extraction complete.")
return extract_path
except Exception:
print_error("Unexpected error occurred.")
return None
def normalize_name(value):
if not isinstance(value, str):
return ""
return re.sub(r"[^a-z0-9]+", "", value.lower())
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 load_games_db():
for path in GAMES_DB_PATHS:
try:
if os.path.isfile(path):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return data
except Exception:
continue
return None
def get_verified_paths_from_db(game_name):
data = load_games_db()
if not isinstance(data, dict):
return []
games = data.get("game_mod_paths")
if not isinstance(games, list):
return []
key = normalize_name(game_name)
for item in games:
if not isinstance(item, dict):
continue
name = item.get("name")
if isinstance(name, str) and normalize_name(name) == key:
paths = []
mod_paths = item.get("mod_folder_paths")
if isinstance(mod_paths, dict):
for _k, v in mod_paths.items():
if isinstance(v, str):
paths.append(v)
return paths
return []
def get_modio_storage_roots():
roots = []
public_root = os.path.join(os.environ.get("PUBLIC", r"C:\Users\Public"), "mod.io")
if os.path.isdir(public_root):
roots.append(public_root)
local_app = os.environ.get("LOCALAPPDATA", "")
if local_app:
settings = os.path.join(local_app, "mod.io", "globalsettings.json")
try:
if os.path.isfile(settings):
with open(settings, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
root = data.get("RootLocalStoragePath")
if isinstance(root, str) and os.path.isdir(root):
roots.append(root)
except Exception:
pass
seen = set()
unique = []
for r in roots:
key = r.lower()
if key in seen:
continue
seen.add(key)
unique.append(r)
return unique
def detect_mod_folders(game_name, game_id):
if os.name != "nt":
return []
verified = get_verified_paths_from_db(game_name)
verified_candidates = []
for p in verified:
full = expand_path(p)
if full and os.path.isdir(full):
verified_candidates.append((f"{game_name} - Verified", full))
if verified_candidates:
return verified_candidates
roots = []
steam_root = r"C:\Program Files (x86)\Steam\steamapps\common"
epic_root = r"C:\Program Files\Epic Games"
if os.path.isdir(steam_root):
roots.append(steam_root)
if os.path.isdir(epic_root):
roots.append(epic_root)
candidates = []
mod_dir_names = {"mods", "mod", "paks"}
game_key = normalize_name(game_name)
for root in roots:
for base, dirs, _files in os.walk(root):
rel = os.path.relpath(base, root)
depth = rel.count(os.sep) if rel != "." else 0
if depth > 3:
dirs[:] = []
continue
lower_base = base.lower()
if lower_base.endswith(os.path.join("bepinex", "plugins")):
found_game = os.path.basename(os.path.dirname(os.path.dirname(base)))
if game_key and normalize_name(found_game) != game_key:
continue
label = f"{found_game} - BepInEx/plugins"
candidates.append((label, base))
for d in list(dirs):
if d.lower() in mod_dir_names:
full = os.path.join(base, d)
found_game = os.path.basename(base)
if game_key and normalize_name(found_game) != game_key:
continue
if os.path.isdir(full):
label = f"{found_game} - {d}"
candidates.append((label, full))
if isinstance(game_id, int):
gid = str(game_id)
for root in get_modio_storage_roots():
try:
for base, dirs, _files in os.walk(root):
rel = os.path.relpath(base, root)
depth = rel.count(os.sep) if rel != "." else 0
if depth > 2:
dirs[:] = []
continue
for d in list(dirs):
if d == gid:
path = os.path.join(base, d)
if os.path.isdir(path):
label = f"mod.io storage (game_id {gid})"
candidates.append((label, path))
except Exception:
continue
seen = set()
unique = []
for label, path in candidates:
key = path.lower()
if key in seen:
continue
seen.add(key)
unique.append((label, path))
return unique
def install_mod(zip_path, target_path, force=False):
if not zip_path or not os.path.isfile(zip_path):
print_error("Downloaded mod file is invalid.")
return False
if not target_path:
print_error("Target install path is invalid.")
return False
if not os.path.isdir(target_path):
print_error("Target install path is invalid.")
return False
extracted_path = ""
try:
base_name = os.path.splitext(os.path.basename(zip_path))[0]
existing_dir = os.path.join(target_path, base_name)
if os.path.isdir(existing_dir) and os.listdir(existing_dir) and not force:
print_info("Up to date — nothing to do.")
return True
extracted_path = extract_mod(zip_path)
if not extracted_path:
print_error("Install skipped (extraction failed).")
return False
print_status("Installing...")
for name in os.listdir(extracted_path):
src = os.path.join(extracted_path, name)
dst = os.path.join(target_path, name)
if os.path.isdir(src):
shutil.copytree(src, dst, dirs_exist_ok=True)
else:
shutil.copy2(src, dst)
print_status("Install complete.")
print_info(f"Mod installed successfully: {target_path}")
return True
except Exception:
print_error("Unexpected error occurred.")
return False
finally:
if extracted_path and os.path.isdir(extracted_path):
shutil.rmtree(extracted_path, ignore_errors=True)
def process_single_mod(api_key, game_slug, mod_slug, install_requested, force_requested, cache):
if not game_slug or not mod_slug:
print_error("Missing game or mod slug.")
return False, None, "", None, None, False, False
game_id, err = resolve_game_id(api_key, game_slug)
if err:
print_error(friendly_error(err))
return False, None, "", None, None, False, False