-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.py
290 lines (240 loc) · 9.46 KB
/
update.py
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
import asyncio
import os
import threading
import zipfile
from json import loads as loadjson
from tkinter import filedialog as fd
import aiohttp
from tomllib import loads as loadtoml
import common
def get_files():
modnames = []
modfilenames = []
modversionsbase = []
modversionsminor = []
modframeworks = []
badmods = []
modids = []
modversionbase = ""
modversionminor = ""
modframework = ""
print("Select mod folder please!")
path = fd.askdirectory(initialdir=os.getcwd())
if not path:
print("No folder selected!")
os.system('pause')
os._exit(-1)
print(path, " <= path")
os.chdir(path)
if not os.listdir():
print("Empty directory!")
os.system('pause')
os._exit(-1)
for x in os.listdir():
filename, file_ext = os.path.splitext(x)
if file_ext != ".jar":
continue
print(x)
try:
try:
# Get json file
jarfile = zipfile.ZipFile(x, "r")
jsonfile = loadjson(jarfile.read("fabric.mod.json"))
# Set Values
modframeworks.append("fabric")
modfilenames.append(x)
modnames.append(jsonfile["name"])
modids.append(jsonfile["id"])
# Some mods don't have this for some reason
try:
modversionsbase.append(common.cleanversion(jsonfile["depends"]["minecraft"].rsplit('.', 1)[0]))
modversionsminor.append(jsonfile["depends"]["minecraft"].rsplit('.', 1)[1])
except:
continue
except:
# Get toml file and decode
jarfile = zipfile.ZipFile(x, "r")
tomlraw = jarfile.read("META-INF/mods.toml")
tomlraw = tomlraw.decode()
tomlfile = loadtoml(tomlraw)
# Set Values
modframeworks.append("forge")
modfilenames.append(x)
modnames.append(tomlfile["mods"][0]["modId"])
modids.append(tomlfile["mods"][0]["modId"])
try:
modv = list(filter(lambda test_list: test_list['modId'] == 'minecraft', tomlfile["dependencies"][tomlfile["mods"][0]["modId"]]))
modversionsbase.append(modv[0]["versionRange"].strip('[)').split(',')[0].rsplit('.',1)[0])
modversionsminor.append(modv[0]["versionRange"].strip('[)').split(',')[0].rsplit('.', 1)[1])
except:
continue
except:
badmods.append(x)
for i in modframeworks:
curr_frequency = modframeworks.count(i)
counter = 0
if (curr_frequency> counter):
counter = curr_frequency
modframework = i
for i in modversionsbase:
curr_frequency = modversionsbase.count(i)
counter = 0
if (curr_frequency> counter):
counter = curr_frequency
modversionbase = i
for i in modversionsminor:
curr_frequency = modversionsminor.count(i)
counter = 0
try:
int(i)
except:
continue
if (curr_frequency> counter):
counter = curr_frequency
modversionminor = i
modversion = modversionbase + "." + modversionminor
print("Guessed Minecraft Version:", modversion)
print("Guessed Minecraft Mod Loader:", modframework)
print(len(modnames), "Mods found.")
return modnames, modids, modfilenames, modversion, modframework, badmods
async def get_list():
""" Queries Modrinth for the mod's slugs """
x = 0
y = 0
array = []
not_found = []
badmods = []
result = []
searchlist, modids, modfilenames, mc_version, mc_framework, badmods = get_files()
async with aiohttp.ClientSession() as session:
tasks = []
for item in modids:
task = asyncio.ensure_future(common.query(item, mc_framework, mc_version, session, searchlist[modids.index(item)]))
tasks.append(task)
result = await asyncio.gather(*tasks)
for item in result:
if not item[0] and item[1] == None:
dict = {
"name": searchlist[modids.index(item[2])],
"id": item[2],
"reason": "No Mod Found"
}
print()
not_found.append(dict)
continue
elif not item[0] and item[1]:
dict = {
"name": searchlist[modids.index(item[2])],
"id": item[2],
"query": item[1],
"reason": "Bad Mod",
}
not_found.append(dict)
continue
dict = {
"name": item[3],
"slug": item[0],
"filename": modfilenames[len(array)+len(not_found)]
}
x += 1
print(f'{x}: {item[3]} => {item[0]}')
array.append(dict)
if not_found:
print("\n")
for item in not_found:
match item['reason']:
case "Bad Mod":
print("\033[91m"+ f"{item['name']} ({item['id']}) => Not found on Modrinth! (Wrong Mod Found, Found: {item['query']})" + "\033[0m")
case "No Mod Found":
print("\033[91m"+ f"{item['name']} ({item['id']}) => Not found on Modrinth! (No mod found.)" + "\033[0m")
if badmods:
print("\n")
for item in badmods:
print("\033[91m"+ f"{item} has hit this program's limitations. Needs to be updated manually." + "\033[0m")
if not_found or badmods:
mods = []
for item in not_found:
mods.append(item["name"])
mods += badmods
with open('mods-to-manually-update.txt', 'w') as f:
for line in mods:
f.write(line)
f.write('\n')
os.startfile('mods-to-manually-update.txt')
print("A text file labeled 'mods-to-manually-update.txt' has been created for your convenience. ;)")
inp = ""
if array:
while inp != "done":
print("Would you like to change any of the items?")
print("Enter the number you would like to change")
print("OR enter 'done' if you are okay with the list")
print("OR enter 'cancel' to cancel the download.")
inp = input()
if inp == "cancel":
print("Download cancelled!")
os._exit(1)
if inp.isdigit():
print("What would you like to do? (remove, change)")
ch = input()
try:
if ch == "remove":
array.pop(int(inp)-1)
searchlist.pop(int(inp)-1)
print("Item Removed.")
if ch == "change":
print(f'What would you like to change {array[int(inp)-1]["slug"]} to? ')
search = input()
async with aiohttp.ClientSession() as session:
tasks = []
task = asyncio.ensure_future(common.query(search, mc_framework, mc_version, session, search))
tasks.append(task)
result = await asyncio.gather(*tasks)
if not result[0][0]:
print("Error!")
if result[0][1]:
print(f'Closest mod found is {result[1]}')
else:
print("No mod found.")
continue
searchlist[int(inp)-1] = search
array[int(inp)-1] = {
"name": result[0][3],
"slug": result[0][0],
"filename": array[int(inp)-1]["filename"]
}
print(f'=> {result[0][0]}')
x = 0
for item in array:
print(f'{x+1}: {item["name"]} => {item["slug"]}')
x += 1
if not_found:
print("\n")
for item in not_found:
match item['reason']:
case "Bad Mod":
print("\033[91m"+ f"{item['name']} => Not found on Modrinth! (Wrong Mod Found, Found: {item['query']})" + "\033[0m")
case "No Mod Found":
print("\033[91m"+ f"{item['name']} => Not found on Modrinth! (No mod found.)" + "\033[0m")
continue
except Exception as e:
print(f'Error! {e}')
continue
else:
print("Empty mod list!")
os.system('pause')
os._exit(-1)
return array, mc_version, mc_framework
def main():
list, mc_version, mc_framework = asyncio.run(get_list())
print("Please wait!")
threads = []
for item in list:
x = threading.Thread(target=common.download, args=(item, mc_version, mc_framework, "update"))
x.start()
threads.append(x)
for item in threads:
item.join()
if os.path.exists("mods-that-broke.txt"):
os.startfile('mods-that-broke.txt')
if __name__ == "__main__":
main()