-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
2100 lines (1974 loc) · 69.8 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 fileUpload = require('express-fileupload')
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');
const { MongoClient, ObjectId } = require('mongodb');
const app = express();
const { promises: fs } = require('fs');
const { spawn } = require('child_process');
const history = require('connect-history-api-fallback');
const cron = require('node-cron');
const aggregations = require('./aggregations.js');
const { OAuth2Client } = require('google-auth-library');
require('dotenv').config();
const console = require('console');
const { $push } = require('mongo-dot-notation');
async function exists (path) {
try {
await fs.access(path)
return true
} catch {
return false
}
}
// Function to run a Python script and return a Promise
function runPythonScript(scriptPath, args = []) {
return new Promise((resolve, reject) => {
const pythonProcess = spawn('python3', [scriptPath, ...args]);
pythonProcess.stdout.on('data', (data) => {
console.log(`stdout from ${scriptPath}: ${data}`);
});
pythonProcess.stderr.on('data', (data) => {
console.error(`stderr from ${scriptPath}: ${data}`);
});
pythonProcess.on('close', (code) => {
console.log(`${scriptPath} process exited with code ${code}`);
if (code === 0) {
resolve();
} else {
reject(new Error(`${scriptPath} process exited with code ${code}`));
}
});
});
}
const deleteFiles = async (audioID) => {
const peaksPath = 'peaks/' + audioID + '.json';
const spectrogramsPath = 'spectrograms/' + audioID;
const mp3Path = 'audio/mp3/' + audioID + '.mp3';
const wavPath = 'audio/wav/' + audioID + '.wav';
const opusPath = 'audio/opus/' + audioID + '.opus';
const peaksPathExists = await exists(peaksPath);
const spectrogramsPathExists = await exists(spectrogramsPath);
const mp3PathExists = await exists(mp3Path);
const wavPathExists = await exists(wavPath);
const opusPathExists = await exists(opusPath);
if (peaksPathExists) {
fs.unlink(peaksPath)
}
if (spectrogramsPathExists) {
fs.rm(spectrogramsPath, { recursive: true, force: true })
}
if (mp3PathExists) {
fs.unlink(mp3Path)
}
if (wavPathExists) {
fs.unlink(wavPath)
}
if (opusPathExists) {
fs.unlink(opusPath)
}
}
const getSuffix = mimetype => {
// TODO add other audio file types
const end = mimetype.split('/')[1];
if (end === 'mpeg') {
return '.mp3'
} else if (end === 'wav' || end === 'x-wav') {
return '.wav'
} else if (end === 'm4a' || end === 'x-m4a') {
return '.m4a'
} else if (end === 'flac' || end === 'x-flac') {
return '.flac'
} else if (end === 'ogg' || end === 'x-ogg') {
return '.opus'
} else if (end === 'opus' || end === 'x-opus') {
return '.opus'
}
};
cron.schedule('0 0 * * *', () => {
spawn('python3', ['delete_unlinked_audio.py'])
})
// schedule a cron job to backup every day
cron.schedule('0 0 * * *', () => {
spawn('python3', ['backups/backup_mongo.py'])
});
app.use(fileUpload({
createParentPath: true
}))
app.use(history({
htmlAcceptHeaders: ['text/html']
}))
app.use(cors({
origin: '*'
}));
app.use(bodyParser({
limit: '1000mb'
}))
app.use(express.json({
type: ['application/json', 'text/plain']
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(morgan('dev'));
const apiTimeout = 600000;
app.use((req, res, next) => {
// Set the timeout for all HTTP requests
req.setTimeout(apiTimeout, () => {
let err = new Error('Request Timeout');
err.status = 408;
next(err);
});
// Set the server response timeout for all HTTP requests
res.setTimeout(apiTimeout, () => {
let err = new Error('Service Unavailable');
err.status = 503;
next(err);
});
next();
});
const settings = 'retryWrites=true&w=majority';
const webAddress = 'swara.f5cuf.mongodb.net/swara';
const password = process.env.PASSWORD;
const username = process.env.USER_NAME;
const login = `srv://${username}:${password}`;
const uri = `mongodb+${login}@${webAddress}?${settings}`;
const runServer = async () => {
try {
const client = await MongoClient.connect(uri, { useUnifiedTopology: true });
console.log('Connected to Database')
const db = client.db('swara');
const transcriptions = db.collection('transcriptions');
const audioFiles = db.collection('audioFiles');
const audioEvents = db.collection('audioEvents');
const musicians = db.collection('musicians');
const eventTypes = db.collection('audioEventTypes');
const ragas = db.collection('ragas');
const instruments = db.collection('instruments');
const location = db.collection('location');
const performanceSections = db.collection('performanceSections');
const audioRecordings = db.collection('audioRecordings');
const users = db.collection('users');
const phonemes = db.collection('phonemes');
const collections = db.collection('collections');
const gharanas = db.collection('gharanas');
app.post('/insertNewTranscription', async (req, res) => {
// creates new transcription entry in transcriptions collection
try {
const insert = req.body;
insert['dateCreated'] = new Date(insert.dateCreated);
insert['dateModified'] = new Date(insert.dateModified);
const result = await transcriptions.insertOne(req.body)
const userID = insert.userID;
const query = { _id: ObjectId(userID) };
// const update = { transcriptions: $push(result.insertedId) };
const update = { $push: { transcriptions: result.insertedId } };
await users.updateOne(query, update);
res.send(JSON.stringify(result));
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post('/updateTranscription', async (req, res) => {
// updates a transcription
const updateObj = {};
Object.keys(req.body).forEach(key => {
if (key !== '_id') updateObj[key] = req.body[key]
});
updateObj['dateModified'] = new Date();
updateObj['dateCreated'] = new Date(updateObj['dateCreated'])
const query = { '_id': ObjectId(req.body._id) };
const update = { '$set': updateObj };
try {
const result = await transcriptions.updateOne(query, update);
result['dateModified'] = updateObj['dateModified']
res.send(JSON.stringify(result))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getAllCollections', async (req, res) => {
try {
const result = await collections.find().toArray();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getAllMusicians', async (req, res) => {
try {
const result = await musicians.find().toArray();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
})
app.get('/getAllGharanas', async (req, res) => {
try {
const result = await gharanas.find().toArray();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
})
app.get('/getAllTranscriptions', async (req, res) => {
try {
const userID = JSON.parse(req.query.userID);
const sortKey = JSON.parse(req.query.sortKey);
let newPermissions = false;
const reqNP = req.query.newPermissions;
if (reqNP && reqNP !== 'undefined') {
newPermissions = JSON.parse(req.query.newPermissions);
}
let secondarySortKey = undefined;
if (sortKey === 'family_name') secondarySortKey = 'given_name';
const sortDir = JSON.parse(req.query.sortDir);
const proj = {
title: 1,
dateCreated: 1,
dateModified: 1,
location: 1,
_id: 1,
durTot: 1,
raga: 1,
userID: 1,
permissions: 1,
name: 1,
family_name: 1,
given_name: 1,
audioID: 1,
instrumentation: 1,
explicitPermissions: 1,
soloist: 1,
soloInstrument: 1
}
let query;
if (!newPermissions) {
query = {
'$or': [
{
'$or': [
{ 'permissions': 'Public' },
{ 'permissions': 'Publicly Editable' }
]
},
{ 'userID': userID },
]
};
} else {
query = {
$or: [
{ "explicitPermissions.publicView": true },
{ "explicitPermissions.edit": userID },
{ "explicitPermissions.view": userID },
{ "userID": userID }
]
};
}
const sort = {};
sort[sortKey] = sortDir;
if (secondarySortKey) sort[secondarySortKey] = sortDir;
const result = await transcriptions
.find(query)
.collation({ 'locale': 'en' })
.sort(sort)
.project(proj)
.toArray();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getAllTranscriptionsOfAudioFile', async (req, res) => {
const query = {
audioID: req.query.audioID,
$or: [
{ userID: req.query.userID },
{ permissions: { $in: ['Public', 'Publicly Editable'] } }
]
};
const projection = {
title: 1,
dateCreated: 1,
dateModified: 1,
location: 1,
_id: 1,
durTot: 1,
raga: 1,
userID: 1,
permissions: 1,
name: 1,
family_name: 1,
given_name: 1,
audioID: 1,
instrumentation: 1,
explicitPermissions: 1
};
try {
const result = await transcriptions.find(query)
.project(projection).toArray();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/nameFromUserID', async (req, res) => {
// retrieve a user's name from their associated userID in the users db
const query = {
_id: ObjectId(JSON.parse(req.query.userID))
};
try {
const result = await users.findOne(query);
res.send(await JSON.stringify(result.name))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/allUsers', async (req, res) => {
try {
const result = await users.find().toArray();
res.send(await JSON.stringify(result))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
})
app.get('/getAllAudioRecordingMetadata', async (req, res) => {
// get all relevent data for audio files
const projection = {
performers: 1,
musicians: 1,
raags: 1,
_id: 1,
duration: 1,
fundamental: 1,
fileNumber: 1,
year: 1,
saEstimate: 1,
saVerified: 1,
octOffset: 1,
parentID: 1,
parentTitle: 1,
parentTrackNumber: 1,
userID: 1,
explicitPermissions: 1
}
try {
const out = await audioRecordings.find().project(projection).toArray();
res.json(out)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post('/saveMultiQuery', async (req, res) => {
const userID = req.body.userID;
if (!userID || userID.length !== 24) {
console.log(userID)
return res.status(400).send('Invalid userID: ' + userID);
}
const query = { _id: ObjectId(userID) };
const multiQueryObj = {};
multiQueryObj['queries'] = req.body.queries;
multiQueryObj['dateCreated'] = new Date();
multiQueryObj['options'] = req.body.options;
multiQueryObj['transcriptionID'] = req.body.transcriptionID;
multiQueryObj['title'] = req.body.title;
const uniqueID = new ObjectId();
multiQueryObj['_id'] = uniqueID;
try {
const result = await users.updateOne(query, { $push: {
multiQueries: multiQueryObj
} });
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.delete('/deleteQuery', async (req, res) => {
const query = { _id: ObjectId(req.body.userID) };
const mQueryID = ObjectId(req.body.queryID);
try {
const result = await users.updateOne(query, {
$pull: { multiQueries: { _id: mQueryID } }
});
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post('/createCollection', async (req, res) => {
// create a new collection
try {
// get the user's name from their userID
const query = { _id: ObjectId(req.body.userID) };
const projection = { projection: { _id: 0, name: 1 } };
const result = await users.findOne(query, projection);
const name = result.name;
// create the collection
const collection = req.body;
collection['dateCreated'] = new Date();
collection['dateModified'] = new Date();
collection['userName'] = name;
const result2 = await collections.insertOne(collection);
res.json(result2)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.delete('/deleteCollection', async (req, res) => {
// delete a collection
try {
const query = { _id: ObjectId(req.body._id) };
const result = await collections.deleteOne(query);
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post('/updateCollection', async (req, res) => {
// update a collection
try {
const query = { _id: ObjectId(req.body._id) };
// copy to updates, and remove _id
const updates = req.body;
delete updates._id;
const update = { $set: updates };
const result = await collections.updateOne(query, update);
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getAllAudioEventMetadata', async (req, res) => {
// retreive metadata for all audio events
try {
const result = await audioEvents.find().sort({
'name': 1
}).toArray();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post('/getOneTranscription', async (req, res) => {
// retreive a particular transcription. If _id is 0, return first one.
if (req.body._id === 0) {
try {
const result = await transcriptions.find().sort({ "_id": 1 }).next();
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
} else {
try {
const query = { '_id': ObjectId(req.body._id) };
const result = await transcriptions.findOne(query);
res.send(JSON.stringify(result))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
}
});
app.get('/pieceExists', async (req, res) => {
try {
const query = { _id: ObjectId(req.query._id) };
const result = await transcriptions.countDocuments(query) > 0;
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err)
}
});
app.delete('/oneTranscription', async (req, res) => {
// delete a particular transcription
try {
const query = { "_id": ObjectId(req.body._id) };
const result = await transcriptions.deleteOne(query);
// also, remove from user's transcriptions array
const userID = req.body.userID;
const query2 = { _id: ObjectId(userID) };
const tID = ObjectId(req.body._id);
const result2 = await users.updateOne(query2, { $pull: {
transcriptions: { $in: [tID] }
} });
console.log(userID)
console.log(query2)
console.log(result2)
res.json(result);
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.delete('/deleteRecording', async (req, res) => {
// delete a particular recording
try {
const query1 = { "_id": ObjectId(req.body._id) };
const found1 = await audioRecordings.findOne(query1);
const parentID = found1.parentID;
const result1 = await audioRecordings.deleteOne(query1);
// also delete recording from audioevent, if rec has associated audio
// event
// if parentID is not null
if (parentID) {
const query2 = { "_id": ObjectId(parentID) };
const projection = { 'recordings': 1, '_id': 0 };
const result2 = await audioEvents.findOne(query2, projection);
const recordings = result2.recordings;
const newRecordings = {};
let count = 0;
for (let idx in recordings) {
if (recordings[idx].audioFileId.toString() !== req.body._id) {
newRecordings[count] = recordings[idx];
if (newRecordings[count].parentTrackNumber !== count) {
newRecordings[count].parentTrackNumber = count;
// update in audioRecordings collection
const query = {
'_id': ObjectId(newRecordings[count].audioFileId)
};
const update = { $set: { 'parentTrackNumber': count } };
await audioRecordings.updateOne(query, update);
}
count++;
}
}
result2.recordings = newRecordings;
const result3 = await audioEvents.updateOne(query2, {
$set: {recordings: newRecordings}
});
// if no recs left, delete audio event
let result4 = undefined;
if (Object.keys(newRecordings).length === 0) {
result4 = await audioEvents.deleteOne(query2);
}
if (result4 !== undefined) {
res.json({ result1, result2, result3, result4 });
} else {
res.json({ result1, result2, result3 });
}
} else {
res.json(result1);
}
const peaksPath = 'peaks/' + req.body._id + '.json';
const spectrogramsPath = 'spectrograms/' + req.body._id;
const mp3Path = 'audio/mp3/' + req.body._id + '.mp3';
const wavPath = 'audio/wav/' + req.body._id + '.wav';
const opusPath = 'audio/opus/' + req.body._id + '.opus';
const peaksPathExists = await exists(peaksPath);
const spectrogramsPathExists = await exists(spectrogramsPath);
const mp3PathExists = await exists(mp3Path);
const wavPathExists = await exists(wavPath);
const opusPathExists = await exists(opusPath);
if (peaksPathExists) {
fs.unlink(peaksPath)
}
if (spectrogramsPathExists) {
fs.rm(spectrogramsPath, { recursive: true, force: true })
}
if (mp3PathExists) {
fs.unlink(mp3Path)
}
if (wavPathExists) {
fs.unlink(wavPath)
}
if (opusPathExists) {
fs.unlink(opusPath)
}
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.delete('/deleteAudioEvent', async (req, res) => {
// delete a particular audio event
try {
const query = { "_id": ObjectId(req.body._id) };
const projection = { 'recordings': 1, '_id': 0 };
const result = await audioEvents.findOne(query, projection);
const recordings = result.recordings;
const idxs = Object.keys(recordings);
idxs.forEach(async idx => {
const recID = recordings[idx].audioFileId?.toString();
// remove from audioRecordings collection
const query = { '_id': ObjectId(recID) };
const result = await audioRecordings.deleteOne(query);
console.log(result)
// remove from peaks folder
const peaksPath = 'peaks/' + recID + '.json';
const spectrogramsPath = 'spectrograms' + recID;
const mp3Path = 'audio/mp3/' + recID + '.mp3';
const wavPath = 'audio/wav/' + recID + '.wav';
const opusPath = 'audio/opus/' + recID + '.opus';
const peaksPathExists = await exists(peaksPath);
const spectrogramsPathExists = await exists(spectrogramsPath);
const mp3PathExists = await exists(mp3Path);
const wavPathExists = await exists(wavPath);
const opusPathExists = await exists(opusPath);
if (peaksPathExists) {
fs.unlink(peaksPath)
}
if (spectrogramsPathExists) {
fs.rm(spectrogramsPath, { recursive: true, force: true })
}
if (mp3PathExists) {
fs.unlink(mp3Path)
}
if (wavPathExists) {
fs.unlink(wavPath)
}
if (opusPathExists) {
fs.unlink(opusPath)
}
})
const delResult = await audioEvents.deleteOne(query);
console.log(delResult)
res.json(delResult);
// res.json('not deleted _id ' + req.body._id);
} catch (err) {
console.error(err);
res.status(500).send(err);
}
})
app.post('/getAudioDBEntry', async (req, res) => {
// retrieve a particular entry from the audioFiles db
try {
const query = { '_id': ObjectId(req.body._id) };
const result = await audioFiles.findOne(query);
res.json(result);
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getSortedMusicians', async (req, res) => {
//Get all names of all musicians from db, sorted
const sorts = { 'Last Name': 1, 'First Name': 1, 'Middle Name': 1};
const proj = { 'Initial Name': 1, _id: 0 };
if (req.query.verbose === 'true') {
proj['First Name'] = 1;
proj['Last Name'] = 1;
proj['Middle Name'] = 1;
}
try {
let result = await musicians.find().sort(sorts).project(proj).toArray();
const output = req.query.verbose === 'true' ?
result :
result.map(r => r['Initial Name']);
res.json(output)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getGharana', async (req, res) => {
//gets gharana of a particular musician
const initName = JSON.parse(req.query.initName);
const query = { 'Initial Name': initName };
const projection = { projection: { Gharana: 1, _id: 0 } };
try {
const result = musicians.findOne(query, projection);
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getInstruments', async (req, res) => {
// get names of all instruments, or instruments of particular kind (if
// melody is true)
const proj = { name: 1, _id: 0 };
if (req.query.melody) {
const query = { 'kind': 'melody' };
try {
const result = await instruments.find(query).project(proj).toArray();
res.json(result.map(r => r.name))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
} else {
try {
const result = await instruments.find().project(proj).toArray();
res.json(result.map(r => r.name))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
}
});
app.get('/verifySpectrogram', async (req, res) => {
// verify that spectrogram exists for a particular recording
const dir = 'spectrograms/' + req.query.id + '/0';
try {
const files = await fs.readdir(dir);
res.json(files.length > 0)
} catch (err) {
if (err.code === 'ENOENT') {
res.json(false)
} else {
console.error(err);
res.status(500).send(err);
}
}
});
app.get('/verifyMelograph', async (req, res) => {
// verify that melograph exists for a particular recording
const dir = 'melographs/' + req.query.id;
try {
const files = await fs.readdir(dir);
res.json(files.length > 0)
} catch (err) {
if (err.code === 'ENOENT') {
res.json(false)
} else {
console.error(err);
res.status(500).send(err);
}
}
});
app.get('/getRagaNames', async (req, res) => {
// gets names of all ragas
const proj = { 'name': 1, _id: 0 };
const sortRule = { 'name': 1 };
try {
let result = await ragas.find().sort(sortRule).project(proj).toArray();
const names = await result.map(r => r.name);
res.json(names)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getLocationObject', async (req, res) => {
// gets location object
try {
const result = await location.findOne({}, { projection: { _id: 0 } });
res.json(result);
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getEventTypes', async (req, res) => {
// retrieve list of all possible event types
const projection = { 'type': 1, _id: 0 };
try {
const result = await eventTypes.find().project(projection).toArray();
res.json(result.map(r => r.type))
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getPerformanceSections', async (req, res) => {
// retrieve list of all possible performance sections
const proj = { 'name': 1, _id: 0 };
try {
const result = await performanceSections.find().project(proj).toArray();
res.json(result.map(r => r.name));
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get('/getNumberOfSpectrograms', async (req, res) => {
// returns the number of spectrograms that the app needs to load
const dir = 'spectrograms/' + req.query.id + '/0';
try {
const files = await fs.readdir(dir);
res.json(files.length)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post('/updateVisibility', async (req, res) => {
// update the visibility of either a transcription, recording, or
// audioEvent
if (req.body.artifactType === 'transcription') {
try {
const query = { _id: ObjectId(req.body._id) };
const update = { $set: {
"explicitPermissions": req.body.explicitPermissions
} };
const result = await transcriptions.updateOne(query, update);
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
} else if (req.body.artifactType === 'audioRecording') {
try {
const q = { _id: ObjectId(req.body._id) };
const up = { $set: {
"explicitPermissions": req.body.explicitPermissions
} };
const options = { returnOriginal: false };
const result = await audioRecordings.findOneAndUpdate(q, up, options);
console.log(result)
const parentID = result.value.parentID;
const key = result.value.parentTrackNumber;
const query2 = { _id: ObjectId(parentID) };
const path = `recordings.${key}.explicitPermissions`;
const update2 = { $set: { [path]: req.body.explicitPermissions } };
const result2 = await audioEvents.updateOne(query2, update2);
res.json({ result, result2 })
} catch (err) {
console.error(err);
res.status(500).send(err);
}
} else if (req.body.artifactType === 'audioEvent') {
console.log(req.body)
try {
const query = { _id: ObjectId(req.body._id) };
const update = { $set: {
"explicitPermissions": req.body.explicitPermissions
} };
const result = await audioEvents.findOneAndUpdate(query, update);
const audioEvent = result.value;
for (let recording of Object.values(audioEvent.recordings)) {
const query = { _id: ObjectId(recording.audioFileId) };
const update = { $set: {
"explicitPermissions": req.body.explicitPermissions
} };
await audioRecordings.findOneAndUpdate(query, update);
}
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);
}
}
});
// app.post('/makeVisualizationData', async (req, res) => {
// // generate visualization data for the given recording ID
// const script1 = './visualization_scripts/generate_melograph.py';
// const script2 = './visualization_scripts/make_spec_data.py';
// try {
// await Promise.all([
// runPythonScript(script1, [req.body.recId]),
// runPythonScript(script2, [req.body.recId])
// ])
// } catch (err) {
// console.error(err);
// res.status(500).send(err);
// }
// })
app.post('/makeSpectrograms', async (req, res) => {
// generate spectrograms for the given recording ID and tonic estimate
const makingSpecs = spawn(
'python3',
['generate_log_spectrograms.py', req.body.recId, req.body.saEst]
);
try {
makingSpecs.stdout.on('data', data => {
console.log(`stdout: ${data}`)
});
makingSpecs.stderr.on('data', data => {
console.error(`stderr: ${data}`)
});
await makingSpecs.on('close', (msg) => {
console.log(msg)
res.json('made the spectrograms')
})
} catch (err) {
console.error(err)
}
})
app.post('/makeMelograph', async (req, res) => {
res.setTimeout(10 * 60 * 1000); // 10 minutes
const makingMelograph = spawn(
'python3',
['generate_melograph.py', req.body.recId, req.body.saEst]
);
try {
makingMelograph.stdout.on('data', data => {
console.log(`stdout: ${data}`)
});
makingMelograph.stderr.on('data', data => {
console.error(`stderr: ${data}`)
});
// await makingMelograph.on('close', (msg) => {
// console.log(msg)
// res.json('made the melograph')
// })
await new Promise((resolve, reject) => {
makingMelograph.on('close', (msg) => {
console.log(msg);
resolve();
});
makingMelograph.on('error', (err) => {
console.error(err);
reject(err);
});
});
res.json('made the melograph')
} catch (err) {
console.error(err)
}
})
app.get('/getAudioEvent', async (req, res) => {
try {
const result = await audioEvents.findOne({
_id: ObjectId(req.query._id)
});
res.json(result)
} catch (err) {
console.error(err);
res.status(500).send(err);