This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manifest_composer.py
254 lines (190 loc) · 8.15 KB
/
manifest_composer.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
from requests import get
from os import mkdir, listdir, remove, system
from shutil import rmtree
from tqdm import tqdm
from json import load, loads, dump, dumps
from pathlib import Path
from hashlib import sha1
import re
from traceback import print_exc
def get_command_output(command):
print(f"Running command: {command}")
system(command + " > out 2>&1")
with open("out", "r") as f:
output = f.read()
remove("out")
return output
def find_cid(text):
# Find CIDv1
try:
cid = re.findall(r"baf[a-zA-Z0-9]{56}", text)
return cid[0]
except Exception as e:
print(text)
raise e
def main(url, version_id):
MANIFEST_URL = url
ASSET_PATH = Path("assets")
with open("cid_db.json", "r") as f:
cid_db = load(f)
def download(url: str, path: Path):
path.parent.mkdir(parents=True, exist_ok=True)
response = get(url)
with open(path, 'wb') as f:
f.write(response.content)
rmtree('assets', ignore_errors=True)
mkdir('assets')
manifest = loads(get(MANIFEST_URL).text)
# Download assets
# Download assetIndex
print("Downloading assetIndex...")
assetIndex = get(manifest['assetIndex']["url"]).json()
original_assetIndex = get(manifest['assetIndex']["url"]).json()
# Filter assets
# If hash is not in cid_db, save it
for key in list(assetIndex['objects']):
if assetIndex['objects'][key]['hash'] in cid_db:
del assetIndex['objects'][key]
# Download assets
for key in tqdm(assetIndex['objects'].values()):
download(f"https://resources.download.minecraft.net/{key['hash'][0:2]}/{key['hash']}", ASSET_PATH / "objects" / key['hash'][0:2] / key['hash'])
# Download client
if manifest["mainJar"]['downloads']['artifact']["sha1"] in cid_db:
print("Skipping client...")
else:
print("Downloading client...")
client = download(manifest["mainJar"]['downloads']['artifact']['url'], ASSET_PATH / "client.jar")
# Download libraries
print("Downloading libraries...")
for library in tqdm(manifest.get('libraries', [])):
if library['downloads'].get('artifact', None) is not None:
if library['downloads']['artifact']['sha1'] not in cid_db:
download(library['downloads']['artifact']['url'], ASSET_PATH / "libraries" / library['downloads']['artifact']['sha1'])
for classifier in library['downloads'].get('classifiers', {}):
if library['downloads']["classifiers"][classifier]['sha1'] not in cid_db:
download(library['downloads']["classifiers"][classifier]['url'], ASSET_PATH / "libraries" / library['downloads']["classifiers"][classifier]['sha1'])
# Upload to IPFS
if len(listdir(ASSET_PATH)) == 0:
print("Nothing to upload...")
else:
cid = find_cid(get_command_output("w3 put --no-wrap " + str(ASSET_PATH)))
# Fill cid_db
print("Filling cid_db...")
# Add assetIndex
for key in tqdm(assetIndex['objects']):
cid_db[assetIndex['objects'][key]['hash']] = cid + "/objects/" + assetIndex['objects'][key]['hash'][0:2] + "/" + assetIndex['objects'][key]['hash']
# Add client
if manifest["mainJar"]['downloads']['artifact']["sha1"] not in cid_db:
cid_db[manifest["mainJar"]['downloads']['artifact']["sha1"]] = cid + "/client.jar"
# Add libraries
for library in tqdm(manifest.get('libraries', [])):
if library['downloads'].get('artifact', None) is not None:
if library['downloads']['artifact']['sha1'] not in cid_db:
cid_db[library['downloads']['artifact']['sha1']] = cid + "/libraries/" + library['downloads']['artifact']['sha1']
for classifier in library['downloads'].get('classifiers', {}):
if library['downloads']["classifiers"][classifier]['sha1'] not in cid_db:
cid_db[library['downloads']["classifiers"][classifier]['sha1']] = cid + "/libraries/" + library['downloads']["classifiers"][classifier]['sha1']
rmtree('assets', ignore_errors=True)
mkdir('assets')
# Make modified assetIndex
print("Making modified assetIndex...")
new_assetIndex = {}
for key in original_assetIndex['objects']:
new_assetIndex[key] = {
"hash": original_assetIndex['objects'][key]['hash'],
"size": original_assetIndex['objects'][key]['size'],
"path": cid_db[original_assetIndex['objects'][key]['hash']]
}
assetIndex_data = dumps({ "objects": new_assetIndex }, indent=2)
assetIndex_hash = sha1(assetIndex_data.encode()).hexdigest()
if assetIndex_hash in cid_db:
print("Skipping modified assetIndex...")
else:
with open(ASSET_PATH / "assetIndex.json", "w") as f:
f.write(assetIndex_data)
cid = find_cid(get_command_output("w3 put --no-wrap " + str(ASSET_PATH / "assetIndex.json")))
cid_db[assetIndex_hash] = cid
# Modify manifest to use IPFS
print("Modifying manifest...")
del manifest['assetIndex']['url']
manifest['assetIndex']['sha1'] = assetIndex_hash
manifest['assetIndex']['size'] = len(assetIndex_data)
manifest['assetIndex']['path'] = cid_db[assetIndex_hash]
del manifest["mainJar"]['downloads']['artifact']['url']
manifest["mainJar"]['downloads']['artifact']['path'] = cid_db[manifest["mainJar"]['downloads']['artifact']['sha1']]
for library in manifest.get('libraries', []):
if library['downloads'].get('artifact', None) is not None:
del library['downloads']['artifact']['url']
library['downloads']['artifact']['path'] = cid_db[library['downloads']['artifact']['sha1']]
for classifier in library['downloads'].get('classifiers', {}):
del library['downloads']["classifiers"][classifier]['url']
library['downloads']["classifiers"][classifier]['path'] = cid_db[library['downloads']["classifiers"][classifier]['sha1']]
# Save manifest
print("Saving manifest...")
with open("net.minecraft/" + version_id + ".json", "w") as f:
dump(manifest, f, indent=2)
# Save cid_db
print("Saving cid_db...")
with open("cid_db.json", "w") as f:
dump(cid_db, f, indent=2)
version_index = get("https://meta.prismlauncher.org/v1/net.minecraft/index.json").json()
for version in version_index['versions']:
version_id = version['version']
# if re.findall(r"^\d+\.\d+\.\d+$", version_id) == []:
# print(f"Skipping {version_id}...")
# continue
# skip = False
# for name in listdir("versions"):
# if version_id + ".json" in name:
# print(f"Skipping {version_id}...")
# skip = True
# break
# if skip:
# continue
print(f"Processing {version_id}...")
try:
main(f"https://meta.prismlauncher.org/v1/net.minecraft/{version_id}.json", version_id)
except Exception:
print_exc()
print(f"Failed to process {version_id}...")
with open("cid_db.json", "r") as f:
cid_db = load(f)
lst = listdir("net.minecraft")
# Upload to IPFS
get_command_output("git add .")
to_delete = []
for i, version in enumerate(version_index["versions"]):
del version_index["versions"][i]["sha256"]
if version["version"] + ".json" not in lst:
to_delete.append(version["version"])
continue
# Calculate sha1
with open("net.minecraft/" + version["version"] + ".json", "rb") as f:
version_index["versions"][i]["sha1"] = sha1(f.read()).hexdigest()
# If sha1 not in cid_db, upload
if version_index["versions"][i]["sha1"] not in cid_db:
# Upload file
path = find_cid(get_command_output("w3 put --no-wrap net.minecraft/" + version["version"].replace(" ", "\\ ") + ".json"))
# Add to cid_db
cid_db[version_index["versions"][i]["sha1"]] = path
version_index["versions"][i]["path"] = cid_db[version_index["versions"][i]["sha1"]]
# Delete old versions
for version in to_delete:
for i, v in enumerate(version_index["versions"]):
if v["version"] == version:
del version_index["versions"][i]
with open("net.minecraft/index.json", "w") as f:
dump(version_index, f, indent=2)
changed = get_command_output("git diff --name-only").split("\n")
if "net.minecraft/index.json" in changed:
print("Uploading index.json...")
path = find_cid(get_command_output("w3 put --no-wrap net.minecraft/index.json"))
print(f"Path: {path}")
# Calculate sha1
with open("net.minecraft/index.json", "rb") as f:
version_index["sha1"] = sha1(f.read()).hexdigest()
print(f"SHA1: {version_index['sha1']}")
# Save cid_db
print("Saving cid_db...")
with open("cid_db.json", "w") as f:
dump(cid_db, f, indent=2)