-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
259 lines (216 loc) Β· 6.55 KB
/
server.js
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
const path = require('path');
const http = require('http');
// Require the fastify framework and instantiate it
const fastify = require('fastify')({
// set this to true for detailed logging:
logger: false
});
// Setup our static files
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'public'),
prefix: '/' // optional: default '/'
});
fastify.register(require('fastify-socket.io'), {
// put your options here
})
// fastify-formbody lets us parse incoming forms
fastify.register(require('fastify-formbody'));
// point-of-view is a templating manager for fastify
fastify.register(require('point-of-view'), {
engine: {
handlebars: require('handlebars')
}
});
// Our main GET home page route, pulls from src/pages/index.hbs
fastify.get('/', function(request, reply) {
// params is an object we'll pass to our handlebars template
const joinScript = buildJoinScript(process.env.URL || 'http://localhost:3000');
let params = {
joinScript,
joinScriptMin: joinScript.replace(/\n\s+/g, ' ')
};
// request.query.paramName <-- a querystring example
reply.view('/src/pages/index.hbs', params);
});
fastify.get('/login', function(request, reply) {
// request.query.paramName <-- a querystring example
reply.view('/src/pages/login.hbs', {});
});
fastify.get('/join', function(request, reply) {
// request.query.paramName <-- a querystring example
const joinScript = buildJoinScript(process.env.URL || 'http://localhost:3000', request.query.username);
let params = {
joinScript,
joinScriptMin: joinScript.replace(/\n\s+/g, ' ')
};
reply.view('/src/pages/join.hbs', params);
});
fastify.get('/watch', function(request, reply) {
// request.query.paramName <-- a querystring example
reply.view('/src/pages/watch.hbs', {challengeN: request.query.challenge || null });
});
fastify.post('/event', function (request, reply) {
fastify.io.emit('change', request.body);
reply.send();
});
fastify.post('/score', function (request, reply) {
fastify.io.emit('score', request.body);
reply.send();
});
// A POST route to handle form submissions
fastify.post('/', function(request, reply) {
let params = {
greeting: 'Hello Form!'
};
// request.body.paramName <-- a form post example
reply.view('/src/pages/index.hbs', params);
});
fastify.ready(err => {
if (err) throw err
fastify.io.on('connection', (socket) => {
console.log('a user connected');
socket.on('msg', (msg) => {
console.log('message: ' + msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
});
// Run the server and report out to the logs
fastify.listen(3000, function(err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log(`Your app is listening on ${address}`);
fastify.log.info(`server listening on ${address}`);
});
function buildJoinScript (serverUrl, uname = "") {
const username = uname ?? "";
return `(() => {
const challengeId = window.location.pathname.replace("/play/", "");
const username = "${username}";
function quickH (obj) {
return ((str, hash = 5381, i = null) => {
while (i ??= str.length) {
hash = (hash * 33) ^ str.charCodeAt(--i);
};
return hash >>> 0;
})(JSON.stringify(obj));
}
let
lastHash = -1,
debug = false,
name = "";
if (username !== "") {
name = username;
} else {
name = prompt('Enter your name to connect');
}
const editor = document.querySelector('.cm-editor .cm-content');
function req (payload) {
return {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify({...payload, challengeId})
};
}
let lastScH = null;
function postScore (payload) {
const disScH = quickH(payload);
if (disScH === lastScH) return;
lastScH = disScH;
if (debug) {
console.log(' π€ Sending score event with payload:', { payload });
}
return fetch(
'${serverUrl}/score',
req(payload)
).then(
resp => {
if (debug) {
console.log(' π€ recieved success:', { resp });
}
return resp;
},
err => {
if (debug) {
console.log(' π€ recieved error:', { err });
}
return err;
}
);
}
function fireAndForget (payload) {
const disH = quickH(payload);
if (disH === lastHash) return;
lastHash = disH;
if (debug) {
console.log(' π€ Sending change event with payload:', { payload });
}
return fetch(
'${serverUrl}/event',
req(payload)
).then(
resp => {
if (debug) {
console.log(' π€ recieved success:', { resp });
}
return resp;
},
err => {
if (debug) {
console.log(' π€ recieved error:', { err });
}
return err;
}
);
}
new MutationObserver((mutations) => {
mutations.forEach((m) => {
(m?.addedNodes ?? []).forEach((n) => {
const text = n?.textContent ?? null;
if (!text) return;
const found = text.match(/\s*You scored (\S+) with (\S+) match/i);
if (found?.length < 3) return;
const [_, score, percent] = found;
postScore({name, score, percent});
});
});
}).observe(document.querySelector(".Toastify"), { childList: true });
const timer = setInterval(() => {
fireAndForget({
name,
text: editor.innerText
});
}, 1000);
window.cssancelConn = () => {
const log = debug ? console.log : () => undefined;
if (!timer) {
log(' π€ No timer found to cancel.');
} else {
clearInterval(timer);
log(' π€ Timer canceled. Goodbye.');
}
};
window.csstoggleDebug = () => {
debug = !debug;
console.log(' π€ Set debug to:', debug);
};
console.group(' π₯ Welcome to css_head2head');
console.log('Some commands you might enjoy knowing...');
console.log(' π€ cssancleConn()', '- will end the connection to the server.');
console.log(' π€ csstoggleDebug()', '- will print messages for each action this little client takes.');
console.log(' βοΈ Happy battling. ');
console.groupEnd();
})()
`;
}