-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_manage.js
411 lines (345 loc) · 12.4 KB
/
server_manage.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
/*
* Audio stream manager
*
* 07.01.2020
*
* */
const http = require('http');
const fs = require('fs');
const formidable = require('formidable');
const {
spawn,
execSync
} = require('child_process');
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////// GLOBAL CONSTANTS & VARIABLES ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
let VERSION = "ROSI POC AUDIO 0.1";
let PORT = 10011;
let SLICE_DURATION = 10;
let FORMAT_ENDING = ".flac";
let FORMAT_FFMPEGCODEC = "flac";
let FORMAT_MIME = "audio/flac";
const DIR_DB = 'db';
const STREAMS_DB = "db/streams.json";
const COVER_NAME = "folder.jpg";
const RELEVANT_TAGS = [ 'title',
'album',
'artist',
'album_artist',
'genre',
'track',
'disc',
'date'
];
const OPTIONAL_TAGS = [ 'comment'
];
if(typeof process.env.npm_package_version != "undefined")
{
VERSION = process.env.npm_package_version;
console.log("Using Environment Variable for VERSION, value: " + VERSION);
}
if(typeof process.env.npm_package_config_portms != "undefined")
{
PORT = parseInt(process.env.npm_package_config_portms);
console.log("Using Environment Variable for PORT, value: " + PORT);
}
if(typeof process.env.npm_package_config_msslicedur != "undefined")
{
SLICE_DURATION = parseInt(process.env.npm_package_config_msslicedur);
console.log("Using Environment Variable for SLICE_DURATION, value: " + SLICE_DURATION);
}
if(typeof process.env.npm_package_config_msformatending == "string")
{
FORMAT_ENDING = process.env.npm_package_config_msformatending;
console.log("Using Environment Variable for FORMAT_ENDING, value: " + FORMAT_ENDING);
}
if(typeof process.env.npm_package_config_msformatffmpeg == "string")
{
FORMAT_FFMPEGCODEC = process.env.npm_package_config_msformatffmpeg;
console.log("Using Environment Variable for FORMAT_FFMPEGCODEC, value: " + FORMAT_FFMPEGCODEC);
}
if(typeof process.env.npm_package_config_msformatmime == "string")
{
FORMAT_MIME = process.env.npm_package_config_msformatmime;
console.log("Using Environment Variable for FORMAT_MIME, value: " + FORMAT_MIME);
}
// html file containing upload form
const upload_html = fs.readFileSync("manager/upload_file.html");
const delete_html = fs.readFileSync("manager/delete.html");
const upload_path = "manager/tmp/";
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// HELPERS ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// file ... path to temp file
// info ... {title, album,... (more added later)}
let addFileToDB = function(file, info, price, res) {
try {
console.log("Getting metadata ...");
let finfo = JSON.parse(execSync("ffprobe -v quiet -print_format json -show_format \"" + file + "\""));
finfo = finfo.format;
let techinfo = {
duration: Math.ceil(Number(finfo.duration)),
price: price
};
for(let i = 0; i < RELEVANT_TAGS.length; i++)
{
let rkey = Object.keys(finfo.tags).find(key => key.toLowerCase() === RELEVANT_TAGS[i]);
if (typeof rkey == "undefined" && typeof info[RELEVANT_TAGS[i]] === "undefined") {
console.error("Necessary tag " + RELEVANT_TAGS[i] + " not found!");
res.writeHead(200);
res.end("Necessary tag \"" + RELEVANT_TAGS[i] + "\" not found! " +
"\nPlease fill in all of the following tags in your file: " +
RELEVANT_TAGS.join(', '));
return;
}
info[RELEVANT_TAGS[i]] = typeof info[RELEVANT_TAGS[i]] === "undefined" ?
finfo.tags[rkey] : info[RELEVANT_TAGS[i]];
}
for(let i = 0; i < OPTIONAL_TAGS.length; i++)
{
let rkey = Object.keys(finfo.tags).find(key => key.toLowerCase() === OPTIONAL_TAGS[i]);
if(typeof rkey != "undefined" && typeof info[OPTIONAL_TAGS[i]] === "undefined")
info[OPTIONAL_TAGS[i]] = finfo.tags[rkey];
}
// Convert track to number and remove possible slashes like (1/10) format
info.track = Number(info.track.split("/", 2)[0]);
console.log("Info Object:", info);
console.log("Adding " + file + " to database...");
// Convert and move ...
if (typeof info.albumID === "undefined")
{
info.albumID = info.album.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 10) + Date.now();
console.warn("No AlbumID provided - created new one.");
}
console.log('This Song belongs to AlbumID:', info.albumID);
let destDir = 'db/audio/' + info.albumID + '/';
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, {
recursive: true
});
}
techinfo.sliceDuration = typeof techinfo.sliceDuration == 'undefined' ?
SLICE_DURATION : techinfo.sliceDuration;
techinfo.sliceAmount = Math.ceil(techinfo.duration / techinfo.sliceDuration);
techinfo.fileBaseName = info.track + FORMAT_ENDING;
console.log("Now converting file using FFMPEG...");
// ---------- DEFINE STEPS ---------------------
let spliceAudio = (callback) =>
{
// ------ Get segmented audio files ---------
// ffmpeg -i zuhilfe.mp3 -map_metadata -1 -vn -c:a flac
// -f segment -segment_time 10 %03d.test05.flac
let ffmpeg = spawn('ffmpeg', ['-i', file, '-map_metadata', '-1', '-vn', '-c:a', 'flac',
'-f', 'segment', '-segment_time', techinfo.sliceDuration, '-v', 'quiet',
destDir + '%d.' + techinfo.fileBaseName
]);
ffmpeg.stdout.on('data', data => {
console.error(data.toString());
});
ffmpeg.stderr.on('data', data => {
console.log(data.toString());
});
ffmpeg.on('close', code => {
if (code == 0) {
console.log("Audio slicing finished successfully.");
callback(true);
}
else
{
console.error("FFMPEG finished with exit code:", code);
callback(false);
}
});
};
let extractCover = (callback) =>
{
// ------ Get cover of album ---------fs
//ffmpeg -i fernando.flac -an -vcodec mjpeg folder.jpg
let ffmpeg = spawn('ffmpeg', ['-i', file, '-an', '-vcodec', 'mjpeg', '-v', 'quiet',
'-vf', 'scale=480:480', destDir + COVER_NAME
]);
ffmpeg.stdout.on('data', data => {
console.error(data.toString());
});
ffmpeg.stderr.on('data', data => {
console.log(data.toString());
});
ffmpeg.on('close', code => {
if (code == 0) {
console.log("Cover extraction finished successfully.");
callback(true);
}
else
{
console.error("FFMPEG finished with exit code:", code);
callback(false);
}
});
};
// Delete temp-file and add info to db (file)
let finishSetup = () =>
{
fs.unlink(file, () => {
console.log("Deleted temporary file.");
});
let streams = JSON.parse(fs.readFileSync(STREAMS_DB));
info.duration = techinfo.duration,
streams.push({
"info": info,
"slice": {
"duration": techinfo.sliceDuration,
"length": techinfo.sliceAmount,
"price": techinfo.price
},
"dir": destDir,
"file": techinfo.fileBaseName,
"mime": FORMAT_MIME
});
fs.writeFileSync(STREAMS_DB, JSON.stringify(streams));
res.writeHead(200);
res.write('File uploaded, converted and added to database.\n');
res.write('AlbumID: ' + info.albumID);
res.end();
};
let handleError = (e) => {
console.error("Error occurred Converting File: " + e);
res.writeHead(500);
res.end("Internal Server Error.");
};
// CONNECT THE FUNCTIONS
spliceAudio((success) => {
if(!success)
{
handleError("Splicing file failed.");
return;
}
if(fs.existsSync(destDir + COVER_NAME))
{
// Cover file already exists, no need to replace it
finishSetup();
return;
}
extractCover((success) => {
if(!success)
console.warn("Could not extract cover image.");
// Continue anyway
finishSetup();
});
});
} catch (e) {
console.error("Error occurred Converting File: " + e);
res.writeHead(500);
res.end("Internal Server Error.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// SERVER ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
http.createServer(function(req, res) {
console.log("Requesting url:", req.url);
if (req.url == '/upload')
{
res.writeHead(200);
res.write(upload_html);
return res.end();
}
else if (req.url == '/delete')
{
res.writeHead(200);
res.write(delete_html);
return res.end();
}
else if (req.url == '/change')
{
res.writeHead(200);
res.write("Not yet implemented.");
return res.end();
}
else if(req.url == '/albums.js')
{
res.writeHead(200);
res.write("var albums = " + JSON.stringify(JSON.parse(fs.readFileSync(STREAMS_DB)).filter((t,i,l) => l.findIndex(lt => lt.info.albumID == t.info.albumID) == i).map(s => {
return { albumID: s.info.albumID,
album: s.info.album,
artist: s.info.album_artist,
date: s.info.date,
genre: s.info.genre
};
})) + ";\n");
return res.end();
}
else if (req.url == '/fileupload')
{
try {
let form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
let price = Number(fields['price_per_slice']);
let info = {};
if (fields.albumID != "") {
info.albumID = fields.albumID;
}
for (let i = 0; i < 25 &&
typeof fields["addtag_name_" + i] != "undefined" &&
fields["addtag_name_" + i] != ""; i++) {
info[fields["addtag_name_" + i]] = fields["addtag_value_" + i];
}
// oldpath : temporary folder to which file is saved to
let oldpath = files.filetoupload.path;
let newpath = upload_path + files.filetoupload.name;
// copy the file to a new location
fs.rename(oldpath, newpath, function(err)
{
try {
if (err) throw err;
addFileToDB(newpath, info, price, res);
} catch (e) {
console.error("Error occurred E02:" + e);
res.writeHead(500);
res.end("Internal Server Error.");
};
});
});
} catch (e) {
console.error("Error occurred E01:" + e);
res.writeHead(500);
res.end("Internal Server Error.");
};
}
else if (req.url == '/albumdelete')
{
try {
let form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
let albumID = fields['albumID'];
console.log("ablumID to delete:", albumID);
// Delete folder ...
try
{
execSync("rm -rf db/audio/" + albumID);
console.log("Deleted data folder.");
fs.writeFileSync(STREAMS_DB, JSON.stringify(JSON.parse(fs.readFileSync(STREAMS_DB))
.filter(t => t.info.albumID !== albumID)
));
console.log("Deleted from DB-File.");
res.writeHead(200);
res.end("Delete SUCCESS.");
}catch(e)
{
console.error("Error occurred when trying to DELETE album: " + e
+ " Please check database for consistency!");
res.writeHead(500);
res.end("Internal Server Error.");
};
});
} catch (e) {
console.error("Error occurred E01:" + e);
res.writeHead(500);
res.end("Internal Server Error.");
};
}
}).listen(PORT);
console.log("Available functions:");
console.log(" http://127.0.0.1:" + PORT + "/upload - add new streams");
console.log(" http://127.0.0.1:" + PORT + "/delete - delete albums");
console.log(" http://127.0.0.1:" + PORT + "/change - change info");