-
Notifications
You must be signed in to change notification settings - Fork 0
/
pissarra-backend.js
1811 lines (1495 loc) · 72.8 KB
/
pissarra-backend.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
// Now everything related to loading positions/JSONs is here
// And it can change fully without affecting the other parts
/*
Mètodes a gestionar:
.new_connection
.load_json
.load_positions
.import
.save_change
*/
const calculateProvesDates = (order, durations, horaInici) => {
const DEFAULT_DURATION = 10;
// const knownProves = order
// .filter(fullName => (fullName?.split('.')?.[0] || '') in durations)
const provesDurations = order
.map(fullName => durations[(fullName?.split('.')?.[0] || '')] || DEFAULT_DURATION)
const compoundDurations = (hora => duration =>
[
hora.toDate(),
hora.add(duration, 'minutes').toDate()
]
)(horaInici.clone())
const compoundedHores = provesDurations
.map(compoundDurations)
const horesStructured = compoundedHores
.map(([start, end], i) => ({
'prova': order[i],
'start': start,
'end': end,
}))
return horesStructured;
}
const formatDurations = data => {
let dict = {}
const canvis = data.split('\n')
for (const canvi of canvis) {
if (canvi.split('=').length !== 2) continue
const [prova, duration] = canvi.split('=')
dict[prova] = parseInt(duration)
}
return dict;
}
const formatLastLine = data => {
const lastLine = data
.split('\n')
.filter(line => line !== '')
.at(-1) || '[]'
return JSON.parse(lastLine);
}
const leaveAllRooms = socket => {
const rooms = [...socket.rooms].filter(room => room !== socket.id);
rooms.forEach(room => socket.leave(room));
};
function appendNewlineIfNeeded(fs, filePath, callback) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) throw err;
// Check if the content ends with a newline
if (data?.length > 0 && data[data.length - 1] !== '\n') {
fs.appendFile(filePath, '\n', callback);
} else {
callback();
}
});
}
// This function wraps the logic you provided, but ensures a newline exists at the end of the file before appending the new data
function appendToFileEnsuringNewline(fs, filePath, content, callback) {
appendNewlineIfNeeded(fs, filePath, () => {
fs.appendFile(filePath, content + '\n', callback);
});
}
const getAddonsFromId = (fs, bundleId) => {
const addonsFilename = `${__dirname}/data/bundles/addons/${bundleId}.json`
const addonsFile = fs.existsSync(addonsFilename) ? fs.readFileSync(addonsFilename) : null
if (!addonsFile) return false
return JSON.parse(addonsFile)
}
const get_available_imports = (socket, fs, selectedEvent, selectedBundle, selectedVersio) => {
const eventsDirs = fs.readdirSync(`${__dirname}/events/`);
const path = require('node:path');
const castellsInEvents = eventsDirs.map(event => {
const posicionsDir = path.join(`${__dirname}/events/`, event, 'posicions');
const castellsInEvent = fs.existsSync(posicionsDir) ? fs.readdirSync(posicionsDir) : [];
const hiddenPosicionsDir = path.join(`${__dirname}/events/`, event, 'posicions/hidden');
const hiddenCastellsInEvent = fs.existsSync(hiddenPosicionsDir) ? fs.readdirSync(hiddenPosicionsDir) : [];
const adminPosicionsDir = path.join(`${__dirname}/events/`, event, 'posicions/admin');
const adminCastellsInEvent = fs.existsSync(adminPosicionsDir) ? fs.readdirSync(adminPosicionsDir) : [];
return [...castellsInEvent, ...hiddenCastellsInEvent, ...adminCastellsInEvent]
.filter(c => c.split('.').length > 2)
// .filter(c => c.split('.')[0] === selectedBundle)
.filter(c => event !== selectedEvent || c.split('.')[1] !== selectedVersio);
});
const posicionsLogOfCastell = castellsInEvents
.map((castells, i) => castells.map(fullname => {
const [castell, versio, _] = fullname.split('.');
const posicionsLogPath = `${__dirname}/events/${eventsDirs[i]}/posicions/${castell}.${versio}.canvis`;
const hiddenPosicionsLogPath = `${__dirname}/events/${eventsDirs[i]}/posicions/hidden/${castell}.${versio}.canvis`;
const adminPosicionsLogPath = `${__dirname}/events/${eventsDirs[i]}/posicions/admin/${castell}.${versio}.canvis`;
if (fs.existsSync(posicionsLogPath)) {
return fs.readFileSync(posicionsLogPath).toString();
} else if (fs.existsSync(hiddenPosicionsLogPath)) {
return fs.readFileSync(hiddenPosicionsLogPath).toString();
} else if (fs.existsSync(adminPosicionsLogPath)) {
return fs.readFileSync(adminPosicionsLogPath).toString();
} else {
return '';
}
}));
socket.emit('.available_imports', {
'events': eventsDirs,
'castells': castellsInEvents,
'posicionsLog': posicionsLogOfCastell,
});
};
module.exports.build = (app, io, fs, emit_query, execute_query) => {
const moment = require('moment');
const path = require('node:path');
const crypto = require('crypto');
const { fdir } = require("fdir");
const cron = require('node-cron');
const AWS = require('aws-sdk');
const accessKeys = require('./aws.credentials.json');
const credentials = JSON.parse(fs.readFileSync('../db.credentials.json'));
const colla = credentials.colla;
const s3 = new AWS.S3({
accessKeyId: accessKeys.accessKeyId,
secretAccessKey: accessKeys.secretAccessKey,
region: accessKeys.region,
});
const isBackupNeeded = {};
const get_future_nearby_events = (hours=48) => `select id from events WHERE \`data-esperada-inici\` >= NOW() AND \`data-esperada-inici\` <= DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`;
// Function to perform the backup
const performPositionsBackup = () => {
// Fetch events happening in the next 48 hours
execute_query(get_future_nearby_events(), data => {
// For each event, backup the positions
data.forEach(event => backupPositionsEvent(event.id.toString()));
});
};
const backupIfNeeded = () => {
Object.keys(isBackupNeeded).forEach(event => {
Object.keys(isBackupNeeded[event]).forEach(castellVersio => {
if (isBackupNeeded[event][castellVersio]) {
const [castell, versio] = castellVersio.split('.');
backupPositionsProva(event, castell, versio);
delete isBackupNeeded[event][castellVersio];
}
});
});
};
const backupPositionsProva = (event, castell, versio) => {
const pinyaPath = `${__dirname}/events/${event}/posicions/${castell}.${versio}.canvis`
const hiddenPinyaPath = `${__dirname}/events/${event}/posicions/hidden/${castell}.${versio}.canvis`
const adminPinyaPath = `${__dirname}/events/${event}/posicions/admin/${castell}.${versio}.canvis`
const matchedPath =
fs.existsSync(pinyaPath) ? pinyaPath :
fs.existsSync(hiddenPinyaPath) ? hiddenPinyaPath :
fs.existsSync(adminPinyaPath) ? adminPinyaPath :
'';
if (!matchedPath) return;
const params = {
Bucket: 'aleta-' + colla,
Key: `positions/${event}/${castell}.${versio}.canvis`,
Body: fs.createReadStream(matchedPath)
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack);
// else console.log(`Periodic backup of ${castell}.${versio}.canvis saved to S3`);
});
}
const backupPositionsEvent = (event) => {
const eventDir = path.join(__dirname, 'events', event);
const walkDir = (currentPath) => {
const files = fs.readdirSync(currentPath);
for (const file of files) {
if (file.includes("order")) continue;
const curFile = path.join(currentPath, file);
if (fs.statSync(curFile).isFile() && path.extname(curFile) === '.canvis') {
const params = {
Bucket: 'aleta-' + colla,
Key: `positions/${event}/${file}`,
Body: fs.createReadStream(curFile)
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack);
// else console.log(`Periodic backup of ${file} saved to S3`);
});
} else if (fs.statSync(curFile).isDirectory()) {
walkDir(curFile);
}
}
};
walkDir(eventDir);
};
// Schedule the backup function if needed
cron.schedule('* * * * *', backupIfNeeded);
const save_change = (fs, room, io, socket, pos, action_id) => {
if (room.split('.').length < 3) return;
// Evita que es pugui guardar una posició amb caixa -1
if (pos.split(',').length >= 2) {
const [caixa, ...rest] = pos.split(',')
if (parseInt(caixa) === -1) return;
}
const actionId = action_id || Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
const withAddons = pos
.split(',')
.concat(socket?.userId || 'anonymous')
.concat(new Date().toISOString())
.concat(actionId)
.join(',')
const [event, castell, versio] = room.split('.');
const pinyaPath = `${__dirname}/events/${event}/posicions/${castell}.${versio}.canvis`
const hiddenPinyaPath = `${__dirname}/events/${event}/posicions/hidden/${castell}.${versio}.canvis`
const adminPinyaPath = `${__dirname}/events/${event}/posicions/admin/${castell}.${versio}.canvis`
if (fs.existsSync(pinyaPath)) appendToFileEnsuringNewline(fs, pinyaPath, withAddons, () => io.to(room).emit(`.new_change`, withAddons));
else if (fs.existsSync(hiddenPinyaPath)) appendToFileEnsuringNewline(fs, hiddenPinyaPath, withAddons, () => io.to(room).emit(`.new_change`, withAddons));
else if (fs.existsSync(adminPinyaPath)) appendToFileEnsuringNewline(fs, adminPinyaPath, withAddons, () => io.to(room).emit(`.new_change`, withAddons));
// Create a backup in S3 of the changed .canvis file
const backupPath =
fs.existsSync(pinyaPath) ? pinyaPath :
fs.existsSync(hiddenPinyaPath) ? hiddenPinyaPath :
fs.existsSync(adminPinyaPath) ? adminPinyaPath :
'';
if (!backupPath) return;
// const params = {
// Bucket: 'aleta-' + colla,
// Key: `positions/${event}/${castell}.${versio}.canvis`,
// Body: fs.createReadStream(backupPath)
// };
// s3.putObject(params, function(err, data) {
// if (err) console.log(err, err.stack); // an error occurred
// // else console.log(data); // successful response
// else console.log(`Backup of ${castell}.${versio}.canvis saved to S3`)
// });
// Mark the event as needing a backup
if (!(event in isBackupNeeded)) isBackupNeeded[event] = {};
isBackupNeeded[event][`${castell}.${versio}`] = true;
io.emit(`.posicions_changed`, event, castell, versio, withAddons);
};
const get_sockets_in_room = (room) => {
const sockets = io.sockets.adapter.rooms.get(room);
if (!sockets) return [];
return [...sockets].map(id => io.sockets.sockets.get(id));
}
const change_first_line = (filePath, newFirstLine, callback) => {
const lines = fs.readFileSync(filePath).toString().split('\n')
const newContent = (lines.length > 0 ? [newFirstLine, ...lines.slice(1)] : [newFirstLine]).join('\n')
fs.writeFile(filePath, newContent, (err) => callback(err))
};
const get_first_line = (filePath) => {
const lines = fs.readFileSync(filePath).toString().split('\n');
if (lines.length > 0) {
return lines[0];
} else {
return false;
}
};
const get_last_line = (filePath, user) => {
const lines = fs
.readFileSync(filePath)
.toString()
.split('\n')
.filter(line => line !== '');
const onlyUserLines = lines
.filter(line => user ? parseInt(line.split(',')?.[2]) === parseInt(user) : true)
if (onlyUserLines.length > 0) {
return onlyUserLines[onlyUserLines.length - 1];
} else {
return false;
}
}
const undo_action = (filePath, action_id, callback) => {
const lines = fs.readFileSync(filePath)
.toString()
.split('\n')
.filter(line => line !== '')
if (action_id) {
const action_lines = lines
.map((line, i) => [line, i])
.filter(([line, i]) => line.split(',').includes(action_id))
.map(([line, i]) => i)
// Pop actionIndex from lines
const newLines = lines.filter((line, i) => !action_lines.includes(i))
const newContent = newLines.join('\n');
fs.writeFile(filePath, newContent, (err) => callback(err))
} else {
// Pop last line from lines
const newLines = lines.slice(0, -1)
const newContent = newLines.join('\n');
fs.writeFile(filePath, newContent, (err) => callback(err))
}
}
const undo = (event, castell, versio, io, socket) => {
const pinyaPath = `${__dirname}/events/${event}/posicions/${castell}.${versio}.canvis`
const hiddenPinyaPath = `${__dirname}/events/${event}/posicions/hidden/${castell}.${versio}.canvis`
const adminPinyaPath = `${__dirname}/events/${event}/posicions/admin/${castell}.${versio}.canvis`
if (fs.existsSync(pinyaPath) || fs.existsSync(hiddenPinyaPath) || fs.existsSync(adminPinyaPath)) {
const matchedPath =
fs.existsSync(pinyaPath) ? pinyaPath :
fs.existsSync(hiddenPinyaPath) ? hiddenPinyaPath :
fs.existsSync(adminPinyaPath) ? adminPinyaPath :
'';
if (!matchedPath) return;
const lastLine = get_last_line(matchedPath, socket?.userId);
if (!lastLine) return;
const action_id = lastLine.split(',')?.[4] || false
undo_action(matchedPath, action_id, (err) => {
if (err) {
console.log(err);
return;
}
io.to(`${event}.${castell}.${versio}`).emit(`.undid_action`, action_id);
})
}
}
const change_option = (filePath, option, value, callback) => {
const first_line = get_first_line(filePath);
if (first_line) {
const options = first_line
.replace('OPTIONS:', '')
.split(',')
.map(str => str.split('='));
const newOptions = options
.map(([key, val]) => key === option ? [key, value] : [key, val])
.map(([key, val]) => `${key}=${val}`)
.join(',');
change_first_line(filePath, `OPTIONS:${newOptions}`, callback);
} else {
change_first_line(filePath, `OPTIONS:${option}=${value}`, callback);
}
};
const rotate_ajuntament = (room, io, val) => {
if (room.split('.').length < 3) return;
const [event, castell, versio] = room.split('.');
const pinyaPath = `${__dirname}/events/${event}/posicions/${castell}.${versio}.canvis`
const hiddenPinyaPath = `${__dirname}/events/${event}/posicions/hidden/${castell}.${versio}.canvis`
const adminPinyaPath = `${__dirname}/events/${event}/posicions/admin/${castell}.${versio}.canvis`
const ajuntamentRotation = isNaN(val) || (0 <= val && val < 4) ? parseInt(val) : 0
if (fs.existsSync(pinyaPath) || fs.existsSync(hiddenPinyaPath) || fs.existsSync(adminPinyaPath)) {
const matchedPath =
fs.existsSync(pinyaPath) ? pinyaPath :
fs.existsSync(hiddenPinyaPath) ? hiddenPinyaPath :
fs.existsSync(adminPinyaPath) ? adminPinyaPath :
'';
change_option(
matchedPath,
'ajuntament',
ajuntamentRotation,
() => io.to(room).emit(`.ajuntament_rotated`, ajuntamentRotation)
)
}
}
const getBundleFromId = id => {
const bundlePath = `${__dirname}/data/bundles/${id}.json`;
const bundleExists = fs.existsSync(bundlePath);
if (bundleExists) {
const fetchedJSON = JSON.parse(fs.readFileSync(bundlePath))
fetchedJSON.id = id;
return fetchedJSON;
} else {
return null;
}
}
const uploadProvesToS3 = (event) => {
const public_path = `${__dirname}/events/${event}/posicions`;
if (!fs.existsSync(public_path)) fs.mkdirSync(public_path, { recursive: true });
const private_path = `${__dirname}/events/${event}/posicions/hidden`;
if (!fs.existsSync(private_path)) fs.mkdirSync(private_path, { recursive: true });
const admin_path = `${__dirname}/events/${event}/posicions/admin`;
if (!fs.existsSync(admin_path)) fs.mkdirSync(admin_path, { recursive: true });
const public_crawler = new fdir().withMaxDepth(0).crawl(public_path);
const private_crawler = new fdir().withMaxDepth(0).crawl(private_path);
const admin_crawler = new fdir().withMaxDepth(0).crawl(admin_path);
// Asynchronously - slow process. No need to block thread
public_crawler.withPromise().then(public_files => {
private_crawler.withPromise().then(private_files => {
admin_crawler.withPromise().then(admin_files => {
const public_proves = public_files.map(f => f.split('/').at(-1)).filter(file => file.includes('.canvis'));
const private_proves = private_files.map(f => f.split('/').at(-1)).filter(file => file.includes('.canvis'));
const admin_proves = admin_files.map(f => f.split('/').at(-1)).filter(file => file.includes('.canvis'));
const content = { 'event': event, 'public': public_proves, 'private': private_proves, 'admin': admin_proves };
// Save to S3
const params = {
Bucket: 'aleta-' + colla,
Key: `proves/${event}.json`,
Body: JSON.stringify(content)
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else console.log(data); // successful response
});
});
});
});
}
function authenticateAPIKey(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (!apiKey) return res.status(401).send('API Key missing');
// Check the database or your store to see if this is a valid key
const validKeys = fs.readFileSync('./api-keys.txt', 'utf8')
.split('\n')
.filter(key => key.length > 0)
.filter(key => !key.startsWith('#'))
const isValidKey = validKeys.includes(apiKey);
if (!isValidKey) return res.status(403).send('Invalid API Key');
next();
}
app.get('/api/proves/:event', authenticateAPIKey, (req, res) => {
const event = req.params.event;
const params = {
Bucket: 'aleta-' + colla,
Key: `proves/${event}.json`
};
s3.getObject(params, (err, data) => {
const jsonData = data ? (JSON.parse(data?.Body?.toString()) || {}) : {};
const isGood = 'event' in jsonData && 'public' in jsonData && 'private' in jsonData && 'admin' in jsonData;
if (err || !isGood) {
if (err?.statusCode !== 404) console.log(err, err.stack);
readFromDisk(true);
} else {
res.json(jsonData)
}
});
function readFromDisk(uploadToS3=false) {
const public_path = `${__dirname}/events/${event}/posicions`;
if (!fs.existsSync(public_path)) fs.mkdirSync(public_path, { recursive: true });
const private_path = `${__dirname}/events/${event}/posicions/hidden`;
if (!fs.existsSync(private_path)) fs.mkdirSync(private_path, { recursive: true });
const admin_path = `${__dirname}/events/${event}/posicions/admin`;
if (!fs.existsSync(admin_path)) fs.mkdirSync(admin_path, { recursive: true });
const public_crawler = new fdir().withMaxDepth(0).crawl(public_path);
const private_crawler = new fdir().withMaxDepth(0).crawl(private_path);
const admin_crawler = new fdir().withMaxDepth(0).crawl(admin_path);
// Asynchronously - slow process. No need to block thread
public_crawler.withPromise().then(public_files => {
private_crawler.withPromise().then(private_files => {
admin_crawler.withPromise().then(admin_files => {
const public_proves = public_files.map(f => f.split('/').at(-1)).filter(file => file.includes('.canvis'));
const private_proves = private_files.map(f => f.split('/').at(-1)).filter(file => file.includes('.canvis'));
const admin_proves = admin_files.map(f => f.split('/').at(-1)).filter(file => file.includes('.canvis'));
const content = { 'event': event, 'public': public_proves, 'private': private_proves, 'admin': admin_proves };
res.json(content);
if (uploadToS3) {
// Save to S3
const params = {
Bucket: 'aleta-' + colla,
Key: `proves/${event}.json`,
Body: JSON.stringify(content)
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else console.log(data); // successful response
});
}
});
});
});
}
});
const uploadHoraIniciToS3 = (event, date) => {
const params = {
Bucket: 'aleta-' + colla,
Key: `horainici/${event}.date`,
Body: date
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else console.log(data); // successful response
});
}
io.on('connection', socket => {
socket.emit('.new_connection', socket.id);
socket.on('.associate_user', userId => {
socket.userId = userId;
})
// Torna quines plantilles existeixen com a llista
socket.on('.request_plantilles', () => {
const plantillesPath = `${__dirname}/data/plantilles/`;
const plantilles = fs.readdirSync(plantillesPath)
.filter(file => file.includes('.json'))
.map(file => file.replace('.json', ''))
socket.emit('.plantilles', plantilles);
});
socket.on('.request_bundles', (selected=null) => {
const bundlesPath = `${__dirname}/data/bundles/`;
const bundles = fs.readdirSync(bundlesPath)
.filter(file => file.includes('.json'))
.map(file => file.replace('.json', ''))
.filter(id => selected === null || selected.includes(id))
.map(id => getBundleFromId(id))
if (selected !== null) {
bundles.sort((a, b) => {
const aIndex = selected.indexOf(a.id)
const bIndex = selected.indexOf(b.id)
return aIndex > bIndex ? 1 : -1
})
}
socket.emit('.bundles', bundles);
});
app.get('/api/bundles', (req, res) => {
const bundlesPath = `${__dirname}/data/bundles/`;
const bundles = fs.readdirSync(bundlesPath)
.filter(file => file.includes('.json'))
.map(file => file.replace('.json', ''))
.map(id => getBundleFromId(id))
res.json(bundles)
})
socket.on('.request_horainici', (event, defaultHoraInici) => {
const event_path = `${__dirname}/events/${event}`;
const horaIniciFile = `${event_path}/horaIniciProves.date`;
if (!fs.existsSync(horaIniciFile)) {
fs.writeFileSync(
horaIniciFile,
defaultHoraInici
)
}
fs.readFile(
horaIniciFile,
(err, data) => socket.emit(`.horainici`, event, data.toString())
)
})
app.get('/api/horainici/:event', (req, res) => {
const event = req.params.event;
const params = {
Bucket: 'aleta-' + colla,
Key: `horainici/${event}.date`
};
s3.getObject(params, (err, data) => {
const parsedData = data ? (data?.Body?.toString() || '') : '';
const isGood = parsedData !== '';
if (err || !isGood) {
if (err?.statusCode !== 404) console.log(err, err.stack);
readFromDisk(true);
} else {
res.json(parsedData)
}
});
function readFromDisk(uploadToS3=false) {
const event_path = `${__dirname}/events/${req.params.event}`;
const horaIniciFile = `${event_path}/horaIniciProves.date`;
if (!fs.existsSync(horaIniciFile)) {
return res.json('');
}
fs.readFile(
horaIniciFile,
(err, data) => {
if (err) {
return res.status(500).json(null);
}
res.json(data.toString());
}
)
if (uploadToS3) {
const params = {
Bucket: 'aleta-' + colla,
Key: `horainici/${event}.date`,
Body: fs.readFileSync(horaIniciFile)
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else console.log(data); // successful response
});
}
}
});
socket.on('.save_horainici', (event, date) => {
const event_path = `${__dirname}/events/${event}`;
const horaIniciFile = `${event_path}/horaIniciProves.date`;
fs.writeFile(
horaIniciFile,
date,
(err, data) => io.emit(`.horainici`, event, date)
)
uploadHoraIniciToS3(event, date)
})
// Dona les duracions de cada prova
socket.on('.request_durations', () => {
const dataPath = `${__dirname}/data`;
const durationsFile = `${dataPath}/provesDurations.canvis`;
if (!fs.existsSync(durationsFile)) {
fs.writeFileSync(durationsFile, '')
}
fs.readFile(
durationsFile,
(err, data) => socket.emit(`.durations`, data.toString())
)
})
app.get('/api/durations', (req, res) => {
const params = {
Bucket: 'aleta-' + colla,
Key: `bundles_durations.json`
};
s3.getObject(params, (err, data) => {
const parsedData = data ? (data?.Body?.toString() || '') : '';
const isGood = parsedData !== '';
if (err || !isGood) {
if (err?.statusCode !== 404) console.log(err);
readFromDisk(true);
} else {
res.json(parsedData)
}
});
function readFromDisk(uploadToS3=false) {
const dataPath = `${__dirname}/data`;
const durationsFile = `${dataPath}/provesDurations.canvis`;
if (!fs.existsSync(durationsFile)) {
fs.writeFileSync(durationsFile, '')
}
try {
const data = fs.readFileSync(durationsFile);
res.json(data.toString());
if (uploadToS3) {
const params = {
Bucket: 'aleta-' + colla,
Key: `bundles_durations.json`,
Body: fs.readFileSync(durationsFile)
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else console.log(data); // successful response
});
}
} catch (err) {
res.json(null);
}
}
})
const uploadDurationsToS3 = (durationsData) => {
const params = {
Bucket: 'aleta-' + colla,
Key: `bundles_durations.json`,
Body: durationsData.toString()
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else console.log(data); // successful response
});
}
// Edita la duració d'una cada prova
socket.on('.edit_duration', (prova, duration) => {
const dataPath = `${__dirname}/data`;
const durationsFile = `${dataPath}/provesDurations.canvis`;
if (!fs.existsSync(durationsFile)) {
fs.writeFileSync(durationsFile, '')
}
fs.appendFileSync(
durationsFile,
`${prova}=${duration}\n`
);
socket.emit(`.durations_changed`, prova, duration);
uploadDurationsToS3(fs.readFileSync(durationsFile));
})
// Obtén les hores que es farà cada prova (en funció de (durations, horaInici, order))
socket.on('.request_hores_proves', eventId => {
const dataPath = `${__dirname}/data`;
const eventPath = `${__dirname}/events/${eventId}`;
const durationsFile = `${dataPath}/provesDurations.canvis`;
const horaIniciFile = `${eventPath}/horaIniciProves.date`;
const orderFile = `${eventPath}/proves.order.canvis`;
// Check existance
if (!fs.existsSync(durationsFile)) fs.writeFileSync(durationsFile, '{}');
if (!fs.existsSync(horaIniciFile)) fs.writeFileSync(horaIniciFile, '');
if (!fs.existsSync(orderFile)) fs.writeFileSync(orderFile, '');
// Read
const durationsData = fs.readFileSync(durationsFile).toString()
const horaIniciData = fs.readFileSync(horaIniciFile).toString()
const orderData = fs.readFileSync(orderFile).toString()
// Filter
const durations = formatDurations(durationsData)
const horaInici = moment(horaIniciData)
const order = formatLastLine(orderData)
// Calculate dates
const dates = calculateProvesDates(order, durations, horaInici)
io.emit('.hores_proves', eventId, dates)
})
// Carrega la plantilla del castell, si no existeix, envia error.
socket.on('.load_json', castell => {
const filename = `${__dirname}/data/plantilles/${castell}.json`;
if (fs.existsSync(filename)) {
const data = fs.readFileSync(filename);
socket.emit('.loaded_json', JSON.parse(data));
} else {
socket.emit('.loaded_json', 'ERROR:NOT_EXISTS');
}
});
socket.on('.duplicate_bundle', (bundleId, newAttrs) => {
const bundle = getBundleFromId(bundleId)
const newBundleId = crypto.randomBytes(5).toString('hex')
const bundlePath = `${__dirname}/data/bundles/${newBundleId}.json`;
const newBundle = {
...bundle,
...newAttrs,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
}
// Write bundle to file
fs.writeFileSync(bundlePath, JSON.stringify(newBundle))
// Also duplicate addons
const addonsFilename = `${__dirname}/data/bundles/addons/${bundleId}.json`
const addonsFile = fs.existsSync(addonsFilename) ? fs.readFileSync(addonsFilename) : null
if (addonsFile) {
const newAddonsFilename = `${__dirname}/data/bundles/addons/${newBundleId}.json`
fs.writeFileSync(newAddonsFilename, addonsFile)
}
io.emit('.bundle_duplicated', newBundleId)
})
socket.on('.create_bundle', ({ parts, simultani, bundles, ...other }) => {
const bundleId = crypto.randomBytes(5).toString('hex')
const bundlePath = `${__dirname}/data/bundles/${bundleId}.json`;
const partPath = part => `${__dirname}/data/plantilles/${part}.json`;
if (simultani) {
const bundleDict = bundles
.reduce((acc, item) => {
const part_id = crypto.randomBytes(5).toString('hex')
item.part_id = part_id;
acc[part_id] = item;
return acc;
}, {});
fs.writeFileSync(bundlePath, JSON.stringify({
id: bundleId,
...other,
simultani: true,
bundles: bundleDict,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
}))
} else {
const partsThatExist = Object.fromEntries(
Object.entries(parts)
.filter(([key, value]) => fs.existsSync(partPath(value)))
)
fs.writeFileSync(bundlePath, JSON.stringify({
id: bundleId,
...other,
parts: partsThatExist,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
}))
}
io.emit('.bundle_created', bundleId)
})
const cutBeforeValue = (arr, value) => {
const index = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(value));
return index >= 0 ? arr.slice(index) : [];
}
socket.on('.create_bundles_a_terra', ({ parts, ...other }) => {
const partPath = part => `${__dirname}/data/plantilles/${part}.json`;
const partsThatExist = Object.fromEntries(
Object.entries(parts)
.filter(([key, value]) => fs.existsSync(partPath(value)))
)
Object.entries(partsThatExist).forEach(([part, plantilla]) => {
// Part in ['Folre', 'Manilles', 'Puntals']
if (part?.toLowerCase() === 'pinya' || part?.toLowerCase() === 'tronc') {
return;
}
const bundleId = crypto.randomBytes(5).toString('hex')
const bundlePath = `${__dirname}/data/bundles/${bundleId}.json`;
const partsUntilValue = Object.fromEntries(
cutBeforeValue(
Object.entries(partsThatExist),
Object.entries(partsThatExist)
.find(([key, value]) => key === part)
)
)
const { shortName } = other
const newShortName = `${shortName} (${part[0].toLowerCase()}t)`
const newNom = `${part} a terra de ${shortName}`
fs.writeFileSync(bundlePath, JSON.stringify({
id: bundleId,
...other,
nom: newNom,
shortName: newShortName,
parts: partsUntilValue,
createdAt: new Date().toISOString(),
}))
io.emit('.bundle_created', bundleId)
})
})
socket.on('.edit_bundle', ({ id, hidden, ...other }) => {
const bundlePath = `${__dirname}/data/bundles/${id}.json`;
const bundleExists = fs.existsSync(bundlePath);
if (bundleExists) {
const bundle = JSON.parse(fs.readFileSync(bundlePath))
if (hidden !== undefined) bundle.hidden = hidden
bundle.updatedAt = new Date().toISOString()
bundle.id = id
Object.entries(other)
.filter(([key, value]) => value !== undefined)
.forEach(([key, value]) => bundle[key] = value)
fs.writeFileSync(bundlePath, JSON.stringify(bundle))
io.emit('.bundle_edited', id)
} else {
io.emit('.bundle_edited', 'ERROR:NOT_EXISTS');
}
})
socket.on('.request_bundle', (bundleId) => {
const bundle = getBundleFromId(bundleId)
socket.emit('.bundle', {
id: bundleId,
bundle: bundle
});
})
function uploadBundleToS3(id, data) {
const fullParams = {
Bucket: 'aleta-' + colla,
Key: `full_bundles/${id}.json`,
Body: data
};