-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpackCreation.js
More file actions
437 lines (419 loc) · 15.2 KB
/
packCreation.js
File metadata and controls
437 lines (419 loc) · 15.2 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
const lodash = require("lodash");
const filesystem = require("fs");
const path = require("path");
const zipFolder = require("./zip.js");
const { cdir, loadJson, dumpJson, uuidv4 } = require("./helperFunctions.js");
async function makePackRequest(req, res, type) {
const rawPackName = (req.headers.packname || `BTRP-${Math.floor(Math.random() * 1000000)}`)
const packName = (rawPackName.replaceAll(/[\.\/\\]/g, "") || `BTRP-${Math.floor(Math.random() * 1000000)}`)
let selectedPacks;
try {
selectedPacks = JSON.parse(req.body);
} catch (error) {
console.log("Error parsing request body:", req.body);
return res.status(400).send("Invalid JSON in request body.");
}
const mcVersion = req.headers.mcversion;
const zipPath = await createPack(selectedPacks, packName, type, mcVersion, res);
if (!zipPath)
return;
res.download(zipPath, `${path.basename(zipPath)}`, (err) => {
if (err) {
console.error("Error downloading the file:", err);
try {
res.status(500).send("Error downloading the file.");
} catch (e) {
console.log(e);
}
}
try {
filesystem.unlinkSync(zipPath);
} catch (e) {
console.log(e);
}
});
let downloadTotals = {};
let fileIndex = 0;
let fileName = `downloadTotals${type}.json`;
let fileLoaded = false;
while (!fileLoaded) {
try {
if (filesystem.existsSync(fileName)) {
downloadTotals = JSON.parse(filesystem.readFileSync(fileName, "utf8"));
}
fileLoaded = true;
} catch (e) {
console.log(`Error loading ${fileName}: ${e.message}. Trying next file index.`);
downloadTotals = {};
fileIndex++;
fileName = `downloadTotals${type}${fileIndex}.json`;
}
}
if (!Object.hasOwn(downloadTotals, "total")) {
downloadTotals["total"] = 0;
}
downloadTotals["total"] += 1;
for (var i in selectedPacks.raw) {
if (!Object.hasOwn(downloadTotals, selectedPacks.raw[i])) {
downloadTotals[selectedPacks.raw[i]] = 0;
}
downloadTotals[selectedPacks.raw[i]] += 1;
}
const sortedDownloadTotals = Object.entries(downloadTotals);
sortedDownloadTotals.sort((a, b) => b[1] - a[1]);
const sortedData = Object.fromEntries(sortedDownloadTotals);
let dumpFileName = `downloadTotals${type}.json`;
if (fileIndex > 0) {
dumpFileName = `downloadTotals${type}${fileIndex}.json`;
}
dumpJson(dumpFileName, sortedData);
}
function lsdir(directory) {
let folderList = [];
function traverseDir(currentDir) {
const entries = filesystem.readdirSync(currentDir, { withFileTypes: true });
entries.forEach((entry) => {
const fullPath = path.join(currentDir, entry.name);
const relativePath = path
.relative(directory, fullPath)
.replace(/\\/g, "/");
if (entry.isDirectory()) {
folderList.push(relativePath + "/");
traverseDir(fullPath);
} else {
folderList.push(relativePath);
}
});
}
traverseDir(directory);
return folderList;
}
async function createPack(selectedPacks, packName, type, mcVersion, res) {
let realManifest;
if (type == "behaviour") {
realManifest = generateManifest(selectedPacks, packName, type, mcVersion, res, "bp");
if (!realManifest) return null;
generateManifest(selectedPacks, packName, type, mcVersion, res, "rp");
} else {
realManifest = generateManifest(selectedPacks, packName, type, mcVersion, res);
}
if (!realManifest) return null;
console.log(`Generated default files for ${packName}`);
const [fromDir, priorities] = listOfFromDirectories(selectedPacks, type);
if (process.argv.includes('--dev')) console.log([fromDir, priorities]);
console.log(`Obtained list of directories and priorities`);
console.log(
`Exporting at ${cdir()}${path.sep}${realManifest.header.name}...`,
);
addFilesToPack(fromDir, priorities, type == "behaviour", realManifest);
console.log(`Copied tweaks`);
console.log(`${realManifest.header.name}.zip 1/2`);
let extension;
if (type == "behaviour") {
// check if pack needs rp
if (lsdir(`${cdir()}/${realManifest.header.name}/rp`).length > 3) {
// requires rp
extension = "mcaddon";
// 'link' as dependencies
const bpManifest = loadJson(`${cdir()}/${packName}/bp/manifest.json`);
const rpManifest = loadJson(`${cdir()}/${packName}/rp/manifest.json`);
if (bpManifest.dependencies === undefined) {
bpManifest.dependencies = [];
}
if (rpManifest.dependencies === undefined) {
rpManifest.dependencies = [];
}
// add the dependencies to the manifest
bpManifest.dependencies.push({
uuid: rpManifest.header.uuid,
version: [1, 0, 0],
});
rpManifest.dependencies.push({
uuid: bpManifest.header.uuid,
version: [1, 0, 0],
});
dumpJson(`${cdir()}/${packName}/bp/manifest.json`, bpManifest);
dumpJson(`${cdir()}/${packName}/rp/manifest.json`, rpManifest);
if (process.argv.includes('--dev')) console.log(bpManifest.dependencies);
if (process.argv.includes('--dev')) console.log(rpManifest.dependencies);
} else {
// does not require rp
extension = "mcpack";
filesystem.rmSync(`${cdir()}/${realManifest.header.name}/rp/`, {
recursive: true,
});
}
} else {
extension = "mcpack";
}
await zipFolder(`${cdir()}/${realManifest.header.name}`);
console.log(`${realManifest.header.name}.${extension} 2/2`);
filesystem.renameSync(
`${path.join(cdir(), realManifest.header.name)}.zip`,
`${path.join(cdir(), realManifest.header.name)}.${extension}`,
);
filesystem.rmSync(`${cdir()}/${realManifest.header.name}`, {
recursive: true,
});
console.log(
`Exported at ${cdir()}${path.sep}${realManifest.header.name}.${extension}`,
);
return `${path.join(cdir(), realManifest.header.name)}.${extension}`;
}
function generateManifest(selectedPacks, packName, type, mcVersion, res, extra_dir = undefined) {
// generate the manifest
const regex =
/^\d\.\d\d$|^\d\.\d\d\.\d$|^\d\.\d\d\.\d\d$|^\d\.\d\d\.\d\d\d$/gm;
// check if manifest exists in pack alr
let templateManifest
if (extra_dir !== undefined) {
// this means that pack is bp
templateManifest = loadJson(
`${cdir(type)}/jsons/${extra_dir}manifest.json`,
);
} else {
templateManifest = loadJson(`${cdir(type)}/jsons/manifest.json`);
}
templateManifest.header.name = packName;
let description = "";
try {
for (let i in selectedPacks) {
if (i !== "raw" && selectedPacks[i].length !== 0) {
description += `\n${i}`;
selectedPacks[i].forEach((p) => {
description += `\n\t${p}`;
});
}
}
} catch (error) {
console.log("Invalid pack list.", selectedPacks);
res.status(400).send("Invalid pack list.");
return null;
}
templateManifest.header.description = description.slice(1);
if (regex.test(mcVersion)) {
let splitMCVersion = [];
console.log(`min_engine_version set to ${mcVersion}`);
for (var i = 0; i < 3; i++) {
if (mcVersion.split(".")[i])
splitMCVersion[i] = parseInt(mcVersion.split(".")[i]);
else splitMCVersion[i] = 0;
}
templateManifest.header.min_engine_version = splitMCVersion;
} else templateManifest.header.min_engine_version = [1, 21, 0];
templateManifest.header.uuid = uuidv4();
templateManifest.modules[0].uuid = uuidv4();
let packDir;
if (extra_dir !== undefined) {
packDir = `${cdir()}/${packName}/${extra_dir}`;
} else {
packDir = `${cdir()}/${templateManifest.header.name}`;
}
if (!filesystem.existsSync(packDir)) {
filesystem.mkdirSync(packDir, { recursive: true });
}
//templateManifest.modules[0].description = "The most ass filler description ever";
dumpJson(`${packDir}/manifest.json`, templateManifest);
let realManifest = templateManifest;
// add the pack icon
filesystem.copyFileSync(
`${cdir(type)}/pack_icons/pack_icon.png`,
`${packDir}/pack_icon.png`,
);
// add the selected packs for the easy selecting from site
dumpJson(`${packDir}/selected_packs.json`, selectedPacks);
return realManifest
}
function listOfFromDirectories(selectedPacks, type) {
let addedPacks = [];
let addedPacksPriority = []; // mapped priority of the fromDir
let fromDir = [];
let addedCompatibilitiesPacks = []; // doesnt require priority, just exists for checking purposes
const nameToJson = loadJson(`${cdir(type)}/jsons/map/name_to_json.json`);
const priorityMap = loadJson(`${cdir(type)}/jsons/map/priority.json`);
const compatibilities = loadJson(
`${cdir(type)}/jsons/map/compatibility.json`,
);
const comp_file = loadJson(`${cdir(type)}/jsons/packs/compatibilities.json`);
const max_comps = comp_file["max_simultaneous"];
for (let n = max_comps; n >= 2; n--) {
// for the love of god, change the key
compatibilities[`${n}way`].forEach((compatibility) => {
// check for compatibilities
let useThisCompatibility = true;
compatibility.forEach((packToCheck) => {
if (
!selectedPacks.raw.includes(packToCheck) ||
addedCompatibilitiesPacks.includes(packToCheck)
) {
useThisCompatibility = false;
}
});
if (useThisCompatibility) {
// get index in defs
const thisDefinedCompatibility =
comp_file[`${n}way`][
compatibilities[`${n}way`].indexOf(compatibility)
];
if (process.argv.includes("--dev")) console.log(thisDefinedCompatibility);
// check if you should overwrite
if (thisDefinedCompatibility.overwrite) {
// ignore adding respective packs
addedPacks.push(...compatibility);
}
addedCompatibilitiesPacks.push(...compatibility);
addedPacksPriority.push(999); // compatibilities shouldnt be affected by priorities
fromDir.push(
`${cdir(type)}/packs/${thisDefinedCompatibility.location}`,
);
}
});
}
const categoryKeys = Object.keys(selectedPacks);
categoryKeys.forEach((category) => {
if (category === "raw") {
return;
} else {
// Validate that category exists in nameToJson mapping
if (!nameToJson.hasOwnProperty(category)) {
console.warn(`Unknown category "${category}" - skipping`);
return;
}
// Additional check: ensure category name doesn't contain path traversal
if (category.includes('..') || category.includes('/') || category.includes('\\')) {
console.warn(`Invalid category name "${category}" - contains path traversal characters`);
return;
}
const currentCategoryJSON = loadJson(
`${cdir(type)}/jsons/packs/${nameToJson[category]}`,
);
let location;
if (currentCategoryJSON.location === undefined) {
location = currentCategoryJSON.topic;
location = location.toLowerCase();
} else {
location = currentCategoryJSON.location;
}
selectedPacks[category].forEach((pack) => {
if (typeof pack !== 'string') {
return;
}
// Sanitize pack name - remove path traversal characters (same as packName header)
const sanitizedPack = pack.replaceAll(/[\.\/\\]/g, "");
if (!sanitizedPack || addedPacks.includes(sanitizedPack)) {
return;
}
addedPacks.push(sanitizedPack);
fromDir.push(`${cdir(type)}/packs/${location}/${sanitizedPack}/files`);
addedPacksPriority.push(priorityMap[sanitizedPack]);
});
}
});
return [fromDir, addedPacksPriority];
}
function addFilesToPack(fromDir, priorities, isbehaviour, manifest) {
var addedFiles, addedFilesPriority;
if (isbehaviour) {
addedFiles = [
"bp/manifest.json",
"rp/manifest.json",
"bp/pack_icon.png",
"rp/pack_icon.png",
];
addedFilesPriority = [1000, 1000, 1000, 1000];
} else {
addedFiles = ["manifest.json", "pack_icon.png"];
addedFilesPriority = [1000, 1000];
}
fromDir.forEach((dir, dirIndexed) => {
const fromDirRecursive = lsdir(dir);
fromDirRecursive.forEach((item, itemIndexed) => {
const progress = `${item}`;
process.stdout.write(
`\r${progress}${" ".repeat(process.stdout.columns - progress.length)}`,
);
// skip the root directory
if (item === "./") {
return;
}
const targetPath = path.join(cdir(), manifest.header.name, item);
if (item.endsWith("/")) {
// create directory if it doesnt exist
if (!filesystem.existsSync(targetPath)) {
filesystem.mkdirSync(targetPath, { recursive: true });
}
} else {
// is a file
if (item.endsWith("manifest.json")) {
const alreadyExistingJson = loadJson(targetPath);
const newJson = loadJson(path.join(dir, item));
// only need modules, dependencies and metadata
try {
newJson.modules.forEach((module) => {
alreadyExistingJson.modules.push(module);
});
} catch (error) {
console.log("No modules found.");
}
try {
if (!Object.hasOwn(alreadyExistingJson, "dependencies")) {
alreadyExistingJson.dependencies = [];
}
newJson.dependencies.forEach((dependency) => {
alreadyExistingJson.dependencies.push(dependency);
});
} catch (error) {
console.log(`No dependencies found. ${error}`);
}
newJson.metadata.authors.forEach((author) => {
if (!alreadyExistingJson.metadata.authors.includes(author)) {
alreadyExistingJson.metadata.authors.push(author);
}
});
dumpJson(targetPath, alreadyExistingJson);
} else if (addedFiles.includes(item)) {
// already exists
if (item.endsWith(".json")) {
// first check if manifest.json
const alreadyExistingJson = loadJson(targetPath);
const newJson = loadJson(path.join(dir, item));
const customizer = (objValue, srcValue) => {
if (lodash.isArray(objValue) && lodash.isArray(srcValue)) {
return objValue.concat(srcValue);
}
return undefined;
};
const mergedData = lodash.mergeWith({}, newJson, alreadyExistingJson, customizer);
dumpJson(targetPath, mergedData);
} else if (
item.endsWith(".lang") ||
item.endsWith(".mcfunction") ||
item.endsWith(".txt") ||
item.endsWith(".js")
) {
// usually plaintext without needing proper formatting
const newFileToMerge = filesystem.readFileSync(
path.join(dir, item),
"utf-8",
);
filesystem.appendFileSync(targetPath, `\n${newFileToMerge}`);
} else if (
priorities[dirIndexed] >
priorities[addedFiles.indexOf(item)]
) {
// binary files, usually images
filesystem.copyFileSync(path.join(dir, item), targetPath);
priorities[addedFiles.indexOf(item)] = priorities[dirIndexed];
}
} else {
filesystem.copyFileSync(path.join(dir, item), targetPath);
priorities.push(priorities[dirIndexed]);
addedFiles.push(item);
}
}
});
});
}
module.exports = {
makePackRequest
}