forked from ArnoldSmith86/virtualtabletop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
198 lines (168 loc) · 6.1 KB
/
server.mjs
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
import fs from 'fs';
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import http from 'http';
import CRC32 from 'crc-32';
import WebSocket from './server/websocket.mjs';
import Player from './server/player.mjs';
import Room from './server/room.mjs';
import MinifyRoom from './server/minify.mjs';
const app = express();
const server = http.Server(app);
const savedir = path.resolve() + '/save';
const sharedLinks = fs.existsSync(savedir + '/shares.json') ? JSON.parse(fs.readFileSync(savedir + '/shares.json')) : {};
fs.mkdirSync(savedir + '/assets', { recursive: true });
fs.mkdirSync(savedir + '/rooms', { recursive: true });
fs.mkdirSync(savedir + '/states', { recursive: true });
fs.mkdirSync(savedir + '/links', { recursive: true });
fs.mkdirSync(savedir + '/errors', { recursive: true });
function ensureRoomIsLoaded(id) {
if(!id.match(/^[A-Za-z0-9_-]+$/))
return false;
if(!activeRooms.has(id)) {
activeRooms.set(id, new Room(id, function() {
activeRooms.delete(id);
}));
}
return true;
}
async function downloadState(res, roomID, stateID, variantID) {
try {
if(ensureRoomIsLoaded(roomID)) {
const d = await activeRooms.get(roomID).download(stateID, variantID);
res.setHeader('Content-Type', d.type);
res.setHeader('Content-Disposition', `attachment; filename="${d.name.replace(/[^A-Za-z0-9._-]/g, '_')}"`);
res.send(d.content);
}
} catch(e) {
console.log(new Date().toISOString(), `EXCEPTION in downloadState for ${roomID}.${stateID}.${variantID}: ${String(e)}`);
res.sendStatus(500);
}
}
function autosaveRooms() {
setInterval(function() {
for(const [ _, room ] of activeRooms)
room.writeToFilesystem();
}, 60*1000);
}
MinifyRoom().then(function(result) {
app.use('/', express.static(path.resolve() + '/client'));
app.use('/i', express.static(path.resolve() + '/assets'));
app.use('/library', express.static(path.resolve() + '/library'));
app.get('/assets/:name', function(req, res) {
if(!req.params.name.match(/^[0-9_-]+$/))
return;
fs.readFile(savedir + '/assets/' + req.params.name, function(err, content) {
if(!content) {
res.sendStatus(404);
console.log(new Date().toISOString(), 'WARNING: Could not load asset ' + req.params.name);
return;
}
if(content[0] == 0xff)
res.setHeader('Content-Type', 'image/jpeg');
else if(content[0] == 0x89)
res.setHeader('Content-Type', 'image/png');
else if(content[0] == 0x3c)
res.setHeader('Content-Type', 'image/svg+xml');
else if(content[0] == 0x47)
res.setHeader('Content-Type', 'image/gif');
else if(content[0] == 0x52)
res.setHeader('Content-Type', 'image/webp');
else
console.log(new Date().toISOString(), 'WARNING: Unknown file type of asset ' + req.params.name);
res.send(content);
});
});
app.post('/quit', function(req, res) {
process.exit();
});
app.get('/', function(req, res) {
res.redirect(Math.random().toString(36).substring(3, 7));
});
app.get('/dl/:room/:state/:variant', function(req, res) {
downloadState(res, req.params.room, req.params.state, req.params.variant);
});
app.get('/dl/:room/:state', function(req, res) {
downloadState(res, req.params.room, req.params.state);
});
app.get('/dl/:room', function(req, res) {
downloadState(res, req.params.room);
});
app.get('/state/:room', function(req, res) {
if(ensureRoomIsLoaded(req.params.room)) {
res.setHeader('Content-Type', 'application/json');
const state = {...activeRooms.get(req.params.room).state};
delete state._meta;
res.send(JSON.stringify(state, null, ' '));
}
});
app.use(bodyParser.json({
limit: '10mb'
}));
app.put('/state/:room', function(req, res) {
if(typeof req.body == 'object') {
if(ensureRoomIsLoaded(req.params.room)) {
activeRooms.get(req.params.room).setState(req.body);
res.send('OK');
}
} else {
res.send('not a valid JSON object');
}
});
app.get('/s/:link/:junk', function(req, res) {
if(!sharedLinks[`/s/${req.params.link}`])
return res.status(404);
const tokens = sharedLinks[`/s/${req.params.link}`].split('/');
downloadState(res, tokens[2], tokens[3]);
});
app.get('/share/:room/:state', function(req, res) {
const target = `/dl/${req.params.room}/${req.params.state}`;
for(const link in sharedLinks)
if(sharedLinks[link] == target)
return res.send(link);
const newLink = `/s/${Math.random().toString(36).substring(3, 11)}`;
sharedLinks[newLink] = target;
fs.writeFileSync(savedir + '/shares.json', JSON.stringify(sharedLinks));
res.send(newLink);
});
app.get('/:id', function(req, res) {
if(!ensureRoomIsLoaded(req.params.id)) {
res.send('Invalid characters in room ID.');
return;
}
if(req.headers['accept-encoding'] && req.headers['accept-encoding'].match(/\bgzip\b/)) {
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Content-Type', 'text/html');
res.send(result.gzipped);
} else {
res.send(result.min);
}
});
app.use(bodyParser.raw({
limit: '100mb'
}));
app.put('/asset', function(req, res) {
const filename = `/assets/${CRC32.buf(req.body)}_${req.body.length}`;
if(!fs.existsSync(path.resolve() + '/save' + filename))
fs.writeFileSync(path.resolve() + '/save' + filename, req.body);
res.send(filename);
});
server.listen(process.env.PORT || 8272, function() {
console.log(new Date().toISOString(), 'Listening on ' + server.address().port);
});
});
const activeRooms = new Map();
const ws = new WebSocket(server, function(connection, { playerName, roomID }) {
if(ensureRoomIsLoaded(roomID))
activeRooms.get(roomID).addPlayer(new Player(connection, playerName, activeRooms.get(roomID)));
});
autosaveRooms();
['exit', 'SIGINT', 'SIGUSR1', 'SIGUSR2', 'SIGTERM'].forEach((eventType) => {
process.on(eventType, function() {
for(const [ _, room ] of activeRooms)
room.unload();
if(eventType != 'exit')
process.exit();
});
});