This repository has been archived by the owner on Mar 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
/
index.ts
168 lines (132 loc) · 5.82 KB
/
index.ts
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
/// <reference path="index.d.ts" />
import * as path from "path";
import * as fs from "fs";
import * as http from "http";
import * as express from "express";
import * as cookieParser from "cookie-parser";
import * as socketio from "socket.io";
import * as paths from "./paths";
import config from "./config";
import * as SupCore from "../SupCore";
import loadSystems from "./loadSystems";
import ProjectHub from "./ProjectHub";
// Globals
(<any>global).SupCore = SupCore;
let { version, superpowers: { appApiVersion: appApiVersion } } = JSON.parse(fs.readFileSync(`${__dirname}/../package.json`, { encoding: "utf8" }));
SupCore.log(`Server v${version} starting...`);
function handle404(err: any, req: express.Request, res: express.Response, next: Function) {
if (err.status === 404) { res.status(404).end("File not found"); return; }
next();
}
let hub: ProjectHub = null;
process.on("uncaughtException", (err: Error) => {
if (hub != null && hub.loadingProjectFolderName != null) {
SupCore.log(`The server crashed while loading project "${hub.loadingProjectFolderName}".\n${(<any>err).stack}`);
} else {
SupCore.log(`The server crashed.\n${(<any>err).stack}`);
}
process.exit(1);
});
// Public version
fs.writeFileSync(`${__dirname}/../public/superpowers.json`, JSON.stringify({ version, appApiVersion, hasPassword: config.password.length !== 0 }, null, 2));
// Main HTTP server
let mainApp = express();
let languageIds = fs.readdirSync(`${__dirname}/../public/locales`);
languageIds.unshift("none");
mainApp.use(cookieParser());
mainApp.use((req, res, next) => {
if (req.cookies["supLanguage"] == null) {
let language = req.header("Accept-Language");
if (language != null) {
language = language.split(",")[0];
if (languageIds.indexOf(language) === -1 && language.indexOf("-") !== -1) {
language = language.split("-")[0];
}
}
if (languageIds.indexOf(language) === -1) language = "en";
res.cookie("supLanguage", language);
}
next();
});
function redirectIfNoAuth(req: express.Request, res: express.Response, next: Function) {
if (req.cookies["supServerAuth"] == null) {
res.redirect(`/login?redirect=${encodeURIComponent(req.originalUrl)}`);
return;
}
next();
}
mainApp.get("/", (req, res) => { res.redirect("/hub"); });
mainApp.get("/hub", redirectIfNoAuth);
mainApp.get("/hub", (req, res) => {
res.sendFile(path.join(__dirname, "../public", "hub", paths.getLocalizedFilename("index.html", req.cookies["supLanguage"])));
});
mainApp.get("/project", redirectIfNoAuth);
mainApp.get("/project", (req, res) => {
res.sendFile(path.join(__dirname, "../public", "project", paths.getLocalizedFilename("index.html", req.cookies["supLanguage"])));
});
mainApp.get("/login", (req, res) => {
res.sendFile(path.join(__dirname, "../public", "login", paths.getLocalizedFilename("index.html", req.cookies["supLanguage"])));
});
mainApp.use("/", express.static(`${__dirname}/../public`));
mainApp.use("/projects/:projectId/*", (req, res) => {
let projectPath = hub.serversById[req.params.projectId].projectPath;
res.sendFile(req.params[0], { root: `${projectPath}/public` }, (err) => {
if (req.params[0] === "icon.png") res.sendFile("/images/default-project-icon.png", { root: `${__dirname}/../public` });
});
});
let mainHttpServer = http.createServer(mainApp);
mainHttpServer.on("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE") {
SupCore.log(`Could not start the server: another application is already listening on port ${config.mainPort}.`);
process.exit(1);
} else throw(err);
});
let io = socketio(mainHttpServer, { transports: ["websocket"] });
// Build HTTP server
let buildApp = express();
function redirectToHub(req: express.Request, res: express.Response) {
res.redirect(`http://${req.hostname}:${config.mainPort}/hub/`);
}
buildApp.get("/", redirectToHub);
buildApp.get("/systems/:systemName/SupCore.js", (req, res) => {
res.sendFile("SupCore.js", { root: `${__dirname}/../public` });
});
buildApp.use("/", express.static(`${__dirname}/../public`));
buildApp.get("/builds/:projectId/:buildId/*", (req, res) => {
let projectServer = hub.serversById[req.params.projectId];
if (projectServer == null) { res.status(404).end("No such project"); return; }
res.sendFile(path.join(projectServer.buildsPath, req.params.buildId, req.params[0]));
});
let buildHttpServer = http.createServer(buildApp);
loadSystems(mainApp, buildApp, () => {
mainApp.use(handle404);
buildApp.use(handle404);
// Project hub
hub = new ProjectHub(io, (err: Error) => {
if (err != null) { SupCore.log(`Failed to start server:\n${(<any>err).stack}`); return; }
SupCore.log(`Loaded ${Object.keys(hub.serversById).length} projects from ${paths.projects}.`);
let hostname = (config.password.length === 0) ? "localhost" : "";
mainHttpServer.listen(config.mainPort, hostname, () => {
buildHttpServer.listen(config.buildPort, hostname, () => {
SupCore.log(`Main server started on port ${config.mainPort}, build server started on port ${config.buildPort}.`);
if (hostname === "localhost") SupCore.log("NOTE: Setup a password to allow other people to connect to your server.");
});
});
});
});
// Save on exit and handle crashes
let isQuitting = false;
function onExit() {
if (isQuitting) return;
isQuitting = true;
mainHttpServer.close();
buildHttpServer.close();
SupCore.log("Saving all projects...");
hub.saveAll((err: Error) => {
if (err != null) SupCore.log(`Error while exiting:\n${(<any>err).stack}`);
else SupCore.log("Exited cleanly.");
process.exit(0);
});
}
process.on("SIGINT", onExit);
process.on("message", (msg: string) => { if (msg === "stop") onExit(); });