-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursely
1439 lines (1119 loc) · 41.1 KB
/
cursely
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import json
import shutil
from time import sleep
from multiprocessing import Pool
from itertools import chain, repeat
import subprocess
import requests
from prettytable import PrettyTable, SINGLE_BORDER
from numerize.numerize import numerize
DOWNLOAD_RETRIES = 3
HOME = os.path.expanduser("~")
CONFIG_FOLDER = os.path.join(HOME, ".config", "cursely")
CONFIG_PATH = os.path.join(CONFIG_FOLDER, "config.json")
USAGE_INFO = f"""
Usage:
cursely [MOD_ID] Get a brief description of a mod and its download link.
cursely [KEYWORD] Search for a mod by its name or author.
cursely [MODPACK] Install all listed mods and their dependencies.
cursely --help Show this help message.
Your configuration (minecraft version, loader, mods path, etc.) is usually
stored in '{CONFIG_PATH}'. If you ever need to modify it,
simply delete the file and run cursely again or edit the file directly.
If you are running cursely for the first time, you do not need to manually
create a configuration file. It will ask you to provide the necessary
information and create the file for you.
"""
if sys.platform == "linux":
SHELL_PATH = "/bin/sh"
SHELL_ARGS = "-c"
DEF_MODS_PATH = os.path.join(HOME, ".minecraft", "mods")
elif sys.platform == "win32":
SHELL_PATH = "cmd"
SHELL_ARGS = "/c"
DEF_MODS_PATH = os.path.join(HOME, "AppData", "Roaming",
".minecraft", "mods")
def Mod(mod_id, cfg):
"""
Factory function for Mod objects.
Args:
mod_id (int or str): The ID of the mod or the URL to the mod.
cfg (dict): The config file as a dictionary object.
Returns:
Mod (CurseforgeMod or ModrinthMod): The mod object.
"""
try:
int(mod_id)
return CurseforgeMod(mod_id, cfg)
except (ValueError, TypeError):
return ModrinthMod(mod_id, cfg)
class CurseforgeMod:
"""
A class to represent a mod from curseforge.com.
"""
BASE_URL = "https://api.curseforge.com/v1"
def __init__(self, mod_id, cfg):
"""
Initialize a CurseforgeMod object.
Args:
mod_id (int): The ID of the mod.
cfg (dict): The target config for the mod.
{"API_KEY": Your curseforge API key as a string,
"minecraft_version": The target minecraft version,
"loader": The target loader. ('Fabric' or 'Forge')
...}
"""
if id is None or cfg is None:
raise ValueError("id and cfg must not be None.")
self.mod_id = mod_id
self.cfg = cfg
self._name = None
self._mod = None
self._downloads = None
self._last_updated = None
self._file = None
self._dependencies = None
self._website = None
self._summary = None
self._url = None
def __eq__(self, __value: object) -> bool:
"""
Check if two CurseforgeMod objects are equal.
Args:
__value (object): The object to compare to.
Returns:
bool: True if the objects are equal, False otherwise.
"""
if isinstance(__value, CurseforgeMod):
return self.mod_id == __value.mod_id
return False
def __repr__(self) -> str:
"""
String representation of a CurseforgeMod.
Returns:
str: The mod name if it is able to get it, else the mod id.
"""
try:
return str(self.name)
except ValueError:
return str(self.mod_id)
def __hash__(self) -> int:
"""
Get the hash of a CurseforgeMod object.
Returns:
int: The id of the mod.
"""
return hash(self.mod_id)
def _make_request(self, url_path, tries=DOWNLOAD_RETRIES):
"""
Make a request to the curseforge API.
Args:
url_path (str): The url path to the resource.
tries (int): The number of tries left.
Returns:
dict: The response as a json object.
Raises:
ValueError: If the request fails.
"""
while tries > 0:
end_point = f"{self.BASE_URL}{url_path}"
headers = {"Accept": "application/json",
"x-api-key": self.cfg["API_KEY"]}
try:
response = requests.get(end_point, headers=headers, timeout=1)
return response.json()["data"]
except requests.RequestException:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
except Exception:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
raise ValueError("Too many failed requests.")
@property
def name(self):
"""
Get the name of a mod.
Returns:
str: The name of the mod.
Raises:
ValueError: If the name lookup fails.
"""
if self._name is not None:
return self._name
self._name = self.mod["name"]
return self._name
@property
def mod(self):
"""
Get the mod object.
Returns:
dict: The mod as a json object.
Raises:
ValueError: If the connection fails.
"""
if self._mod is not None:
return self._mod
url_path = f"/mods/{self.mod_id}"
self._mod = self._make_request(url_path)
return self._mod
@property
def downloads(self):
"""
Get the number of downloads of a mod.
Returns:
int: The number of downloads.
Raises:
ValueError: If the connection fails.
"""
if self._downloads is not None:
return self._downloads
self._downloads = self.mod["downloadCount"]
return self._downloads
@property
def last_updated(self):
"""
Get the last update of a mod.
Returns:
str: The last update.
Raises:
ValueError: If the connection fails.
"""
if self._last_updated is not None:
return self._last_updated
date = self.mod["dateModified"][:10]
self._last_updated = date
return self._last_updated
@property
def file(self):
"""
Get the latest file of a mod that is compatible with the given config.
Returns:
dict: The file of the mod as a json object.
Raises:
ValueError: If the connection fails or if no compatible file
is found.
"""
def files(mod_id, index=0):
"""
Get a list of files for a mod. Paginated with page size 50.
Args:
index (int): The index of the first file to be returned.
returns:
A list of files.
Raises:
ValueError: If the request fails.
"""
url_path = f"/mods/{mod_id}/files?index={index}&pageSize=50"
response = self._make_request(url_path)
return response
if self._file is not None:
return self._file
compatible_config = {self.cfg["minecraft_version"],
self.cfg["loader"]}
max_results = 5000
page_size = 50
for i in range(0, max_results, page_size):
try:
response = files(self.mod_id, index=i)
if not response:
break
except ValueError:
break
for file in response:
if compatible_config <= set(file["gameVersions"]):
self._file = file
return self._file
raise ValueError("No compatible file found.")
@property
def dependencies(self):
"""
Get all dependencies of a mod.
Args:
mod_id (int): The mod ID.
cfg (dict): The config dictionary.
Returns:
A set of mod IDs.
Raises:
IndexError: If the file has no modId or relationType.
ValueError: If the mod has no dependencies.
"""
if self._dependencies is not None:
return self._dependencies
dependencies = {CurseforgeMod(dependency["modId"], self.cfg)
for dependency
in self.file["dependencies"]
if dependency["modId"] is not None
and dependency["relationType"] == 3}
self._dependencies = dependencies
return self._dependencies
@property
def website(self):
if self._website is not None:
return self._website
self._website = self.mod["links"]["websiteUrl"]
return self._website
@property
def summary(self):
if self._summary is not None:
return self._summary
self._summary = self.mod["summary"]
return self._summary.strip()
@property
def url(self):
"""
Get the download URL of a mod.
Returns:
str: The download URL of the mod.
Raises:
ValueError: If the download URL is unavailable or
the request fails.
"""
if self._url is not None:
return self._url
download_url = self.file["downloadUrl"]
if download_url:
download_url = download_url.replace(" ", "%20")
self._url = download_url
return self._url
raise ValueError("Unavailable through API")
class ModrinthMod:
"""
A class representing a mod from modrinth.com.
"""
BASE_URL = "https://api.modrinth.com/v2"
USER_AGENT = "Cursely/testing2 (github.com/julynx/cursely)"
def __init__(self, mod_id, cfg):
"""
Initialize a ModrinthMod object.
Args:
id (int): The ID of the mod.
cfg (dict): The target config for the mod.
{"API_KEY": Your curseforge API key as a string,
"minecraft_version": The target minecraft version,
"loader": The target loader. ('Fabric' or 'Forge')
...}
"""
if mod_id is None or cfg is None:
raise ValueError("id and cfg must not be None.")
self.mod_id = mod_id
self.cfg = cfg
self._name = None
self._mod = None
self._downloads = None
self._last_updated = None
self._latest_version = None
self._file = None
self._dependencies = None
self._website = None
self._summary = None
self._url = None
def __eq__(self, __value: object) -> bool:
"""
Check if two ModrinthMod objects are equal.
Args:
__value (object): The object to compare to.
Returns:
bool: True if the objects are equal, False otherwise.
"""
if isinstance(__value, ModrinthMod):
return self.mod_id == __value.mod_id
return False
def __repr__(self) -> str:
"""
String representation of a ModrinthMod.
Returns:
str: The mod name if it is able to get it, else the mod id.
"""
try:
return str(self.name)
except ValueError:
return str(self.mod_id)
def __hash__(self) -> int:
"""
Get the hash of a ModrinthMod object.
Returns:
int: The id of the mod.
"""
return hash(self.mod_id)
def _make_request(self, url_path, tries=DOWNLOAD_RETRIES):
"""
Make a request to the modrinth API.
Args:
url_path (str): The url path to the endpoint.
tries (int): The number of tries left.
Returns:
dict: The response as a json object.
Raises:
ValueError: If the request fails.
"""
while tries > 0:
end_point = f"{self.BASE_URL}{url_path}"
headers = {"Accept": "application/json",
"User-Agent": self.USER_AGENT}
try:
response = requests.get(end_point, headers=headers, timeout=1)
return response.json()
except requests.RequestException:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
except Exception:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
raise ValueError("Too many failed requests.")
@property
def name(self):
"""
Get the name of a mod.
Returns:
str: The name of the mod.
Raises:
ValueError: If the name lookup fails.
"""
if self._name is not None:
return self._name
self._name = self.mod["title"]
return self._name
@property
def mod(self):
"""
Get the mod object.
Returns:
dict: The mod as a json object.
Raises:
ValueError: If the connection fails.
"""
if self._mod is not None:
return self._mod
url_path = f"/project/{self.mod_id}"
self._mod = self._make_request(url_path)
return self._mod
@property
def downloads(self):
"""
Get the number of downloads of a mod.
Returns:
int: The number of downloads.
Raises:
ValueError: If the connection fails.
"""
if self._downloads is not None:
return self._downloads
self._downloads = self.mod["downloads"]
return self._downloads
@property
def last_updated(self):
"""
Get the last updated date of a mod.
Returns:
str: The last updated date.
Raises:
ValueError: If the connection fails.
"""
if self._last_updated is not None:
return self._last_updated
date = self.mod["updated"][:10]
self._last_updated = date
return self._last_updated
@property
def latest_version(self):
"""
Get the latest version of a mod compatible with the target config.
Returns:
dict: The latest version as a json object.
Raises:
ValueError: If no compatible version is found.
"""
if self._latest_version is not None:
return self._latest_version
minecraft_version = self.cfg["minecraft_version"]
mod_loader = self.cfg["loader"].lower()
url_path = f"/project/{self.mod_id}/version"
versions = self._make_request(url_path)
try:
version = next(version
for version
in versions
if minecraft_version in version["game_versions"]
and mod_loader in version["loaders"])
except StopIteration:
raise ValueError("No compatible version found.")
self._latest_version = version
return self._latest_version
@property
def file(self):
"""
Get the latest file of a mod compatible with the target config.
Returns:
dict: The latest file as a json object.
Raises:
ValueError: If no compatible file is found.
"""
if self._file is not None:
return self._file
try:
version_file = next(file
for file
in self.latest_version["files"]
if file["primary"])
except StopIteration:
raise ValueError("No compatible file found.")
self._file = version_file
return self._file
@property
def dependencies(self):
"""
Get the dependencies of a mod.
Returns:
set: The dependencies as a set of ModrinthMod objects.
"""
if self._dependencies is not None:
return self._dependencies
self._dependencies = {ModrinthMod(dependency["project_id"], self.cfg)
for dependency
in self.latest_version["dependencies"]
if dependency["project_id"] is not None
and dependency["dependency_type"] == "required"}
return self._dependencies
@property
def website(self):
if self._website is not None:
return self._website
self._website = f"https://modrinth.com/mod/{self.mod['slug']}"
return self._website
@property
def summary(self):
if self._summary is not None:
return self._summary
self._summary = self.mod["description"]
return self._summary.strip()
@property
def url(self):
"""
Get the download url of a mod.
Returns:
str: The download url.
Raises:
ValueError: If the download url lookup fails.
"""
if self._url is not None:
return self._url
download_url = self.file["url"]
if not download_url:
raise ValueError("Unavailable through API")
self._url = download_url
return self._url
class CurseforgeSearch():
BASE_URL = "https://api.curseforge.com/v1"
def __init__(self, keyword, cfg) -> None:
self.keyword = keyword
self.cfg = cfg
self.results = []
self._search()
def __iter__(self):
return self
def __next__(self):
return next(self.results)
def _make_request(self, url_path, params=None, tries=DOWNLOAD_RETRIES):
"""
Make a request to the curseforge API.
Args:
url_path (str): The url path to the resource.
tries (int): The number of tries left.
Returns:
dict: The response as a json object.
Raises:
ValueError: If the request fails.
"""
while tries > 0:
end_point = f"{self.BASE_URL}{url_path}"
headers = {"Accept": "application/json",
"x-api-key": self.cfg["API_KEY"]}
try:
response = requests.get(end_point,
params=params,
headers=headers,
timeout=1)
return response.json()["data"]
except requests.RequestException:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
except Exception:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
raise ValueError("Too many failed requests.")
def _search(self):
if self.results != []:
return self.results
url_path = "/mods/search"
params = {'gameId': 432,
'searchFilter': self.keyword,
'gameVersion': self.cfg['minecraft_version'],
'modLoaderType': self.cfg['loader']}
try:
request = self._make_request(url_path, params=params)
except ValueError:
request = []
mods = []
for mod_info in request:
mod = ModrinthMod(mod_info["id"], self.cfg)
mod._name = mod_info["name"]
mod._downloads = mod_info["downloadCount"]
mod._last_updated = mod_info["dateModified"][:10]
mods.append(mod)
self.results = iter(mods)
return self.results
class ModrinthSearch():
BASE_URL = "https://api.modrinth.com/v2"
def __init__(self, keyword, cfg) -> None:
self.keyword = keyword
self.cfg = cfg
self.results = []
self._search()
def __iter__(self):
return self
def __next__(self):
return next(self.results)
def _make_request(self, url_path, params=None, tries=DOWNLOAD_RETRIES):
"""
Make a request to the curseforge API.
Args:
url_path (str): The url path to the resource.
tries (int): The number of tries left.
Returns:
dict: The response as a json object.
Raises:
ValueError: If the request fails.
"""
while tries > 0:
end_point = f"{self.BASE_URL}{url_path}"
headers = {"Accept": "application/json",
"x-api-key": self.cfg["API_KEY"]}
try:
response = requests.get(end_point,
params=params,
headers=headers,
timeout=1)
return response.json()["hits"]
except requests.RequestException:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
except Exception:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
raise ValueError("Too many failed requests.")
def _search(self):
if self.results != []:
return self.results
facets = [[f"versions:{self.cfg['minecraft_version']}"],
[f"categories:{self.cfg['loader'].lower()}"]]
facets = repr(facets).replace(" ", "").replace("'", "\"")
url_path = f"/search?query={self.keyword}&facets={facets}"
try:
request = self._make_request(url_path)
except ValueError:
request = []
mods = []
for mod_info in request:
mod = ModrinthMod(mod_info["project_id"], self.cfg)
mod._name = mod_info["title"]
mod._downloads = mod_info["downloads"]
mod._last_updated = mod_info["date_modified"][:10]
mods.append(mod)
self.results = iter(mods)
return self.results
class ModTable:
def __init__(self, mods):
if not isinstance(mods, list):
mods = [mods]
self.mods = mods
self._names_column_width = None
try:
self._term_width = os.get_terminal_size().columns
except OSError:
self._term_width = 80
self._table = PrettyTable(align="l")
if sys.platform == "win32":
self._term_width -= 1
self._table.set_style(SINGLE_BORDER)
def __repr__(self):
error_window = PrettyTable(align="c")
error_window.header = False
error_window.set_style(SINGLE_BORDER)
if len(self.mods) <= 0:
text = "No mods found.".center(self._term_width - 4)
error_window.add_row([text])
string = str(error_window)
elif len(self.mods) == 1:
string = str(self.details_view)
else:
string = str(self.list_view)
if self._table_too_wide():
text = "Window too small!".center(self._term_width - 4)
error_window.clear_rows()
error_window.add_row([text])
string = str(error_window)
return string
def _fix_length(self, text, *, length=32):
"""
Fix the length of a string.
Args:
text (str): The string to fix.
length (int): The length to fix the string to.
Returns:
The fixed string.
Raises:
IndexError: If the length is less than 3.
"""
# Remove all emojis from the text
text = str(text).encode('ascii', 'ignore').decode('ascii').strip()
output = text[:length - 3] + "..." if len(text) > length else text
return output.ljust(length)
def _table_too_wide(self):
if self._term_width < 45:
return True
max_line_length = max(len(line)
for line
in str(self._table).split("\n"))
return max_line_length > self._term_width
@property
def names_column_width(self):
if self._names_column_width is not None:
return self._names_column_width
self._names_column_width = self._term_width - 40
return self._names_column_width
@property
def list_view(self):
self._table.field_names = ["Id", "Name", "Downloads", "Updated"]
for mod in sorted(self.mods, key=lambda x: x.downloads, reverse=True):
mod_id = mod.mod_id
name = mod.name
downloads = numerize(mod.downloads)
last_updated = mod.last_updated[:10]
row = [self._fix_length(mod_id, length=8),
self._fix_length(name, length=self.names_column_width),
self._fix_length(downloads, length=9),
self._fix_length(last_updated, length=10)]
self._table.add_row(row)
return self._table
@property
def details_view(self):
# Mod fields
mod = self.mods[0]
mod_id = self._fix_length(mod.mod_id, length=8)
name = self._fix_length(mod.name, length=self.names_column_width)
downloads = self._fix_length(numerize(mod.downloads), length=9)
last_updated = self._fix_length(mod.last_updated, length=10)
# Title row
title = f"{mod_id} | {name} | {downloads} | {last_updated}"
self._table.field_names = [title]
# Mod details
website = mod.website
summary = self._fix_length(mod.summary, length=self._term_width - 4)
try:
download_link = mod.url
except ValueError:
download_link = "Not available."
# Add dependencies
self._table.add_rows([[website], [summary], [""],
["Download:"], [download_link]])
try:
mod_dependencies = mod.dependencies
except ValueError:
mod_dependencies = []
if len(mod_dependencies) != 0:
self._table.add_rows([[""], ["Required dependencies:"]])
for dependency in mod_dependencies:
mod_id = self._fix_length(dependency.mod_id, length=8)
try:
url = dependency.url
except ValueError:
url = "Not available."
self._table.add_row([f"{mod_id} | {url}"])
return self._table
def mod_download_wrapper(mod_or_url, cfg):
"""
Wrapper for the mod_download function.
Args:
mod_or_url (Mod or str): The mod to download or a URL.
cfg (dict): The config file as a dictionary object.
Needed for the destination path.
tries (int): The number of retries if the download fails.
Returns:
int: The ID of the mod if the download suceeded, -1 otherwise.
If the parameter is a string, the ID returned in case of
success is 0.
"""
def download_from_url(url, cfg, tries=DOWNLOAD_RETRIES):
"""
Download a file from a URL.
Args:
url (str): The URL of the file.
cfg (dict): The config file as a dictionary object.
Needed for the destination path.
Returns:
bool: True if the download was successful, raises otherwise.
Raises:
ValueError: If the download fails. Tries DOWNLOAD_RETRIES times.
"""
while tries > 0:
try:
with requests.get(url, stream=True, timeout=1) as response:
if response.status_code != 200:
sleep((DOWNLOAD_RETRIES + 1 - tries) / 2)
tries -= 1
continue
mod_file = os.path.join(cfg["mods_path"],
url.split("/")[-1])
with open(mod_file, "wb") as file:
shutil.copyfileobj(response.raw, file)