This repository has been archived by the owner on Jun 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
379 lines (328 loc) · 10 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
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const sql = require('sql.js');
const fs = require('fs');
const nodemailer = require('nodemailer');
const uuid = require('uuid/v4');
const octokat = require('octokat');
const moment = require('moment');
const app = express();
const dbBuffer = fs.readFileSync('db.sqlite');
const db = new sql.Database(dbBuffer);
app.set('port', (process.env.PORT || 3001));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('frontend/build'));
}
process.on('exit', () => {
if (db) {
db.close();
}
});
/**
* Returns a function which maps a column name to the appropriate index.
* @private
*/
const makeUnderscore = function (result) {
return function (column) {
return result[0]['columns'].indexOf(column);
};
};
/**
* /api/productions
*
* Returns a list of productions.
*/
app.get('/api/productions', (req, res) => {
const result = db.exec('SELECT START, END, LOCATION, THEATER FROM PRODUCTION ORDER BY DATE( START ) ASC, DATE( END ) ASC');
if (!result[0]) {
return res.json({});
}
let _ = makeUnderscore(result);
return res.json(result[0]['values'].map(production => {
return {
'start': production[_('START')],
'end': production[_('END')],
'location': production[_('LOCATION')],
'theater': production[_('THEATER')],
};
}));
});
/**
* /api/actors
*
* Returns a list of all actors.
*/
app.get('/api/actors', (req, res) => {
const result = db.exec('SELECT ID, NAME FROM PERSON ORDER BY NAME ASC');
if (!result[0]) {
return res.json({});
}
let _ = makeUnderscore(result);
let response = {};
result[0]['values'].forEach(row => {
response[row[_('NAME')]] = {
'id': row[_('ID')],
};
});
return res.json(response);
});
/**
* /api/shows/stats
*
* Returns statistics about the dataset of shows.
*/
app.get('/api/shows/stats', (req, res) => {
const result = db.exec('SELECT COUNT( * ) AS CNT FROM SHOW');
if (!result[0]) {
return res.json({});
}
let _ = makeUnderscore(result);
return res.json({
'count': result[0]['values'][0][_('CNT')],
});
});
/**
* /api/shows/dates
*
* Returns a list of dates (YYYY-MM-DD) for which information is available for
* at least one show on that day.
*/
app.get('/api/shows/dates', (req, res) => {
const result = db.exec('SELECT DATE( DAY ) AS DAY, COUNT( * ) AS COUNT FROM SHOW GROUP BY DATE( DAY ) ORDER BY DATE( DAY ) ASC');
if (!result[0]) {
return res.json({});
}
let _ = makeUnderscore(result);
let response = {};
result[0]['values'].forEach(row => {
response[row[_('DAY')]] = {
'count': row[_('COUNT')],
};
});
return res.json(response);
});
/**
* /api/shows/:year/:month/:day
*
* Returns all shows on the specified day.
*/
app.get('/api/shows/:year/:month/:day', (req, res) => {
const { year, month, day } = req.params;
const showStatement = db.prepare(`
SELECT
"SHOW".ID,
DATE( "SHOW".DAY ) AS DAY,
"SHOW".TIME,
"SHOW".TYPE,
"PRODUCTION".LOCATION,
"PRODUCTION".THEATER
FROM "SHOW"
INNER JOIN "PRODUCTION" ON "SHOW".PRODUCTION_ID = "PRODUCTION".ID
WHERE DATE( "SHOW".DAY ) = :day
ORDER BY DATETIME( "SHOW".TIME ) ASC, "SHOW".TYPE ASC
`);
const castStatement = db.prepare(`
SELECT
"PERSON".ID,
"CAST".ROLE,
"PERSON".NAME
FROM "CAST"
INNER JOIN PERSON ON "CAST".PERSON_ID = "PERSON".ID
WHERE "CAST".SHOW_ID = :show
ORDER BY "CAST".ROLE ASC, "PERSON".NAME ASC
`);
let result = [];
try {
showStatement.bind({
':day': [year, month, day].join('-'),
});
while (showStatement.step()) {
let show = showStatement.getAsObject();
let cast = {};
castStatement.bind({
':show': show['ID'],
});
while (castStatement.step()) {
let person = castStatement.getAsObject();
cast[person['ROLE']] = cast[person['ROLE']] || [];
cast[person['ROLE']].push({
'id': person['ID'],
'name': person['NAME'],
});
}
result.push({
'id': show['ID'],
'day': show['DAY'],
'time': show['TIME'],
'type': show['TYPE'],
'location': show['LOCATION'],
'theater': show['THEATER'],
'cast': cast,
});
}
} finally {
showStatement.free();
castStatement.free();
}
return res.json(result);
});
/**
* /api/show/:location/:year/:month/:day/:time
*
* Returns a specific show.
*/
app.get('/api/show/:location/:year/:month/:day/:time', (req, res) => {
const { location, year, month, day, time } = req.params;
const showStatement = db.prepare(`
SELECT
"SHOW".ID,
DATE( "SHOW".DAY ) AS DAY,
"SHOW".TIME,
"SHOW".TYPE,
"PRODUCTION".LOCATION,
"PRODUCTION".THEATER
FROM "SHOW"
INNER JOIN "PRODUCTION" ON "SHOW".PRODUCTION_ID = "PRODUCTION".ID
WHERE DATE( "SHOW".DAY ) = :date
AND "SHOW".TIME = :time
AND "PRODUCTION".LOCATION = :location
`);
const castStatement = db.prepare(`
SELECT
"PERSON".ID,
"CAST".ROLE,
"PERSON".NAME
FROM "CAST"
INNER JOIN PERSON ON "CAST".PERSON_ID = "PERSON".ID
WHERE "CAST".SHOW_ID = :show
ORDER BY "CAST".ROLE ASC, "PERSON".NAME ASC
`);
let result = [];
try {
let show = showStatement.getAsObject({
':date': [year, month, day].join('-'),
':time': time,
':location': location,
});
let cast = {};
castStatement.bind({
':show': show['ID'],
});
while (castStatement.step()) {
let person = castStatement.getAsObject();
cast[person['ROLE']] = cast[person['ROLE']] || [];
cast[person['ROLE']].push({
'id': person['ID'],
'name': person['NAME'],
});
}
return res.json({
'id': show['ID'],
'day': show['DAY'],
'time': show['TIME'],
'type': show['TYPE'],
'location': show['LOCATION'],
'theater': show['THEATER'],
'cast': cast,
});
} finally {
showStatement.free();
castStatement.free();
}
return res.json({ 'error': 'Unknown error.' });
});
const submitCastList = async (data) => {
const featureBranch = `cast-${uuid()}`;
var octo = new octokat({ token: process.env.API_TOKEN });
var repo = octo.repos('tdv-casts', 'website');
const master = await repo.git.refs('heads/master').fetch();
const baseBranch = await repo.git.refs.create({
'ref': `refs/heads/${featureBranch}`,
'sha': master.object.sha,
});
const blob = await repo.git.blobs.create({ content: JSON.stringify(data, null, 4) });
const tree = await repo.git.trees.create({
'base_tree': baseBranch.object.sha,
'tree': [
{
'path': `database/data/${data.location}/${moment(data.day, 'DD.MM.YYYY').format('DD.MM.YYYY')}-${data.time.replace(/:/, '')}.json`,
'mode': '100644',
'type': 'blob',
'sha': blob.sha,
}
]
});
const commit = await repo.git.commits.create({
'message': `Added show ${data.day} ${data.time} (${data.location})`,
'tree': tree.sha,
'parents': [baseBranch.object.sha],
});
const updatedBaseBranch = await repo.git.refs(`heads/${featureBranch}`).update({
'sha': commit.sha,
'force': false,
});
const pr = await octo.fromUrl('/repos/tdv-casts/website/pulls').create({
'title': `Added show ${data.day} ${data.time} (${data.location})`,
'body': '',
'head': featureBranch,
'base': 'master',
});
};
const submitCastListViaEmail = data => {
let transporter = nodemailer.createTransport({
host: process.env.SUBMIT_EMAIL_HOST,
port: process.env.SUBMIT_EMAIL_PORT,
secure: false,
auth: {
user: process.env.SUBMIT_EMAIL_USER,
pass: process.env.SUBMIT_EMAIL_PASSWORD,
}
});
let mailOptions = {
from: '"TanzDerVampire.info" <[email protected]>',
to: '[email protected]',
subject: `TanzDerVampire.info – ${data.day} ${data.time}`,
text: JSON.stringify(data, null, 4),
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
};
app.post('/api/shows', bodyParser.json(), (req, res) => {
const data = req.body;
// TODO FIXME Validation
if (process.env.NODE_ENV !== 'production') {
console.log(`Submitted: ${JSON.stringify(data, null, 4)}`);
return res.json({});
}
try {
submitCastList(data).catch(err => {
if (err) {
throw err;
}
});
return res.json({});
} catch(e) {
try {
submitCastListViaEmail(data);
return res.json({});
} catch(e) {
return res.status(500).json({
'error': e.toString(),
});
}
}
});
/* Route everything else to index.html */
if (process.env.NODE_ENV === 'production') {
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
});
}
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`);
});