-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.js
1370 lines (1115 loc) · 49.4 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const session = require('express-session');
const helmet = require('helmet');
const multer = require('multer');
const { Database } = require('sqlite3');
const { scheduleJob } = require('node-schedule');
const ws = require('ws');
const dateFns = require('date-fns');
const { join } = require('path');
const { readdirSync, unlink, rename, copyFile, existsSync, mkdir, writeFile } = require('fs');
const Logger = require('./resources/js/Logger');
const config = require('./config.json');
const { adminToken: defaultToken, sessionSecret: defaultSecret } = require('./config.sample.json');
const { version } = require('../package.json');
let counter = 0, daily = 0, weekly = 0, monthly = 0, yearly = 0, average = 0, fetchedDaysAmount = 1;
let sounds = [], statistics = [], chartData = [], milestones = [];
let databaseUpdateJob;
let socketConnections = [];
let queuedMainClicks = false, queuedSoundboardClicks = {};
let mainClickResponseInterval, soundboardClickResponseInterval;
// On-boot database interaction
const db = new Database(join(__dirname, config.databasePath), () => {
db.exec('PRAGMA foreign_keys = ON;', pragmaErr => {
if (pragmaErr) return Logger.error('Foreign key enforcement pragma query failed.');
});
});
db.serialize(() => {
db.get('SELECT counter FROM main_counter', [], (selectErr, row) => {
if (!row || row.counter === undefined) {
db.run('INSERT INTO main_counter ( counter ) VALUES ( 0 )');
return Logger.warn('Counter not found, automatically inserted into the database and loaded as 0.');
}
counter = row.counter;
return Logger.info('Main counter loaded.');
});
db.all('SELECT * FROM sounds', [], (selectErr, rows) => {
if (!rows) return Logger.warn('No sounds found.');
sounds = rows;
return Logger.info('Sounds & rankings loaded.');
});
db.run('INSERT OR IGNORE INTO statistics ( date, count ) VALUES ( date( \'now\', \'localtime\'), 0 )');
// Insert statistics entry for the boot day if it does not exist
db.all('SELECT * FROM statistics', [], (selectErr, rows) => {
if (!rows) return Logger.warn('No statistics found.');
const startOfBootWeek = dateFns.startOfWeek(new Date(), { weekStartsOn: 1 }), endOfBootWeek = dateFns.endOfWeek(new Date(), { weekStartsOn: 1 });
const startOfBootMonth = dateFns.startOfMonth(new Date()), endOfBootMonth = dateFns.endOfMonth(new Date());
const startOfBootYear = dateFns.startOfYear(new Date()), endOfBootYear = dateFns.endOfYear(new Date());
const thisWeek = rows.filter(row => dateFns.isWithinInterval(dateFns.parseISO(row.date), { start: startOfBootWeek, end: endOfBootWeek }));
const thisMonth = rows.filter(row => dateFns.isWithinInterval(dateFns.parseISO(row.date), { start: startOfBootMonth, end: endOfBootMonth }));
const thisYear = rows.filter(row => dateFns.isWithinInterval(dateFns.parseISO(row.date), { start: startOfBootYear, end: endOfBootYear }));
daily = rows.find(row => row.date === dateFns.format(new Date(), 'yyyy-MM-dd')).count;
weekly = thisWeek.reduce((total, date) => total += date.count, 0);
monthly = thisMonth.reduce((total, date) => total += date.count, 0);
yearly = thisYear.reduce((total, date) => total += date.count, 0);
fetchedDaysAmount = thisMonth.length;
average = Math.round(monthly / thisMonth.length);
statistics = rows;
return Logger.info('Statistics loaded.');
});
db.all('SELECT substr(date, 1, 7) AS month, sum(count) AS count FROM statistics GROUP BY month ORDER BY month ASC', [], (selectErr, rows) => {
if (!rows) return Logger.warn('No chart data found.');
chartData = rows;
return Logger.info('Chart data loaded.');
});
db.all('SELECT * FROM milestones', [], (selectErr, rows) => {
if (!rows) return Logger.warn('No milestones found.');
milestones = rows;
return Logger.info('Milestones loaded.');
});
});
function updateDatabase() {
db.serialize(() => {
db.run('UPDATE main_counter SET counter = ?', counter);
db.run('INSERT OR IGNORE INTO statistics ( date, count ) VALUES ( date("now", "localtime"), ? )', daily);
db.run('UPDATE statistics SET count = ? WHERE date = date("now", "localtime")', daily);
for (const sound of sounds) {
db.run('UPDATE sounds SET count = ? WHERE id = ?', sound.count, sound.id);
}
});
}
// Warning for default admin token and session secret
const warnings = [];
if (config.adminToken === defaultToken) warnings.push('Admin token');
if (config.sessionSecret === defaultSecret) warnings.push('Session secret');
if (warnings.length) {
Logger.warn(`Make sure to change the ${warnings.join(' and ')} value(s) in the configuration.`);
Logger.warn('If left unchanged, anyone can gain access to the admin panel and do as they please.');
}
// Webserver
const server = express();
const http = require('http').Server(server);
const pagePath = join(__dirname, '/pages');
const pages = [
{
name: 'robots.txt',
path: join(pagePath, 'robots.txt'),
route: '/robots.txt'
},
{
name: 'sitemap.xml',
path: join(pagePath, 'sitemap.xml'),
route: '/sitemap.xml'
}
];
function cleanString(string) {
return string.replace(/\s/g, '-').toLowerCase();
}
function updateConfigFile() {
writeFile(join(__dirname, 'config.json'), JSON.stringify(config, null, '\t'), err => {
if (err) {
Logger.error('An error occurred updating the configuration file.');
}
else {
Logger.info('Configuration file updated.');
}
});
}
function manageConnections(connectionLimit, ratelimit) {
if (connectionLimit > 0 || ratelimit > 0) {
if (socketConnections.length === 0) {
// Create data
socketServer.clients.forEach(client => {
let user = socketConnections.find(u => u.ip === client.realIP);
if (!user) {
user = {
ip: client.realIP,
connections: 1,
ratelimitClicks: 0,
ratelimitInterval: null
};
if (ratelimit > 0) {
user.ratelimitInterval = setInterval(() => {
if (user.connections === 0) {
// If user is no longer connected, clear their ratelimit interval and remove their info
clearInterval(user.ratelimitInterval);
socketConnections.splice(socketConnections.findIndex(u => u.ip === user.ip), 1);
}
user.ratelimitClicks = 0;
}, 1000 * 60);
}
socketConnections.push(user);
}
else {
if (connectionLimit > 0) {
if (user.connections >= connectionLimit) client.close(); // Close existing excess connections
else user.connections++;
}
}
});
}
else {
// Modify existing data
if (ratelimit > 0) {
socketConnections.forEach(user => {
clearInterval(user.ratelimitInterval); // Prevent duplication
user.ratelimitInterval = setInterval(() => {
if (user.connections === 0) {
// If user is no longer connected, clear their ratelimit interval and remove their info
clearInterval(user.ratelimitInterval);
socketConnections.splice(socketConnections.findIndex(u => u.ip === user.ip), 1);
}
user.ratelimitClicks = 0;
}, 1000 * 60);
});
}
if (ratelimit === -1) {
socketConnections.forEach(user => {
clearInterval(user.ratelimitInterval);
});
}
}
}
else {
// Clear data
socketConnections.forEach(c => clearInterval(c.ratelimitInterval));
socketConnections = [];
}
}
readdirSync(pagePath).filter(f => f.endsWith('.html')).forEach(file => {
const pageName = file.slice(0, -5).toLowerCase(); // -5 for cutting '.html'
pages.push({
name: file,
path: join(pagePath, file),
route: [`/${pageName}`, `/${pageName}.html`]
});
if (pageName === 'index') pages[pages.length - 1].route.push('/');
// Last array item because during current iteration it will be the last (adds root-dir route for index)
});
server.use(helmet({
hsts: false, // HSTS sent via nginx
contentSecurityPolicy: false
}));
server.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'"],
fontSrc: ["'self'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'"],
objectSrc: ["'none'"]
},
}));
if (config.proxy) server.set('trust proxy', true);
server.use(session({
secret: config.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: { secure: 'auto' },
unset: 'destroy'
}));
server.use(express.static('./resources'));
const apiRouter = express.Router();
apiRouter.use(express.urlencoded({ extended: true }));
apiRouter.use(express.json());
apiRouter.all('/*', (req, res, next) => {
const apiEndpoints = apiRouter.stack.filter(r => r.route).map(r => r.route.path);
if (!apiEndpoints.includes(req.path)) return res.status(404).json({ code: 404, name: 'Invalid route', message: 'Endpoint not found.' });
else return next();
});
apiRouter.get('/', (req, res) => {
return res.json({ code: 200, message: 'You have reached the megumin.love API.' });
});
apiRouter.get('/meta', (req, res) => {
return res.json({ port: config.port, version });
});
apiRouter.get('/counter', (req, res) => {
return res.json({ counter });
});
apiRouter.get('/themes', (req, res) => {
const themes = [...new Set(sounds.map(s => s.theme))];
return res.json(themes);
});
apiRouter.get('/sounds', (req, res) => { // eslint-disable-line complexity
let requestedSounds = sounds;
if (Object.keys(req.query).length) {
const { theme, source } = req.query;
const [equals, over, under] = [parseInt(req.query.equals), parseInt(req.query.over), parseInt(req.query.under)];
if ((req.query.equals && isNaN(equals)) || (req.query.over && isNaN(over)) || (req.query.under && isNaN(under))) {
// Check if the param was initially provided and if the input wasn't a number
return res.status(400).json({ code: 400, name: 'Invalid range', message: 'The "over", "under" and "equals" parameters must be numbers.' });
}
if ((over && under) && over > under) {
return res.status(400).json({ code: 400, name: 'Invalid range', message: 'The "under" parameter must be bigger than the "over" parameter.' });
}
// Theme filtering
if (theme) requestedSounds = requestedSounds.filter(sound => {
if (!sound.theme && theme === 'megumin') return true; // Default sounds have no theme
else return sound.theme === theme;
});
// Source filtering
if (source) requestedSounds = requestedSounds.filter(sound => {
if (sound.source === 'no-source') return false;
else return sound.source.toLowerCase() === source.toLowerCase();
});
// Count filtering
if (equals || over || under) {
if (equals) requestedSounds = requestedSounds.filter(sound => sound.count === equals);
else if (over && !under) requestedSounds = requestedSounds.filter(sound => sound.count > over);
else if (!over && under) requestedSounds = requestedSounds.filter(sound => sound.count < under);
else if (over && under) requestedSounds = requestedSounds.filter(sound => sound.count > over && sound.count < under);
}
}
return res.json(requestedSounds);
});
apiRouter.get('/statistics', (req, res) => { // eslint-disable-line complexity
let requestedStatistics = statistics;
const latestStatisticsEntry = dateFns.parseISO(statistics[statistics.length - 1].date);
// Grab latest statistics entry from the object itself instead of just today's date to make sure the entry exists
if (Object.keys(req.query).length) {
const [from, to] = [dateFns.parseISO(req.query.from), dateFns.parseISO(req.query.to)];
const [equals, over, under] = [parseInt(req.query.equals), parseInt(req.query.over), parseInt(req.query.under)];
if ((req.query.from && isNaN(from)) || (req.query.to && isNaN(to))) {
// Check if the param was initially provided, and if the input wasn't in the correct format
return res.status(400).json({ code: 400, name: 'Wrong Format', message: 'Dates must be provided in yyyy-MM-dd format.' });
}
if ((req.query.from && dateFns.isAfter(from, latestStatisticsEntry)) || (req.query.to && dateFns.isAfter(to, latestStatisticsEntry))) {
return res.status(400).json({ code: 400, name: 'Invalid timespan', message: 'Dates may not be in the future.' });
}
if ((req.query.from && req.query.to) && dateFns.isAfter(from, to)) {
return res.status(400).json({ code: 400, name: 'Invalid timespan', message: 'The start date must be before the end date.' });
}
if ((req.query.equals && isNaN(equals)) || (req.query.over && isNaN(over)) || (req.query.under && isNaN(under))) {
// Check if the param was initially provided, and if the input wasn't a number
return res.status(400).json({ code: 400, name: 'Invalid range', message: 'The "over", "under" and "equals" parameters must be numbers.' });
}
if ((over && under) && over > under) {
return res.status(400).json({ code: 400, name: 'Invalid range', message: 'The "under" parameter must be bigger than the "over" parameter.' });
}
// Date filtering
if (req.query.from && !req.query.to) {
requestedStatistics = requestedStatistics.filter(day => {
const parsedDate = dateFns.parseISO(day.date);
return dateFns.isWithinInterval(parsedDate, { start: from, end: latestStatisticsEntry });
});
}
else if (!req.query.from && req.query.to) {
requestedStatistics = requestedStatistics.filter(day => {
const parsedDate = dateFns.parseISO(day.date);
return dateFns.isSameDay(parsedDate, to) || dateFns.isBefore(parsedDate, to);
});
}
else if (req.query.from && req.query.to) {
requestedStatistics = requestedStatistics.filter(day => {
const parsedDate = dateFns.parseISO(day.date);
return dateFns.isWithinInterval(parsedDate, { start: from, end: to });
});
}
// Count filtering
if (equals || over || under) {
if (equals) {
requestedStatistics = requestedStatistics.filter(day => day.count === equals);
}
else if (over && !under) {
requestedStatistics = requestedStatistics.filter(day => day.count > over);
}
else if (!over && under) {
requestedStatistics = requestedStatistics.filter(day => day.count < under);
}
else if (over && under) {
requestedStatistics = requestedStatistics.filter(day => day.count > over && day.count < under);
}
}
}
return res.json(requestedStatistics);
});
apiRouter.get('/statistics/chartData', (req, res) => { // eslint-disable-line complexity
let requestedChartData = chartData;
const latestChartMonth = dateFns.parseISO(chartData[chartData.length - 1].month);
// Grab latest statistics entry from the object itself instead of just today's date to make sure the entry exists
if (Object.keys(req.query).length) {
const [from, to] = [dateFns.parseISO(req.query.from), dateFns.parseISO(req.query.to)];
const [equals, over, under] = [parseInt(req.query.equals), parseInt(req.query.over), parseInt(req.query.under)];
if ((req.query.from && isNaN(from)) || (req.query.to && isNaN(to))) {
// Check if the param was initially provided, and if the input wasn't in the correct format
return res.status(400).json({ code: 400, name: 'Wrong Format', message: 'Dates must be provided in yyyy-MM format.' });
}
if ((req.query.from && dateFns.isAfter(from, latestChartMonth)) || (req.query.to && dateFns.isAfter(to, latestChartMonth))) {
return res.status(400).json({ code: 400, name: 'Invalid timespan', message: 'Dates may not be in the future.' });
}
if ((req.query.from && req.query.to) && dateFns.isAfter(from, to)) {
return res.status(400).json({ code: 400, name: 'Invalid timespan', message: 'The start date must be before the end date.' });
}
if ((req.query.equals && isNaN(equals)) || (req.query.over && isNaN(over)) || (req.query.under && isNaN(under))) {
// Check if the param was initially provided, and if the input wasn't a number
return res.status(400).json({ code: 400, name: 'Invalid range', message: 'The "over", "under" and "equals" parameters must be numbers.' });
}
if ((over && under) && over > under) {
return res.status(400).json({ code: 400, name: 'Invalid range', message: 'The "under" parameter must be bigger than the "over" parameter.' });
}
// Date filtering
if (req.query.from && !req.query.to) {
requestedChartData = requestedChartData.filter(data => {
const parsedMonth = dateFns.parseISO(data.month);
return dateFns.isWithinInterval(parsedMonth, { start: from, end: latestChartMonth });
});
}
else if (!req.query.from && req.query.to) {
requestedChartData = requestedChartData.filter(data => {
const parsedMonth = dateFns.parseISO(data.month);
return dateFns.isSameMonth(parsedMonth, to) || dateFns.isBefore(parsedMonth, to);
});
}
else if (req.query.from && req.query.to) {
requestedChartData = requestedChartData.filter(data => {
const parsedMonth = dateFns.parseISO(data.month);
return dateFns.isWithinInterval(parsedMonth, { start: from, end: to });
});
}
// Count filtering
if (equals || over || under) {
if (equals) {
requestedChartData = requestedChartData.filter(data => data.count === equals);
}
else if (over && !under) {
requestedChartData = requestedChartData.filter(data => data.count > over);
}
else if (!over && under) {
requestedChartData = requestedChartData.filter(data => data.count < under);
}
else if (over && under) {
requestedChartData = requestedChartData.filter(data => data.count > over && data.count < under);
}
}
}
return res.json(requestedChartData);
});
apiRouter.get('/statistics/summary', (req, res) => {
return res.json({ alltime: counter, daily, weekly, monthly, yearly, average });
});
apiRouter.get('/statistics/milestones', (req, res) => {
const [reached, sound_id] = [parseInt(req.query.reached), parseInt(req.query.sound_id)];
let requestedMilestones = milestones;
if (!isNaN(reached)) {
requestedMilestones = requestedMilestones.filter(ms => ms.reached === reached);
}
if (!isNaN(sound_id)) {
requestedMilestones = requestedMilestones.filter(ms => ms.sound_id === sound_id);
}
return res.json(requestedMilestones);
});
apiRouter.post('/login', (req, res) => { // Only actual page (not raw API) uses this route
if (config.adminToken === req.body.token) {
req.session.loggedIn = true;
Logger.info('A user has logged in on the \'/login\' endpoint.');
return res.json({ code: 200, message: 'Successfully logged in!' });
}
else {
return res.status(401).json({ code: 401, name: 'Access denied', message: 'Invalid token provided.' });
}
});
apiRouter.all(['/admin/', '/admin/*'], (req, res, next) => {
if (req.session.loggedIn || config.adminToken === req.headers.authorization) {
Logger.info(`An authorized user has sent a request to the '${req.path}' endpoint.`);
return next();
}
else {
return res.status(401).json({ code: 401, name: 'Access denied', message: 'Invalid token provided.' });
}
});
apiRouter.get('/admin/logout', (req, res) => {
req.session.destroy();
Logger.info('A user has logged out of the admin panel.');
return res.json({ code: 200, message: 'Successfully logged out!' });
});
apiRouter.all('/admin/sounds/*', (req, res, next) => {
const originalData = req.body;
const parsedData = {};
Object.keys(originalData).forEach(d => {
if (!isNaN(parseInt(originalData[d]))) return parsedData[d] = parseInt(originalData[d]);
else if (typeof originalData[d] === 'string') return parsedData[d] = originalData[d].trim();
else return parsedData[d] = originalData[d];
});
if (parsedData.filename === '') {
return res.status(400).json({ code: 400, name: 'Invalid filename', message: 'Sound filename may not be an empty string if provided.' });
}
if (parsedData.filename && sounds.find(sound => sound.filename === parsedData.filename)) {
return res.status(400).json({ code: 400, name: 'Invalid filename', message: 'Sound filename already in use.' });
}
if (parsedData.count === '' || (originalData.count !== undefined && isNaN(parsedData.count))) {
return res.status(400).json({ code: 400, name: 'Invalid count', message: 'Sound click count must be an integer if provided.' });
}
if (originalData.id !== undefined && isNaN(parseInt(parsedData.id))) {
return res.status(400).json({ code: 400, name: 'Invalid sound', message: 'Sound ID must be an integer.' });
}
if (parsedData.id !== undefined && !sounds.find(sound => sound.id === parsedData.id)) {
return res.status(404).json({ code: 404, name: 'Invalid sound', message: 'Sound not found.' });
}
if (parsedData.filename) parsedData.filename = parsedData.filename.toString();
if (parsedData.displayname) parsedData.displayname = parsedData.displayname.toString();
if (parsedData.theme) parsedData.theme = parsedData.theme.toString();
if (parsedData.source) parsedData.source = parsedData.source.toString();
req.body = parsedData;
return next();
});
apiRouter.post('/admin/sounds/upload', multer({ dest: './resources/temp' }).single('file'), (req, res) => {
let newSound;
if (!req.file || (req.file && !['audio/mpeg', 'audio/mp3'].includes(req.file.mimetype))) {
if (req.file) unlink(req.file.path, delError => {
if (delError) {
Logger.error(`An error occurred deleting the temporary file '${req.file.filename}', please check manually.`);
return Logger.error(delError);
}
}); // If a wrong filetype was provided, delete the created temp file on rejection
return res.status(400).json({ code: 400, name: 'Invalid file', message: 'An mp3 file must be provided.' });
}
const data = req.body;
if (data.count === undefined) data.count = 0;
if (!data.theme) data.theme = 'megumin'; // Default theme
if (!data.source) data.source = 'no-source';
if (!Object.keys(data).includes('filename')) {
return res.status(400).json({ code: 400, name: 'Invalid filename', message: 'Sound filename must be provided.' });
}
Logger.info(`Sound '${data.filename}' (Shown as '${data.displayname}', from '${data.source}') now being uploaded.`);
const latestID = sounds.length ? sounds[sounds.length - 1].id : 0;
const valuePlaceholders = '?, '.repeat(Object.keys(data).length).slice(0, -2); // Cut off dangling comma and whitespace
const columnNames = Object.keys(data).map(k => `"${k}"`).join(', ');
const query = db.prepare(`INSERT INTO sounds ( ${columnNames} ) VALUES ( ${valuePlaceholders} )`);
query.run(...Object.values(data), insertErr => {
if (insertErr) {
Logger.error('An error occurred creating the database entry, upload aborted.');
Logger.error(insertErr);
unlink(req.file.path, delError => {
if (delError) {
Logger.error(`An error occurred deleting the temporary file '${req.file.filename}', please check manually.`);
return Logger.error(delError);
} // Delete temporary file on failure
});
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info('(1/3): Database entry successfully created.');
newSound = {
id: latestID + 1,
filename: data.filename,
displayname: data.displayname || null,
source: data.source,
count: data.count,
theme: data.theme
};
sounds.push(newSound);
Logger.info('(2/3): Sound cache entry successfully created.');
const folderPath = join('./resources/sounds/', cleanString(data.theme), cleanString(data.source));
const folderExists = existsSync(folderPath);
if (!folderExists) {
mkdir(folderPath, createErr => {
if (createErr) {
Logger.error('An error occurred creating the new sound folder.');
Logger.error(createErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
});
}
const soundPath = join(folderPath, `${data.filename}.mp3`);
rename(req.file.path, soundPath, renameErr => {
if (renameErr) {
Logger.error('An error occurred renaming the temporary file.');
Logger.error(renameErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
else Logger.info('(3/3): Uploaded mp3 file successfully renamed to requested filename.');
});
emitUpdate({
type: 'soundUpload',
sound: newSound
});
return res.json({ code: 200, message: 'Sound successfully uploaded.', sound: newSound });
});
});
apiRouter.patch('/admin/sounds/modify', (req, res) => {
const data = req.body;
const stepAmount = data.hasOwnProperty('filename') ? 5 : 2;
if (!data.id) {
return res.status(400).json({ code: 400, name: 'Invalid sound', message: 'Sound ID must be provided.' });
}
if (!['filename', 'displayname', 'source', 'count', 'theme'].some(p => Object.keys(data).includes(p))) {
return res.status(400).json({ code: 400, name: 'Invalid parameters', message: 'At least one property to modify must be provided.' });
}
const changedSound = sounds.find(sound => sound.id === data.id);
Logger.info(`Sound '${changedSound.filename}' now being modified.`);
if (!data.filename) data.filename = changedSound.filename;
let columnPlaceholders = '';
const changedProperties = Object.assign({}, data);
delete changedProperties.id; // Only properties to change wanted
Object.keys(changedProperties).forEach(k => columnPlaceholders += `"${k}" = ?, `);
columnPlaceholders = columnPlaceholders.slice(0, -2); // Cut off dangling comma and whitespace
const query = db.prepare(`UPDATE sounds SET ${columnPlaceholders} WHERE id = ?`);
query.run(...Object.values(changedProperties), data.id, updateErr => {
if (updateErr) {
Logger.error('An error occurred updating the database entry, renaming aborted.');
Logger.error(updateErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info(`(1/${stepAmount}): Database entry successfully updated.`);
const soundSource = cleanString(data.source || changedSound.source);
const soundTheme = cleanString(data.theme || changedSound.theme);
const newFolderPath = join('./resources/sounds/', soundTheme, soundSource);
const newFolderExists = existsSync(newFolderPath);
if (!newFolderExists) {
mkdir(newFolderPath, createErr => {
if (createErr) {
Logger.error('An error occurred creating the new sound folder.');
Logger.error(createErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
});
}
const oldFolderPath = join('./resources/sounds/', cleanString(changedSound.theme), cleanString(changedSound.source));
const oldSoundPath = join(oldFolderPath, `${changedSound.filename}.mp3`);
const newSoundPath = join(newFolderPath, `${data.filename}.mp3`);
Object.assign(changedSound, data);
Logger.info(`(2/${stepAmount}): Sound cache entry successfully updated.`);
if (data.filename || data.source || data.theme) {
copyFile(oldSoundPath, `${oldSoundPath}.bak`, copyErr => {
if (copyErr) {
Logger.error('An error occurred backing up the original mp3 file, renaming aborted.');
Logger.error(copyErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info(`(3/${stepAmount}): Original mp3 file successfully backed up.`);
rename(oldSoundPath, newSoundPath, renameErr => {
if (renameErr) {
Logger.error('An error occurred renaming the original mp3 file, renaming aborted, restoring backup.');
Logger.error(renameErr);
rename(`${oldSoundPath}.bak`, oldSoundPath, backupResErr => {
if (backupResErr) return Logger.error(`Backup restoration for the mp3 file failed.`);
});
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info(`(4/${stepAmount}): Original mp3 file successfully renamed.`);
unlink(`${oldSoundPath}.bak`, unlinkErr => {
if (unlinkErr) {
Logger.warn('An error occurred deleting the original mp3 backup, please delete manually.');
return Logger.error(unlinkErr);
}
Logger.info(`(5/${stepAmount}): Original mp3 backup successfully deleted.`);
});
});
});
}
emitUpdate({
type: 'soundModify',
sound: changedSound
});
return res.json({ code: 200, message: 'Sound successfully modified.', sound: changedSound });
});
});
apiRouter.delete('/admin/sounds/delete', (req, res) => {
const data = req.body;
const deletedSound = sounds.find(sound => sound.id === data.id);
Logger.info(`Sound '${deletedSound.filename}' now being deleted.`); // eslint-disable-line max-len
const query = db.prepare('DELETE FROM sounds WHERE id = ?');
query.run(data.id, deleteErr => {
if (deleteErr) {
Logger.error('An error occurred while deleting the database entry, deletion aborted.');
Logger.error(deleteErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info('(1/3): Database entry successfully deleted.');
sounds.splice(sounds.findIndex(sound => sound.id === deletedSound.id), 1);
Logger.info('(2/3): Sound cache entry successfully deleted.');
const sourceFolder = cleanString(deletedSound.source);
unlink(`./resources/sounds/${deletedSound.theme}/${sourceFolder}/${deletedSound.filename}.mp3`, unlinkErr => {
if (unlinkErr) {
Logger.error('An error occurred while deleting the mp3 file.');
Logger.error(unlinkErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info('(3/3): mp3 file successfully deleted.');
emitUpdate({
type: 'soundDelete',
sound: deletedSound
});
return res.json({ code: 200, message: 'Sound successfully deleted.', sound: deletedSound });
});
});
});
apiRouter.all('/admin/milestones/*', (req, res, next) => {
const originalData = req.body;
const parsedData = {};
Object.keys(originalData).forEach(d => {
if (!isNaN(parseInt(originalData[d]))) return parsedData[d] = parseInt(originalData[d]);
else if (typeof originalData[d] === 'string') return parsedData[d] = originalData[d].trim();
else return parsedData[d] = originalData[d];
});
if (originalData.id && isNaN(parsedData.id)) {
return res.status(400).json({ code: 400, name: 'Invalid milestone', message: 'Milestone ID must be an integer.' });
}
if (originalData.count !== undefined && isNaN(parsedData.count)) {
return res.status(400).json({ code: 400, name: 'Invalid count', message: 'Milestone count must be an integer.' });
}
if (originalData.reached !== undefined && isNaN(parsedData.reached)) {
return res.status(400).json({ code: 400, name: 'Invalid status', message: 'Milestone reached status must be an integer if provided.' });
}
if (originalData.timestamp && isNaN(parsedData.timestamp)) {
return res.status(400).json({ code: 400, name: 'Invalid timestamp', message: 'Milestone timestamp must be an integer if provided.' });
}
if (originalData.sound_id && isNaN(parsedData.sound_id)) {
return res.status(400).json({ code: 400, name: 'Invalid sound', message: 'Milestone sound_id must be an integer if provided.' });
}
if (originalData.reached !== undefined && (parsedData.reached !== 0 && parsedData.reached !== 1)) {
return res.status(400).json({ code: 400, name: 'Invalid status', message: 'Milestone reached status must be an integer of either 0 or 1 if provided.' }); // eslint-disable-line max-len
} // Checking for undefined because reached property can have value 0 which is falsy but still defined
if (originalData.id && !milestones.find(ms => ms.id === parsedData.id)) {
return res.status(404).json({ code: 404, name: 'Invalid milestone', message: 'Milestone not found.' });
}
req.body = parsedData;
return next();
});
apiRouter.post('/admin/milestones/add', (req, res) => {
const data = req.body;
if (!data.reached) data.reached = 0;
if (!data.count) {
return res.status(400).json({ code: 400, name: 'Invalid count', message: 'Milestone count must be provided.' });
}
Logger.info(`Milestone with count ${data.count} now being added.`);
if (milestones.find(ms => ms.count === data.count)) {
Logger.error(`A milestone with count ${data.count} already exists, adding aborted.`);
return res.status(400).json({ code: 400, name: 'Invalid count', message: 'Milestone with submitted count already exists.' });
}
else {
const latestID = milestones.length ? milestones[milestones.length - 1].id : 0;
const valuePlaceholders = '?, '.repeat(Object.keys(data).length).slice(0, -2); // Cut off dangling comma and whitespace
const columnNames = Object.keys(data).map(k => `"${k}"`).join(', ');
const query = db.prepare(`INSERT INTO milestones ( ${columnNames} ) VALUES ( ${valuePlaceholders} )`);
query.run(...Object.values(data), insertErr => {
if (insertErr) {
Logger.error('An error occurred creating the database entry, addition aborted.');
Logger.error(insertErr);
const errorCode = insertErr.code.includes('CONSTRAINT') ? 400 : 500;
const errorMessage = errorCode === 400 ? 'Sound ID must match a sound on the site.' : 'Please check the server console.';
const errorName = errorCode === 400 ? 'Invalid sound' : 'Serverside error';
return res.status(errorCode).json({ code: errorCode, name: errorName, message: errorMessage });
}
Logger.info('(1/2): Database entry successfully created.');
const newMilestone = {
id: latestID + 1,
count: data.count,
reached: data.reached,
timestamp: data.timestamp || null,
sound_id: data.sound_id || null
};
milestones.push(newMilestone);
Logger.info('(2/2): Milestone cache entry successfully created.');
emitUpdate({
type: 'milestoneAdd',
milestone: newMilestone
});
return res.json({ code: 200, message: 'Milestone successfully added.', milestone: newMilestone });
});
}
});
apiRouter.patch('/admin/milestones/modify', (req, res) => {
const data = req.body;
if (!data.id) {
return res.status(400).json({ code: 400, name: 'Invalid milestone', message: 'Milestone ID must be provided.' });
}
if (!['count', 'reached', 'timestamp', 'sound_id'].some(p => Object.keys(data).includes(p))) {
return res.status(400).json({ code: 400, name: 'Invalid parameters', message: 'At least one property to modify must be provided.' });
}
const changedMilestone = milestones.find(ms => ms.id === data.id);
Logger.info(`Milestone ${changedMilestone.id} (${changedMilestone.count} clicks) now being modified.`);
let columnPlaceholders = '';
const changedProperties = Object.assign({}, data);
delete changedProperties.id; // Only properties to change wanted
Object.keys(changedProperties).forEach(k => columnPlaceholders += `"${k}" = ?, `);
columnPlaceholders = columnPlaceholders.slice(0, -2); // Cut off dangling comma and whitespace
const query = db.prepare(`UPDATE milestones SET ${columnPlaceholders} WHERE id = ?`);
query.run(...Object.values(changedProperties), data.id, updateErr => {
if (updateErr) {
Logger.error('An error occurred updating the database entry, modification aborted.');
Logger.error(updateErr);
const errorCode = updateErr.code.includes('CONSTRAINT') ? 400 : 500;
const errorMessage = errorCode === 400 ? 'Sound ID must match a sound on the site.' : 'Please check the server console.';
const errorName = errorCode === 400 ? 'Invalid sound' : 'Serverside error';
return res.status(errorCode).json({ code: errorCode, name: errorName, message: errorMessage });
}
Logger.info('(1/2): Database entry successfully updated.');
Object.assign(changedMilestone, data);
Logger.info('(2/2): Milestone cache entry successfully updated.');
emitUpdate({
type: 'milestoneModify',
milestone: changedMilestone
});
return res.json({ code: 200, message: 'Milestone successfully modified.', milestone: changedMilestone });
});
});
apiRouter.delete('/admin/milestones/delete', (req, res) => {
const data = req.body;
if (!data.id) {
return res.status(400).json({ code: 400, name: 'Invalid milestone', message: 'Milestone ID must be provided.' });
}
const deletedMilestone = milestones.find(ms => ms.id === data.id);
Logger.info(`Milestone ${deletedMilestone.id} (${deletedMilestone.count} clicks) now being deleted.`);
const query = db.prepare('DELETE FROM milestones WHERE id = ?');
query.run(data.id, deleteErr => {
if (deleteErr) {
Logger.error('An error occurred while deleting the database entry, deletion aborted.');
Logger.error(deleteErr);
return res.status(500).json({ code: 500, name: 'Serverside error', message: 'Please check the server console.' });
}
Logger.info('(1/2): Database entry successfully deleted.');
milestones.splice(milestones.findIndex(ms => ms.id === deletedMilestone.id), 1);
Logger.info('(2/2): Milestone cache entry successfully deleted.');
emitUpdate({
type: 'milestoneDelete',
milestone: deletedMilestone
});
return res.json({ code: 200, message: 'Milestone successfully deleted.', milestone: deletedMilestone });
});
});
apiRouter.post('/admin/notification', (req, res) => {
const data = req.body;
if (!data.duration || !data.text) return res.json({ code: 400, name: 'Invalid notification', message: 'Notification text and duration must be provided.' });
Logger.info(`Announcement with text '${data.text}' displayed for ${data.duration} seconds.`);
emitUpdate({
type: 'notification',
notification: data
});
return res.json({ code: 200, message: 'Notification sent.', notification: data });
});
apiRouter.get('/admin/database/save', (req, res) => {
updateDatabase();
Logger.info('Database update initialized via the /admin/database/save endpoint.');
return res.json({ code: 200, message: 'Database successfully updated.' });
});
apiRouter.get('/admin/config', (req, res) => {
return res.json({
updateInterval: config.updateInterval,
socketConnections: config.socketConnections,
requestsPerMinute: config.requestsPerMinute,
responseInterval: config.responseInterval
});
});
apiRouter.patch('/admin/config/updateinterval', (req, res) => {
const data = req.body;
data.interval = parseInt(data.interval);
if (data.interval <= 0 || isNaN(data.interval)) {
return res.status(400).json({ code: 400, name: 'Invalid interval', message: 'Update interval must be any integer above 0.' });
}
config.updateInterval = data.interval;
databaseUpdateJob.reschedule(`*/${data.interval} * * * *`);
updateConfigFile();
Logger.info(`Database updating rescheduled to minute ${data.interval}.`);
return res.json({ code: 200, message: 'Update interval successfully updated', interval: data.interval });
});
apiRouter.patch('/admin/config/responseinterval', (req, res) => {
const data = req.body;
data.interval = parseInt(data.interval);
if (data.interval < -1 || data.interval === 0 || isNaN(data.interval)) {
return res.status(400).json({ code: 400, name: 'Invalid interval', message: 'Response interval must be either -1 or any number above 0.' });
}
if (data.interval === -1) config.responseInterval = -1;
else config.responseInterval = data.interval;
manageResponseIntervals(data.interval);
updateConfigFile();