-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
398 lines (352 loc) · 11 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
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
// UTIL
const path = require('path');
const url = require('url');
// EXPRESS SERVER
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, './dist')));
// CONTENTFUL
const contentful = require('contentful');
const contenfulClient = contentful.createClient({
space: 'yt3y05y0gcz1',
accessToken: process.env.CONTENTFUL_KEY
});
// SESSIONS
let sessions = [];
const thirty_minutes = 1000 * 60 * 30;
const twelve_hours = thirty_minutes * 24;
const session_expirer = setInterval(() => {
sessions = sessions.filter(session => session.expires <= Date.now());
}, thirty_minutes);
// POSTGRES
const { Pool } = require('pg');
const pg_params = url.parse(process.env.DATABASE_URL);
const pg_auth = pg_params.auth.split(":");
const pool = Pool({
host: pg_params.hostname,
port: pg_params.port,
user: pg_auth[0],
database: pg_params.pathname.split('/')[1],
password: pg_auth[1],
ssl: true
});
pool.on('error', (err, client) => {
console.error(err);
console.log(client);
});
// sql helper functions
function loadSQLTable(table){
let q = 'SELECT * FROM ' +table;
if(table === 'matches'){
q += ' ORDER BY completed_at ASC';
} else if(table === 'tiers'){
q += ' ORDER BY key ASC';
}
return new Promise((resolve, reject) => {
pool.query(q)
.then(response => {
return resolve(response.rows);
})
.catch(err => reject(err));
});
}
function insertSQL(table, row){
let qu = 'INSERT INTO '+table;
qu += ' (';
qu += Object.keys(row).join(', ');
qu += ') VALUES(';
qu += Object.keys(row).map(key => {
return row[key];
}).map(val => {
if(Array.isArray(val)){
return "'" + (val.join(", ")).replace(/\'/g, "''") + "'";
} else if(typeof val === 'string'){
return "'"+(val).replace(/\'/g, "''")+"'";
} else {
return val;
}
}).join(', ');
qu += ');';
console.log(qu);
return new Promise((resolve, reject) => {
pool.query(qu)
.then(response => resolve(response))
.catch(err => reject(err));
})
}
function updateSQL(table, id, row){
let qu = 'UPDATE '+table+' ';
qu += 'SET ';
qu += Object.keys(row).map(key => {
let pair = [key, row[key]];
let s = pair[0] + '=';
if(typeof pair[1] === 'string'){
s += "'"+pair[1]+"'";
} else {
s += pair[1];
}
return s;
}).join(', ');
qu += ' WHERE id='+id+';';
return new Promise((resolve, reject) => {
pool.query(qu)
.then(response => resolve(response))
.catch(err => reject(err));
});
}
function countMatches(id1, id2){
return pool.query('SELECT COUNT(*) FROM matches WHERE (player1id='+id1+' AND player2id='+id2+') OR (player1id='+id2+' AND player2id='+id1+')');
}
// API
// security
app.post('/api/auth', (req, res) => {
new Promise((resolve, reject) => {
loadSQLTable('password').then(rows => {
resolve(rows[0].hash);
});
}).then(password => {
if(password === req.body.password){
let token;
let existing = [0];
while(existing.length){
token = Math.random() * Math.pow(10, 18);
existing = sessions.filter(session => session.token === token);
}
sessions.push({
token: token,
expires: Date.now() + twelve_hours
});
res.send(JSON.stringify({
"success": true,
"token": token
}));
} else {
res.send(JSON.stringify({
"success": false
}));
}
})
});
app.post('/api/verify_token', (req, res) => {
let existing = sessions.filter(session => {
return session.token+''.trim() === req.body.token+''.trim();
});
if(existing.length === 1){
existing[0].expires = Date.now() + twelve_hours;
}
res.send(JSON.stringify({
'success': existing.length === 1
}));
});
// delete a match
app.get('/api/delete_match/:id', (req, res) => {
pool.query('DELETE FROM matches WHERE id='+req.params.id)
.then(response => {
return buildLadder()
}, err => {
res.send(JSON.stringify({
'success': false,
'error': err
}))
})
.then(response => {
res.send(JSON.stringify({
'success': true
}))
});
});
// count matches between players
app.get('/api/count_matches/:id1/:id2', (req, res) => {
countMatches(req.params.id1, req.params.id2)
.then(response => {
res.send(JSON.stringify({
'success': true,
'count': parseInt(response.rows[0].count)
}))
}, err => {
res.send(JSON.stringify({
'success': false
}))
});
});
// rebuilding ladder
function buildLadder(tag){
return Promise.all(['events', 'matches', 'players', 'tiers'].map(loadSQLTable)).then(data => {
let events = data[0];
let matches = data[1];
let players = data[2];
let tiers = data[3];
if(tag){
let eventIDs = events.filter(event => event.tags.split(', ').indexOf(tag) > -1).map(event => event.id);
matches = matches.filter(match => eventIDs.indexOf(match.eventid) > -1);
}
players = players.map(player => {
return Object.assign({}, player, {
rank: 0,
tier: 0
});
});
matches.forEach(match => {
let winner = players.filter(player => player.id === match.winnerid)[0];
let loser = players.filter(player => player.id === match.loserid)[0];
winner.rank++;
if(winner.rank > tiers[winner.tier].ranks && tiers[winner.tier].ranks !== -1){
winner.rank = 0;
winner.tier++;
}
if(tiers[loser.tier].cantloose === false){
loser.rank--;
if(loser.rank < 0){
loser.tier--;
loser.rank = tiers[loser.tier].ranks;
}
}
});
return Promise.all(players.map(player => {
return updateSQL('players', player.id, player);
}));
})
}
app.get('/api/rebuild_players/:tag?', (req, res) => {
buildLadder(req.params.tag).then(() => {
res.send(JSON.stringify({
success: true
}))
})
});
// list all players with wins/losses
app.get('/api/players', (req, res) => {
const grid = {
wins: {},
losses: {}
};
loadSQLTable('matches')
.then(matches => {
for(let i = 0; i < matches.length; i++){
if(grid.wins.hasOwnProperty(matches[i].winnerid)){
grid.wins[matches[i].winnerid].push(matches[i].loserid);
} else {
grid.wins[matches[i].winnerid] = [matches[i].loserid];
}
if(grid.losses.hasOwnProperty(matches[i].loserid)){
grid.losses[matches[i].loserid].push(matches[i].winnerid);
} else {
grid.losses[matches[i].loserid] = [matches[i].winnerid];
}
}
return loadSQLTable('players');
}).then(players => {
for(let i = 0; i < players.length; i++){
if(grid.wins.hasOwnProperty(players[i].id)){
players[i].wins = grid.wins[players[i].id];
} else {
players[i].wins = [];
}
if(grid.losses.hasOwnProperty(players[i].id)){
players[i].losses = grid.losses[players[i].id];
} else {
players[i].losses = [];
}
}
res.send(JSON.stringify(players));
});
});
// dump a psql tablle
app.get('/api/table/:table', (req, res) => {
loadSQLTable(req.params.table).then(table => {
res.send(JSON.stringify(table));
})
});
// update a psql table somehow
app.post('/api/update/:table', (req, res) => {
let session = sessions.filter(session => {
return session.token === req.body.token && session.expires >= Date.now();
});
if(session.length === 0){
return res.send(JSON.stringify({
"success": false,
"reason": "Invalid token"
}));
}
let p;
switch(req.body.action){
case 'push':
p = insertSQL(req.params.table, req.body.data);
break;
case 'set':
p = updateSQL(req.params.table, req.body.id, req.body.data);
break;
default:
p = Promise.reject("Couldn't tell what you wanted me to do with that");
}
p.then(result => {
res.send(JSON.stringify({
"success": true
}));
}).catch(err => {
res.send(JSON.stringify({
"success": false,
"reason": err
}))
});
});
// contentful
// list events
app.get('/api/contentful/events', (req, res) => {
contenfulClient.getEntries({
"content_type": "event",
"order": "fields.date"
}).then(response => {
const events = response.items.map(item => {
return item.fields;
});
res.send(JSON.stringify(events));
});
});
// get a key/value pair (e.g., header image)
app.get('/api/contentful/lookup/:key', (req, res) => {
contenfulClient.getEntries({
"content_type": "lookup"
}).then(response => {
const value = response.items
.filter(item => {
return item.fields.key === req.params.key;
});
if(value.length !== 1) {
res.send(JSON.stringify({
success: false,
error: "Couldn't uniquely find the requested key."
}));
} else {
res.send(JSON.stringify({
success: true,
value: value[0].fields.value
}));
}
}, err => {
res.send(JSON.stringify({
success: false,
error: "Couldn't uniquely find the requested key."
}));
})
});
// reidrectors
app.get('/stats', (req, res) => {
res.redirect('https://docs.google.com/spreadsheets/d/1REA9dtbMEubxwO_U1bbGAjuXY7VL3cbpqeFbZvW4fhU/edit#gid=0');
});
app.get('/brackets', (req, res) => {
res.redirect('http://bs.challonge.com/');
});
app.get('/fb', (req, res) => {
res.redirect('https://www.facebook.com/BrightonStockSmash/');
});
app.get('/amnesty', (req, res) => {
res.redirect('https://www.facebook.com/events/132255724104523/');
});
app.get('*', (req, res) => {
res.sendFile(__dirname + '/dist/index.html');
});
const port = process.env.PORT || 3001;
app.listen(port, () => console.log('Listening on port', port));