-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwebsite.js
More file actions
1990 lines (1891 loc) · 84.2 KB
/
website.js
File metadata and controls
1990 lines (1891 loc) · 84.2 KB
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
'use strict';
let http = require('http');
let mysql = require('mysql');
let url = require('url');
let fs = require('fs');
let request = require('request');
let async = require('async');
let ejs = require('ejs');
let moment = require('moment');
let webpush = require('web-push');
let got = require('got');
let querystring = require('querystring');
let childProcess = require('child_process');
// From BarryCarlyon, thanks! https://github.com/BarryCarlyon/twitch_misc/blob/master/authentication/oidc_authentication/server.js
const jwt = require('jsonwebtoken');
let oidc_data = {};
let verifier_options;
let verifier_keys;
let verifier_client;
let jwksClient = require('jwks-rsa');
// Fetch OpenID data
// Twitch provides a endpoint that contains information about openID
// This includes the relevant endpoitns for authentatication
// And the available scopes
// And the keys for validation JWT's
got({
url: 'https://id.twitch.tv/oauth2/.well-known/openid-configuration',
method: 'GET',
responseType: 'json'
})
.then(resp => {
console.log('BOOT: Got openID config');
oidc_data = resp.body;
verifier_options = {
algorithms: oidc_data.id_token_signing_alg_values_supported,
audience: config['clientID'],
issuer: oidc_data.issuer
}
verifier_client = jwksClient({
jwksUri: oidc_data.jwks_uri
});
})
.catch(err => {
console.error('OIDC Got a', err);
});
// https://github.com/auth0/node-jsonwebtoken
function getKey(header, callback) {
verifier_client.getSigningKey(header.kid, function (err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
// END Barry Code
let download = function (uri, filename, callback) {
request.head(uri, function (err, res, body) {
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
let cfgfile = fs.readFileSync('nepbot.cfg', 'utf8');
let cfglines = cfgfile.match(/[^\r\n]+/g);
let dbpw = null;
let dbname = null;
let dbuser = null;
let dbhost = null;
let isLocalMode = false;
let config = {};
let cfgConfig = {};
for (let line of cfglines) {
let lineparts = line.split("=");
let name = lineparts[0];
let value = lineparts.slice(1).join("=");
if (name) {
cfgConfig[name] = value;
}
if (name === "dbpassword") {
dbpw = value;
} else if (name === "database") {
dbname = value;
} else if (name === "dbuser") {
dbuser = value;
} else if (name === "dbhost") {
dbhost = value;
} else if (name === "local") {
isLocalMode = true;
}
}
if (!isLocalMode) {
if (dbpw === null || dbname === null || dbuser === null || dbhost === null) {
process.exit(1);
return;
}
}
let con;
if (!isLocalMode) {
con = mysql.createConnection({
host: dbhost,
user: dbuser,
password: dbpw,
database: dbname,
charset: "utf8mb4"
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
}
let bootstrapwaifucss = fs.readFileSync('waifus-bootstrap.css', 'utf8');
let jsdata = {};
let jsfiles = fs.readdirSync("js/");
jsfiles.forEach(function (filename) {
jsdata[filename] = fs.readFileSync('js/' + filename, 'utf8');
});
jsdata['sw.js'] = fs.readFileSync('sw.js', 'utf-8'); //needs to be explicitly on the root
function booleanConfig(key) {
return key in config && !["off", "no", "false"].includes(config[key].trim().toLowerCase());
}
function renderTemplateAndEnd(filename, vars, res) {
vars["moment"] = moment;
vars["config"] = config;
vars["booleanConfig"] = booleanConfig;
ejs.renderFile(filename, vars, {}, function (err, str) {
if (err) {
throw err;
}
res.write(str);
res.end();
})
}
function httpError(res, code, status, body) {
res.writeHead(code, status);
if (body) {
res.write(body);
}
res.end();
}
function parseCookies(req) {
let header = req.headers.cookie;
let cookies = {};
if (!header) {
return cookies;
}
let split = header.split(';');
for (let item of split) {
let parts = item.split('=');
if (parts.length < 2) {
continue;
}
cookies[parts[0].trim()] = decodeURIComponent(parts.slice(1).join('='));
}
return cookies;
}
function parseRequestBody(req, callback) {
let body = '';
req.on('data', (data) => {
body += data;
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', () => {
callback(body);
});
}
function isAdminIdentity(identity, callback) {
con.query('SELECT 1 FROM admins WHERE LOWER(name) = ? LIMIT 1', [identity.login.toLowerCase()], function (err, result) {
if (err) {
callback(err, false);
return;
}
callback(null, result.length > 0);
});
}
function getAdminJWTSecret() {
return config['adminJwtSecret'] || config['adminjwtsecret'] || config['jwtSecret'] || config['jwtsecret'] || config['admin_jwt_secret'];
}
function issueAdminJWT(identity) {
let secret = getAdminJWTSecret();
if (!secret) {
throw new Error('Missing adminJwtSecret configuration');
}
return jwt.sign({
display_name: identity.display_name,
login: identity.login,
user_id: identity.user_id,
is_admin: true
}, secret, {
algorithm: 'HS256',
expiresIn: config['adminJwtExpirySeconds'] || '12h',
issuer: 'waifus-admin',
audience: 'waifus-admin-panel'
});
}
function readAdminJWT(req) {
let cookies = parseCookies(req);
if (!cookies.admin_token) {
return null;
}
let secret = getAdminJWTSecret();
if (!secret) {
return null;
}
try {
return jwt.verify(cookies.admin_token, secret, {
algorithms: ['HS256'],
issuer: 'waifus-admin',
audience: 'waifus-admin-panel'
});
} catch (e) {
return null;
}
}
function requireAdminJWT(req, res, callback) {
let payload = readAdminJWT(req);
if (!payload || payload.is_admin !== true) {
httpError(res, 403, 'Forbidden', 'Admin access required.');
return;
}
callback(payload);
}
function twitchOAuthStart(res) {
let clientID = config['clientID'];
let redirectUri = (config['siteHost'] || '').replace(/\/$/, '') + '/admin/twitch/callback';
if (!clientID || !config['siteHost']) {
httpError(res, 500, 'Server Error', 'Missing Twitch OAuth configuration.');
return;
}
let state = Math.random().toString(36).slice(2) + Date.now().toString(36);
let location = 'https://id.twitch.tv/oauth2/authorize?response_type=code&client_id=' + encodeURIComponent(clientID) +
'&redirect_uri=' + encodeURIComponent(redirectUri) + '&scope=openid&state=' + encodeURIComponent(state);
res.writeHead(302, {
'Location': location,
'Set-Cookie': 'twitch_admin_oauth_state=' + encodeURIComponent(state) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=600'
});
res.end();
}
function exchangeTwitchCode(code, callback) {
let clientID = config['clientID'];
let clientSecret = config['clientSecret'] || config['twitchclientsecret'] || config['twitchClientSecret'] || config['client_secret'];
let redirectUri = (config['siteHost'] || '').replace(/\/$/, '') + '/admin/twitch/callback';
if (!clientID || !clientSecret || !config['siteHost']) {
console.error('[admin-oauth] Missing Twitch OAuth config values. clientID?', !!clientID, 'clientSecret?', !!clientSecret, 'siteHost?', !!config['siteHost']);
callback(new Error('Missing Twitch OAuth config values clientID/clientSecret/siteHost'));
return;
}
console.log('[admin-oauth] Exchanging Twitch code for token. redirectUri=', redirectUri, 'codeLength=', String(code || '').length);
request.post({
url: 'https://id.twitch.tv/oauth2/token',
form: {
client_id: clientID,
client_secret: clientSecret,
code: code,
grant_type: 'authorization_code',
redirect_uri: redirectUri
},
json: true
}, function (err, response, body) {
if (err) {
console.error('[admin-oauth] Twitch token exchange request error:', err);
}
if (response) {
console.log('[admin-oauth] Twitch token exchange response status:', response.statusCode);
}
if (err || !body || !body.access_token) {
console.error('[admin-oauth] Twitch token exchange failed. Response body:', body);
callback(err || new Error('Missing access token from Twitch'));
return;
}
console.log('[admin-oauth] Twitch token exchange succeeded. accessTokenLength=', String(body.access_token || '').length);
callback(null, body.access_token);
});
}
function fetchTwitchUser(accessToken, callback) {
request.get({
url: 'https://api.twitch.tv/helix/users',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Client-ID': config['clientID']
},
json: true
}, function (err, response, body) {
if (err || !body || !body.data || body.data.length === 0) {
callback(err || new Error('Unable to fetch Twitch user profile'));
return;
}
let user = body.data[0];
callback(null, {
display_name: user.display_name,
login: user.login,
user_id: user.id
});
});
}
function getBoosterUpgradeColumns() {
let normalRarities = parseInt(config['numNormalRarities'] || '0', 10);
if (!normalRarities || normalRarities < 2) {
normalRarities = 6;
}
let columns = [];
for (let i = 0; i < normalRarities - 1; i++) {
columns.push('rarity' + i + 'UpgradeChance');
}
return columns;
}
function defaultBoosterFormData() {
let rarityChances = {};
for (let column of getBoosterUpgradeColumns()) {
rarityChances[column] = 1;
}
return {
name: '',
sortIndex: 0,
listed: 0,
buyable: 0,
cost: 0,
numCards: 1,
guaranteeRarity: 0,
guaranteeCount: 0,
useEventWeightings: 0,
maxEventTokens: 0,
eventTokenChance: 0,
canMega: 0,
applyScaling: 1,
guaranteedRaritySlots: '',
rarityChances: rarityChances
};
}
function parseBoosterForm(form) {
let booster = {
name: String(form.name || '').trim(),
sortIndex: parseInt(form.sortIndex || '0', 10),
listed: form.listed === '1' ? 1 : 0,
buyable: form.buyable === '1' ? 1 : 0,
cost: parseInt(form.cost || '0', 10),
numCards: parseInt(form.numCards || '0', 10),
guaranteeRarity: parseInt(form.guaranteeRarity || '0', 10),
guaranteeCount: parseInt(form.guaranteeCount || '0', 10),
useEventWeightings: form.useEventWeightings === '1' ? 1 : 0,
maxEventTokens: parseInt(form.maxEventTokens || '0', 10),
eventTokenChance: parseFloat(form.eventTokenChance || '0'),
canMega: form.canMega === '1' ? 1 : 0,
applyScaling: form.applyScaling === '1' ? 1 : 0,
guaranteedRaritySlots: String(form.guaranteedRaritySlots || '').trim(),
rarityChances: {}
};
for (let column of getBoosterUpgradeColumns()) {
booster.rarityChances[column] = parseFloat(form[column] || '1');
}
let invalidFields = [];
for (let field of ['sortIndex', 'cost', 'numCards', 'guaranteeRarity', 'guaranteeCount', 'maxEventTokens', 'eventTokenChance']) {
if (Number.isNaN(booster[field])) {
invalidFields.push(field);
}
}
for (let column of Object.keys(booster.rarityChances)) {
if (Number.isNaN(booster.rarityChances[column])) {
invalidFields.push(column);
}
}
if (invalidFields.length) {
console.warn('[admin-booster] Parsed booster form contains invalid numeric fields.', {
name: booster.name,
invalidFields: invalidFields
});
}
return booster;
}
function renderAdminPanel(req, res, adminUser, message, editWaifu, boosterForm) {
res.writeHead(200, {'Content-Type': 'text/html'});
renderTemplateAndEnd('templates/admin.ejs', {
title: 'Admin Panel',
currentPage: 'admin',
user: adminUser.login,
isAdmin: true,
adminUser: adminUser,
message: message || '',
editWaifu: editWaifu || {
id: '',
name: '',
series: '',
image: '',
base_rarity: 0,
normal_weighting: 1,
event_weighting: 1
},
boosterForm: boosterForm || defaultBoosterFormData(),
boosterUpgradeColumns: getBoosterUpgradeColumns()
}, res);
}
function adminPanel(req, res) {
let adminUser = readAdminJWT(req);
if (!adminUser || adminUser.is_admin !== true) {
res.writeHead(302, {'Location': '/admin-login'});
res.end();
return;
}
renderAdminPanel(req, res, adminUser, '', null, null);
}
function adminLogout(res) {
res.writeHead(302, {
'Location': '/',
'Set-Cookie': 'admin_token=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'
});
res.end();
}
function adminLoadWaifu(req, res, query) {
requireAdminJWT(req, res, (adminUser) => {
let waifuID = parseInt(query.waifuId || '0', 10);
if (!waifuID) {
renderAdminPanel(req, res, adminUser, 'Please provide a valid Waifu ID to load.', null, null);
return;
}
con.query('SELECT id, name, series, image, base_rarity, normal_weighting, event_weighting FROM waifus WHERE id = ? LIMIT 1', [waifuID], (err, rows) => {
if (err) {
httpError(res, 500, 'Server Error', 'Could not load waifu.');
return;
}
if (!rows || rows.length === 0) {
renderAdminPanel(req, res, adminUser, 'No waifu found for ID ' + waifuID + '.', null, null);
return;
}
renderAdminPanel(req, res, adminUser, 'Loaded waifu #' + waifuID + ' for editing.', rows[0], null);
});
});
}
function adminSearchWaifus(req, res, query) {
requireAdminJWT(req, res, () => {
let searchTerm = String(query.q || '').trim();
let seriesTerm = String(query.series || '').trim();
let limit = Math.max(1, Math.min(100, parseInt(query.limit || 25, 10) || 25));
let whereParts = [];
let values = [];
if (searchTerm) {
whereParts.push('(name LIKE ? OR series LIKE ?)');
values.push('%' + searchTerm + '%', '%' + searchTerm + '%');
}
if (seriesTerm) {
whereParts.push('series LIKE ?');
values.push('%' + seriesTerm + '%');
}
let whereClause = whereParts.length ? ('WHERE ' + whereParts.join(' AND ')) : '';
values.push(limit);
con.query('SELECT id, name, series, base_rarity FROM waifus ' + whereClause + ' ORDER BY name ASC, id ASC LIMIT ?', values, (err, rows) => {
if (err) {
console.error('[admin-waifu] Could not search waifus:', err);
httpError(res, 500, 'Server Error', 'Could not search waifus.');
return;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
waifus: (rows || []).map((row) => ({
id: row.id,
name: row.name,
series: row.series,
baseRarity: row.base_rarity
}))
}));
});
});
}
function adminUpdateWaifu(req, res) {
requireAdminJWT(req, res, () => {
parseRequestBody(req, (body) => {
let form = querystring.parse(body);
let waifuID = parseInt(form.waifuId, 10);
if (!waifuID || !form.name || !form.series || !form.image) {
httpError(res, 400, 'Bad Request', 'Missing required waifu fields');
return;
}
con.query('UPDATE waifus SET name = ?, series = ?, image = ?, base_rarity = ?, normal_weighting = ?, event_weighting = ? WHERE id = ?', [form.name, form.series, form.image, parseInt(form.baseRarity || 0, 10), parseFloat(form.normalWeighting || 1), parseFloat(form.eventWeighting || 1), waifuID], (err) => {
if (err) {
httpError(res, 500, 'Server Error', 'Could not update waifu.');
return;
}
res.writeHead(302, {'Location': '/admin'});
res.end();
});
});
});
}
function adminAddWaifu(req, res) {
requireAdminJWT(req, res, () => {
parseRequestBody(req, (body) => {
let form = querystring.parse(body);
if (!form.name || !form.series || !form.image) {
httpError(res, 400, 'Bad Request', 'Missing required waifu fields');
return;
}
con.query('INSERT INTO waifus(name, series, image, base_rarity, normal_weighting, event_weighting) VALUES (?, ?, ?, ?, ?, ?)', [form.name, form.series, form.image, parseInt(form.baseRarity || 0, 10), parseFloat(form.normalWeighting || 1), parseFloat(form.eventWeighting || 1)], (err) => {
if (err) {
httpError(res, 500, 'Server Error', 'Could not add waifu.');
return;
}
res.writeHead(302, {'Location': '/admin'});
res.end();
});
});
});
}
function adminUpdateBooster(req, res) {
requireAdminJWT(req, res, (adminUser) => {
parseRequestBody(req, (body) => {
let form = querystring.parse(body);
let booster = parseBoosterForm(form);
console.log('[admin-booster] Save request received.', {
admin: adminUser && adminUser.login ? adminUser.login : 'unknown',
boosterName: booster.name,
listed: booster.listed,
buyable: booster.buyable,
numCards: booster.numCards,
rarityColumnsConfigured: getBoosterUpgradeColumns().length
});
if (!booster.name) {
console.warn('[admin-booster] Save aborted due to missing booster name.');
httpError(res, 400, 'Bad Request', 'Missing booster name');
return;
}
let rarityColumns = getBoosterUpgradeColumns();
let fields = ['name', 'sortIndex', 'listed', 'buyable', 'cost', 'numCards', 'guaranteeRarity', 'guaranteeCount', 'useEventWeightings', 'maxEventTokens', 'eventTokenChance', 'canMega', 'applyScaling'].concat(rarityColumns);
let placeholders = fields.map(() => '?').join(', ');
let values = [booster.name, booster.sortIndex, booster.listed, booster.buyable, booster.cost, booster.numCards, booster.guaranteeRarity, booster.guaranteeCount, booster.useEventWeightings, booster.maxEventTokens, booster.eventTokenChance, booster.canMega, booster.applyScaling];
for (let column of rarityColumns) {
values.push(booster.rarityChances[column]);
}
let updateParts = fields.filter((field) => field !== 'name').map((field) => field + ' = VALUES(' + field + ')').join(', ');
let sql = 'INSERT INTO boosters(' + fields.join(', ') + ') VALUES (' + placeholders + ') ON DUPLICATE KEY UPDATE ' + updateParts;
con.query(sql, values, (err) => {
if (err) {
console.error('[admin-booster] Save failed.', {
boosterName: booster.name,
fieldCount: fields.length,
rarityColumnCount: rarityColumns.length,
errorCode: err.code,
errorNumber: err.errno,
sqlState: err.sqlState,
sqlMessage: err.sqlMessage || err.message
});
httpError(res, 500, 'Server Error', 'Could not save booster settings.');
return;
}
con.query('UPDATE boosters SET guaranteedRaritySlots = ? WHERE name = ?', [booster.guaranteedRaritySlots || null, booster.name], (allowedErr) => {
if (allowedErr) {
if (allowedErr.code === 'ER_BAD_FIELD_ERROR') {
console.warn('[admin-booster] guaranteedRaritySlots column not present. Skipping explicit rarity-set save.', {
boosterName: booster.name
});
} else {
console.error('[admin-booster] Save failed while writing guaranteedRaritySlots.', {
boosterName: booster.name,
errorCode: allowedErr.code,
errorNumber: allowedErr.errno,
sqlState: allowedErr.sqlState,
sqlMessage: allowedErr.sqlMessage || allowedErr.message
});
httpError(res, 500, 'Server Error', 'Could not save booster settings.');
return;
}
}
console.log('[admin-booster] Save successful.', {
boosterName: booster.name,
admin: adminUser && adminUser.login ? adminUser.login : 'unknown',
guaranteedRaritySlotsConfigured: !!booster.guaranteedRaritySlots
});
res.writeHead(302, {'Location': '/admin'});
res.end();
});
});
});
});
}
function adminLoadBooster(req, res, query) {
requireAdminJWT(req, res, (adminUser) => {
let boosterName = String(query.name || '').trim();
if (!boosterName) {
console.warn('[admin-booster] Load aborted due to missing booster name.', {
admin: adminUser && adminUser.login ? adminUser.login : 'unknown'
});
renderAdminPanel(req, res, adminUser, 'Please provide a booster name to load.', null, null);
return;
}
console.log('[admin-booster] Load request received.', {
admin: adminUser && adminUser.login ? adminUser.login : 'unknown',
boosterName: boosterName
});
let rarityColumns = getBoosterUpgradeColumns();
let sql = 'SELECT name, sortIndex, listed, buyable, cost, numCards, guaranteeRarity, guaranteeCount, useEventWeightings, maxEventTokens, eventTokenChance, canMega, applyScaling' + (rarityColumns.length ? ', ' + rarityColumns.join(', ') : '') + ' FROM boosters WHERE name = ? LIMIT 1';
con.query(sql, [boosterName], (err, rows) => {
if (err) {
console.error('[admin-booster] Load failed.', {
boosterName: boosterName,
errorCode: err.code,
errorNumber: err.errno,
sqlState: err.sqlState,
sqlMessage: err.sqlMessage || err.message
});
httpError(res, 500, 'Server Error', 'Could not load booster.');
return;
}
if (!rows || rows.length === 0) {
console.warn('[admin-booster] Load found no booster.', {
boosterName: boosterName
});
renderAdminPanel(req, res, adminUser, 'No booster found for name "' + boosterName + '".', null, null);
return;
}
let row = rows[0];
let boosterForm = {
name: row.name,
sortIndex: row.sortIndex,
listed: row.listed,
buyable: row.buyable,
cost: row.cost,
numCards: row.numCards,
guaranteeRarity: row.guaranteeRarity,
guaranteeCount: row.guaranteeCount,
useEventWeightings: row.useEventWeightings,
maxEventTokens: row.maxEventTokens,
eventTokenChance: row.eventTokenChance,
canMega: row.canMega,
applyScaling: row.applyScaling,
guaranteedRaritySlots: '',
rarityChances: {}
};
for (let column of rarityColumns) {
boosterForm.rarityChances[column] = row[column];
}
con.query('SELECT guaranteedRaritySlots FROM boosters WHERE name = ? LIMIT 1', [boosterName], (allowedErr, allowedRows) => {
if (allowedErr) {
if (allowedErr.code === 'ER_BAD_FIELD_ERROR') {
console.warn('[admin-booster] guaranteedRaritySlots column not present. Skipping explicit rarity-set load.', {
boosterName: boosterName
});
} else {
console.error('[admin-booster] Could not load guaranteedRaritySlots column.', {
boosterName: boosterName,
errorCode: allowedErr.code,
errorNumber: allowedErr.errno,
sqlState: allowedErr.sqlState,
sqlMessage: allowedErr.sqlMessage || allowedErr.message
});
}
} else if (allowedRows && allowedRows.length > 0) {
boosterForm.guaranteedRaritySlots = allowedRows[0].guaranteedRaritySlots || '';
}
console.log('[admin-booster] Load successful.', {
boosterName: boosterName,
rarityColumnCount: rarityColumns.length,
guaranteedRaritySlotsConfigured: !!boosterForm.guaranteedRaritySlots
});
renderAdminPanel(req, res, adminUser, 'Loaded booster "' + boosterName + '" for editing.', null, boosterForm);
});
});
});
}
function adminGetListedBoosters(req, res) {
requireAdminJWT(req, res, () => {
con.query('SELECT name FROM boosters WHERE listed = 1 ORDER BY sortIndex ASC, name ASC', (err, rows) => {
if (err) {
console.error('[admin-event-close] Could not load listed boosters:', err);
httpError(res, 500, 'Server Error', 'Could not load listed boosters.');
return;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({boosters: rows.map((row) => row.name)}));
});
});
}
function adminGetBoosters(req, res) {
requireAdminJWT(req, res, () => {
con.query('SELECT name, listed, buyable FROM boosters ORDER BY sortIndex ASC, name ASC', (err, rows) => {
if (err) {
console.error('[admin-booster] Could not load booster list:', err);
httpError(res, 500, 'Server Error', 'Could not load boosters.');
return;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
boosters: (rows || []).map((row) => ({
name: row.name,
listed: !!row.listed,
buyable: !!row.buyable
}))
}));
});
});
}
function triggerPythonBotReload(callback) {
childProcess.execFile('pkill', ['-USR1', '-f', 'main.py'], (err, stdout, stderr) => {
if (err) {
callback(err);
return;
}
callback(null, {
stdout: stdout,
stderr: stderr
});
});
}
function adminCloseEvent(req, res) {
requireAdminJWT(req, res, (adminUser) => {
parseRequestBody(req, (body) => {
let form = querystring.parse(body);
let boosterName = String(form.boosterName || '').trim();
let allowPromotedCopies = form.allowPromotedCopies === '1';
if (!boosterName) {
httpError(res, 400, 'Bad Request', 'Missing boosterName.');
return;
}
console.log('[admin-event-close] Request received.', {
admin: adminUser && adminUser.login ? adminUser.login : 'unknown',
boosterName: boosterName,
allowPromotedCopies: allowPromotedCopies
});
con.query('SELECT id, name FROM waifus WHERE is_event = 1 AND rarity = ? LIMIT 1', ['promoted'], (promotedErr, promotedRows) => {
if (promotedErr) {
console.error('[admin-event-close] Could not inspect promoted event waifus:', promotedErr);
httpError(res, 500, 'Server Error', 'Could not inspect event waifu rarity state.');
return;
}
if (promotedRows && promotedRows.length > 0 && !allowPromotedCopies) {
res.writeHead(409, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
requiresConfirmation: true,
message: 'Some event waifus are already promoted. Confirm to continue anyway.',
sampleWaifuId: promotedRows[0].id,
sampleWaifuName: promotedRows[0].name
}));
return;
}
con.beginTransaction((txErr) => {
if (txErr) {
console.error('[admin-event-close] Could not start transaction:', txErr);
httpError(res, 500, 'Server Error', 'Could not start update transaction.');
return;
}
con.query('UPDATE waifus SET rarity = ? WHERE is_event = 1', ['promo'], (waifuErr, waifuResult) => {
if (waifuErr) {
return con.rollback(() => {
console.error('[admin-event-close] Could not update event waifus:', waifuErr);
httpError(res, 500, 'Server Error', 'Could not update event waifus.');
});
}
con.query('UPDATE boosters SET listed = 0, buyable = 0 WHERE name = ? LIMIT 1', [boosterName], (boosterErr, boosterResult) => {
if (boosterErr) {
return con.rollback(() => {
console.error('[admin-event-close] Could not update booster listing state:', boosterErr);
httpError(res, 500, 'Server Error', 'Could not update booster listing state.');
});
}
if (!boosterResult || boosterResult.affectedRows < 1) {
return con.rollback(() => {
httpError(res, 404, 'Not Found', 'Selected booster not found.');
});
}
con.commit((commitErr) => {
if (commitErr) {
return con.rollback(() => {
console.error('[admin-event-close] Could not commit updates:', commitErr);
httpError(res, 500, 'Server Error', 'Could not commit event close updates.');
});
}
triggerPythonBotReload((reloadErr) => {
if (reloadErr) {
console.error('[admin-event-close] Data updates succeeded, but bot reload trigger failed:', reloadErr);
httpError(res, 500, 'Server Error', 'Event updates were applied, but bot reload trigger failed.');
return;
}
console.log('[admin-event-close] Completed successfully.', {
admin: adminUser && adminUser.login ? adminUser.login : 'unknown',
boosterName: boosterName,
waifusUpdated: waifuResult && typeof waifuResult.affectedRows === 'number' ? waifuResult.affectedRows : null
});
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
ok: true,
message: 'Event waifus switched to promo, booster hidden/unbuyable, and bot reload triggered.'
}));
});
});
});
});
});
});
});
});
}
let rarities = {
0: "common",
1: "uncommon",
2: "rare",
3: "super",
4: "ultra",
5: "legendary",
6: "mythical",
7: "god",
8: "special",
9: "promo"
};
function getRarityName(number) {
if (number in rarities) {
return rarities[number];
} else {
return "unknown";
}
}
function hand(req, res, query) {
if (!('user' in query)) {
httpError(res, 400, "Missing Parameter");
return;
}
con.query("SELECT waifus.*, c1.rarity, c1.customImage, c1.id as cardid, c1.tradeableAt, c1.created, " +
"IF(c1.rarity = 7 AND NOT EXISTS(SELECT id FROM cards c2 WHERE c2.userid IS NOT NULL AND c2.rarity = 7 AND c2.waifuid = c1.waifuid AND (c2.created < c1.created OR (c2.created=c1.created AND c2.id < c1.id))), 1, 0) AS firstGod FROM waifus JOIN cards c1 ON waifus.id = c1.waifuid JOIN users ON " +
"c1.userid = users.id WHERE users.name = ? AND c1.boosterid IS NULL ORDER BY COALESCE(c1.sortValue, 32000) ASC, (c1.rarity < 8) DESC, waifus.id ASC, c1.rarity ASC, c1.id ASC", query.user, function (err, result) {
if (err) throw err;
let wantJSON = false;
if ("accept" in req.headers && req.headers["accept"] === "application/json") {
wantJSON = true;
}
if (result.length === 0) {
if (wantJSON) {
res.writeHead(404, "Not Found", {'Content-Type': 'application/json; charset=utf-8'});
res.write(JSON.stringify({"error": {"status": 404, "explanation": "User not found"}}));
res.end();
} else {
res.writeHead(404, "Not Found", {'Content-Type': 'text/html'});
renderTemplateAndEnd("templates/hand.ejs", {
user: query.user,
cards: [],
error: "404 - This user doesn't exist.",
eventTokens: 0
}, res);
}
return;
}
con.query("SELECT eventTokens FROM users WHERE users.name = ?", query.user, function (err, resultTokens) {
if (resultTokens.length === 0) {
if (wantJSON) {
res.writeHead(404, "Not Found", {'Content-Type': 'application/json; charset=utf-8'});
res.write(JSON.stringify({"error": {"status": 404, "explanation": "User not found"}}))
res.end();
} else {
res.writeHead(404, "Not Found", {'Content-Type': 'text/html'});
renderTemplateAndEnd("templates/hand.ejs", {
user: query.user,
cards: [],
error: "404 - This user doesn't exist.",
eventTokens: 0
}, res);
}
return;
}
if (wantJSON) {
let sanitizedResult = [];
for (let row of result) {
let obj = {
"id": row.id,
"Name": row.name,
"series": row.series,
"image": row.customImage || row.image,
"base_rarity": row.base_rarity,
"rarity": row.rarity,
"amount": 1,
"cardid": row.cardid,
"firstGod": row.firstGod,
};
sanitizedResult.push(obj);
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify({
'user': query.user,
"cards": sanitizedResult,
"eventTokens": resultTokens[0].eventTokens
}));
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
renderTemplateAndEnd("templates/hand.ejs", {
user: query.user,
cards: result,
error: "",
eventTokens: resultTokens[0].eventTokens
}, res);
}
});
});
}
function booster(req, res, query) {
if (!('user' in query)) {
httpError(res, 400, "Missing Parameter");
return;
}
let start = Date.now();
con.query("SELECT waifus.* FROM boosters_opened JOIN users ON boosters_opened.userid = users.id LEFT JOIN cards ON boosters_opened.id = cards.boosterid LEFT JOIN waifus ON cards.waifuid = waifus.id WHERE users.name = ? AND boosters_opened.status = 'open' ORDER BY waifus.id ASC", query.user, function (err, result) {
if (err) throw err;
let wantJSON = false;
if ("accept" in req.headers && req.headers["accept"] === "application/json") {
wantJSON = true;
}
if (result.length === 0) {
if (wantJSON) {
res.writeHead(404, "Not Found", {'Content-Type': 'application/json; charset=utf-8'});
res.write(JSON.stringify({
"error": {
"status": 404,
"explanation": "User not found or does not have an open booster."
}
}));
res.end();
} else {
res.writeHead(404, "Not Found", {'Content-Type': 'text/html'});
renderTemplateAndEnd("templates/booster.ejs", {
user: query.user,
cards: [],
error: "404 - This user doesn't exist or has no open booster.",
eventTokens: 0
}, res);
}
return;
}
con.query("SELECT boosters_opened.eventTokens FROM boosters_opened JOIN users ON boosters_opened.userid = users.id WHERE users.name = ? AND boosters_opened.status = 'open'", query.user, function (err, resultTokens) {
if (resultTokens.length === 0) {
if (wantJSON) {
res.writeHead(404, "Not Found", {'Content-Type': 'application/json; charset=utf-8'});
res.write(JSON.stringify({
"error": {
"status": 404,
"explanation": "User not found or does not have an open booster."
}
}));
res.end();
} else {
res.writeHead(404, "Not Found", {'Content-Type': 'text/html'});
renderTemplateAndEnd("templates/booster.ejs", {
user: query.user,
cards: [],
error: "404 - This user doesn't exist or has no open booster.",
eventTokens: 0
}, res);
}
return;
}
if (wantJSON) {
res.writeHead(200, {'Content-Type': 'application/json'});
let sanitizedResult = [];
for (let row of result) {
let obj = {};
obj.id = row.id;
obj.name = row.name;
obj.image = row.image;