-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
344 lines (312 loc) · 10.6 KB
/
Copy pathserver.js
File metadata and controls
344 lines (312 loc) · 10.6 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
if (process.argv.includes("--help") || process.argv.includes("-h")) {
console.log(`Usage: node server.js [options]
Options:
--no-rebuild Do not rebuild resource packs and behaviour packs on server start.
--venv <path> Specify the path to the python virtual environment to activate before running the rebuild commands.
--no-format Skip formatting during the rebuild process.
--dev Enable development mode, allowing the server to respond to update requests over http and enables more logging.
--exit-on-update Exit the server after a successful update.
--help, -h Show this help message.`);
process.exit(0);
}
const { execSync } = require("child_process");
const requiredPackages = [
"express",
"fs",
"path",
"cors",
"https",
"nodemon",
"lodash",
];
function checkAndInstallPackages(packages) {
packages.forEach((pkg) => {
try {
require.resolve(pkg);
} catch (e) {
console.log(`${pkg} is not installed. Installing...`);
execSync(`npm install ${pkg}`, { stdio: "inherit" });
}
});
}
checkAndInstallPackages(requiredPackages);
const filesystem = require("fs");
const path = require("path");
const { makePackRequest } = require('./packCreation')
const { cdir, loadJson, dumpJson, isBashInstalled, uuidv4 } = require("./helperFunctions.js");
const httpsApp = require('./https-server').initHttpsServer()
const httpApp = require('./http-server').initHttpServer()
const currentdir = process.cwd();
const secretStuffPath = path.join(currentdir, "secretstuff.json");
const os = require("os");
if (!process.argv.includes("--no-rebuild")) {
let venvActivationScriptPath = null;
for (let i = 0; i < process.argv.length; i++) {
if (process.argv[i] === "--venv" && i + 1 < process.argv.length) {
venvActivationScriptPath = process.argv[i + 1];
break;
}
}
const isWindows = os.platform() === "win32";
const bashIsInstalled = isBashInstalled();
const usingBash = !isWindows && bashIsInstalled;
let commandRunnerPrefix = usingBash ? 'bash -c ' : "powershell -Command";
const runBuildCommand = (dir) => {
console.log(`Rebuilding ${dir.split(path.sep).pop()}...`);
process.chdir(dir);
// check uv installation
let uvAvailable;
try {
execSync("uv --version", { stdio: "ignore" });
uvAvailable = true
} catch {
uvAvailable = false
}
let fullCommand = `python pys/pre_commit.py --no-stash --build server --no-spinner ${process.argv.includes("--no-format") ? "" : "--format"}`;
fullCommand = uvAvailable ? `uv run ${fullCommand}` : fullCommand
if (venvActivationScriptPath != null) {
if (venvActivationScriptPath) {
if (usingBash) {
fullCommand = `source ${venvActivationScriptPath} && ${fullCommand}`;
} else {
fullCommand = `& { . "${venvActivationScriptPath}" | Out-Null; ${fullCommand} }`;
}
}
}
try {
const finalExecCommand = usingBash ? fullCommand : fullCommand.replace(/"/g, '`"');
execSync(`${commandRunnerPrefix} "${finalExecCommand}"`, { stdio: "inherit" });
execSync("git add .");
} catch (error) {
console.error(`Error during ${dir.split(path.sep).pop()} rebuild:`, error.message);
process.exit(1);
}
};
console.log("Rebuilding...");
runBuildCommand(cdir("resource"));
runBuildCommand(cdir("behaviour"));
runBuildCommand(cdir("crafting"));
process.chdir(currentdir);
console.log("Rebuild complete! Setting up server...");
}
if (process.env.npm_lifecycle_script !== "nodemon" && !(process.env.PM2_HOME || process.env.PM2_ENV)) {
console.warn(
"It is recommended to use nodemon when developing or pm2 when running the server.",
);
console.warn("Command: `npx nodemon server.js`");
}
httpApp.post("/exportResourcePack", (req, res) => {
makePackRequest(req, res, "resource");
});
httpApp.post("/exportBehaviourPack", (req, res) => {
makePackRequest(req, res, "behaviour");
});
httpApp.post("/exportCraftingTweak", (req, res) => {
makePackRequest(req, res, "crafting");
});
httpApp.get("/downloadTotals", (req, res) => {
downloadTotals(req, res);
});
httpApp.post("/update", (req, res) => {
if (process.argv.includes("--dev")) {
updateServer(req, res);
}
else {
// https://httpmemes.netlify.app/status/405
res.status(405).send("Updates over HTTP are disabled. Use HTTPS server or enable dev mode.");
}
});
if (process.argv.includes("--dev")) {
httpApp.get("/checkOnline", (req, res) => {
checkOnline(req, res);
});
}
httpApp.get("/ping", (req, res) => {
res.send("Pong!");
});
httpApp.get("/{*splat}", (req, res) => {
res.send(
"There's nothing here, you should probably enter into the submodules to find the website.",
);
});
if (httpsApp) {
httpsApp.post("/exportResourcePack", (req, res) => {
makePackRequest(req, res, "resource");
});
httpsApp.post("/exportBehaviourPack", (req, res) => {
makePackRequest(req, res, "behaviour");
});
httpsApp.post("/exportCraftingTweak", (req, res) => {
makePackRequest(req, res, "crafting");
});
httpsApp.get("/downloadTotals", (req, res) => {
downloadTotals(req, res);
});
httpsApp.post("/update", (req, res) => {
updateServer(req, res);
});
httpsApp.get("/checkOnline", (req, res) => {
checkOnline(req, res);
});
httpsApp.get("/ping", (req, res) => {
res.send("Pong!");
});
httpsApp.get("/{*splat}", (req, res) => {
// https://httpmemes.netlify.app/status/308
res.status(308).redirect("https://becomtweaks.github.io");
});
}
function downloadTotals(req, res) {
const type = req.query.type;
if (!type) {
res.status(400).send("You need a specified query. The only query parameter available is `type`.");
} else {
console.log(`${cdir("base")}/downloadTotals${type}.json`, filesystem.existsSync(`${cdir("base")}/downloadTotals${type}.json`));
if (filesystem.existsSync(`${cdir("base")}/downloadTotals${type}.json`)) {
res.sendFile(`${cdir("base")}/downloadTotals${type}.json`, (err) => {
if (err) {
console.error("Error sending file:", err);
}
});
} else {
res.status(404).type('text/plain').send(`There is no such file called downloadTotals${type}.json at the root directory`);
}
}
}
function updateServer(req, res) {
const key = req.query.key;
if (!key) {
// https://httpmemes.netlify.app/status/401
res.status(401).send("You need a key to update the server.");
return;
}
if (!filesystem.existsSync(secretStuffPath)) {
const newkey = uuidv4();
const secretStuff = { key: newkey };
dumpJson(secretStuffPath, secretStuff);
return res
// https://httpmemes.netlify.app/status/201
.status(201)
.send("Secret stuff file not found. Made a new one.");
}
const secretStuff = loadJson(secretStuffPath);
const storedkey = secretStuff.key;
if (key === storedkey) {
try {
console.log("Pulling from git...");
const gitPullOutput = execSync("git pull --rebase").toString();
console.log("Pulled from git.");
console.log("Updating Submodules...");
const gitSubmoduleOutput = execSync("git submodule update").toString();
console.log("Updated Submodules");
const gitStatusOutput = execSync("git status").toString();
const blue = "\x1b[34m";
const gray = "\x1b[90m";
const reset = "\x1b[0m";
const formattedResponse = `
${blue}Update Successful${reset}
${blue}Git Pull Output:${reset}
${gray}${gitPullOutput}${reset}
${blue}Submodule Update Output:${reset}
${gray}${gitSubmoduleOutput}${reset}
${blue}Git Status Output:${reset}
${gray}${gitStatusOutput}${reset}
Do a GET /checkOnline to see the changes.
`;
if (process.argv.includes("--exit-on-update") && !gitPullOutput.includes("Already up to date.")) {
res.status(410).send(formattedResponse);
process.exit(0);
} else {
return res.status(200).send(formattedResponse);
}
} catch (error) {
const red = "\x1b[31m";
const gray = "\x1b[90m";
const reset = "\x1b[0m";
console.error("Error during git operation:", error);
const errorResponse = `
${red}Error${reset}
There was an error pulling or updating submodules.
${gray}${error.toString()}${reset}
`;
return res.status(500).send(errorResponse);
}
} else {
// https://httpmemes.netlify.app/status/403
res.status(403).send("Wrong key!");
}
}
function checkOnline(req, res) {
try {
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
const gitLogOutput = escapeHtml(execSync("git log -1 --format=short").toString());
const gitSubmoduleOutput = escapeHtml(execSync("git submodule status").toString());
const colorizeGitLog = (log) => {
return log
.replace(
/commit\s([a-f0-9]+)/,
'<span style="color:#f14e32">commit $1</span>',
) // Commit hash
.replace(
/Author:\s(.+)/,
'<span style="color:#1f8ee2">Author: $1</span>',
) // Author
.replace(
/Date:\s+(.+)/,
'<span style="color:#9c9c9c">Date: $1</span>',
);
};
const colorizeSubmoduleStatus = (status) => {
return status.replace(
/([+\-0-9a-f]{40})\s([a-zA-Z0-9\-\/]+)/g,
'<span style="color:#f14e32">$1</span> <span style="color:#1f8ee2">$2</span>',
);
};
const formattedLog = colorizeGitLog(gitLogOutput);
const formattedSubmoduleStatus =
colorizeSubmoduleStatus(gitSubmoduleOutput);
res.send(`
<h1>Server is online</h1>
<h3>Local Repo Status</h3>
<pre>${formattedLog}</pre>
<h3>Submodule Status</h3>
<pre>${formattedSubmoduleStatus}</pre>
<style>
@import url('https://fonts.googleapis.com/css2?family=Cascadia+Code:ital,wght@0,200..700;1,200..700&display=swap');
body { font-family: "Cascadia Code" }
pre {
font-family: "Cascadia Code";
background-color: #1e1e1e;
padding: 10px;
color: #ddd;
border-radius: 5px
}
</style>
`);
} catch (error) {
console.error("Error during git commands:", error);
res.status(500).send(`
<h1>Error</h1>
<p>There was an error retrieving git information.</p>
<pre>${escapeHtml(error.toString())}</pre>
<style>
@import url('https://fonts.googleapis.com/css2?family=Cascadia+Code:ital,wght@0,200..700;1,200..700&display=swap');
body { font-family:"Cascadia Code" }
pre {
font-family: "Cascadia Code";
background-color: #1e1e1e;
padding: 10px;
color: #ddd;
border-radius: 5px
}
</style>
`);
}
}