-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
289 lines (245 loc) · 7.17 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
var config = require('./config-loader.js')
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var MusicLibrary = require('./handlers/library')
var YoutubeDownloader = require('./handlers/youtube')
var path = require('path')
process.on('uncaughtException', function (exception) {
console.log(exception);
});
console.log("Launching server... ");
function logErrors(err, req, res, next) {
console.error(err.stack)
next(err)
}
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' })
} else {
next(err)
}
}
function errorHandler(err, req, res, next) {
res.status(500)
res.render('error', { error: err })
}
function checkAuth(req, res, next) {
if (config.token) {
console.log('checkAuth ' + req.url);
if (config.token !== req.get('api-token')) {
res.status(400).send('Bad Request')
return;
}
}
next();
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(logErrors)
app.use(checkAuth);
app.use(clientErrorHandler)
app.use(errorHandler)
var controllers = {};
const library = new MusicLibrary();
library.on('done', (message, indexDone, chunks) => {
console.log(indexDone + "/" + chunks + " - " + message);
if (indexDone === chunks) {
console.log("UPDATE COMPLETED!");
}
});
controllers.find_filename = function (req, res) {
var keyword = req.params.fileName;
console.log("Searching fileName " + keyword);
try {
var data = library.file(keyword);
console.log("Results for fileName " + keyword, data);
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.update_library = function (req, res) {
console.log("Updating library");
try {
res.json("Update requested");
var handler = library;
handler.update()
} catch (e) {
res.send(e);
}
};
controllers.rebuild_library = function (req, res) {
console.log("Clearing and rebuilding library");
var handler = library;
handler.drop();
console.log("Library dropped...");
controllers.update_library(req, res);
};
controllers.all_library = function (req, res) {
console.log("Requested full library");
try {
var data = library.all();
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.find = function (req, res) {
var keyword = req.params.keyword;
console.log("Searching in all fields " + keyword);
try {
var data = library.searchAll(keyword);
console.log("Results for all fields " + keyword, data);
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.find_title = function (req, res) {
var title = req.params.title;
console.log("Searching title " + title);
try {
var data = library.title(title);
console.log("Results for title " + title, data);
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.find_artist = function (req, res) {
var artist = req.params.artist;
console.log("Searching artist " + artist);
try {
var data = library.artist(artist);
console.log("Results for artist " + artist, data);
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.find_album = function (req, res) {
var album = req.params.album;
console.log("Searching album " + album);
try {
var data = library.album(album);
console.log("Results for album " + album, data);
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.random = function (req, res) {
var count = parseInt(req.params.count) || 10;
console.log("Random songs (" + count + ")");
try {
var data = library.random(count);
console.log("Results for random " + count, data);
res.json(data);
} catch (e) {
res.send(e);
}
};
controllers.downloadYT = function (req, res) {
var body = req.body;
if (!body || !body.list || body.list.length === 0) {
res.send("No data provided");
} else {
console.log("Downloading " + JSON.stringify(body.list));
if (!Array.isArray(body.list)) {
var list = [];
list.push(body.list);
body.list = list;
}
try {
const downloader = new YoutubeDownloader();
for (let index = 0; index < body.list.length; index++) {
const url = body.list[index];
downloader.start(url, function (filePath) {
//library add
library.parseAndAdd(filePath).then(function (data) {
console.log("Added to library: " + filePath);
}, function (err) {
console.log("Error adding to library " + filePath + " : " + err.message);
});
});
}
var data = `Download of ${body.list.length} url started`;
console.log(data);
res.json(data);
} catch (e) {
res.send(e.message);
}
}
};
app.route('/search/:keyword').get(controllers.find);
app.route('/file/:fileName').get(controllers.find_filename);
app.route('/artist/:artist').get(controllers.find_artist);
app.route('/song/:title').get(controllers.find_title);
app.route('/title/:title').get(controllers.find_title);
app.route('/album/:album').get(controllers.find_album);
app.route('/random/:count').get(controllers.random);
app.route('/random').get(controllers.random);
app.route('/library').get(controllers.all_library);
app.route('/library/update').get(controllers.update_library);
app.route('/library/rebuild').get(controllers.rebuild_library);
app.route('/download/yt').post(controllers.downloadYT);
function start(app) {
app.listen(config.port, '0.0.0.0');
console.log('Library API server started on: ' + config.port);
//watch root dir for updates
if (config.watchdog && config.watchdog.enabled) {
addWatcher(config.rootDir);
}
}
//updating db
const current = library;
var size = current.size();
if (size === 0) {
console.log("Updating library...");
current.on('done', (index) => {
console.log("Library updated.");
console.log(res);
start(app);
});
current.update();
} else {
console.log("Library has " + size + " files");
start(app);
}
function addWatcher(watchDir) {
const chokidar = require('chokidar');
// Initialize watcher.
const watcher = chokidar.watch(watchDir, {
ignored: /(^|[\/\\])\../, // ignore dotfiles
ignoreInitial: config.watchdog.ignoreInitial || false, //this avoids tthe emit of add/addDir events at startup
persistent: true,
usePolling: config.watchdog.usePolling || false, //default false, set this to true to successfully watch files over a network
interval: config.watchdog.interval || 100,
binaryInterval: config.watchdog.binaryInterval || 300
});
function check(file, eventName) {
//extension check
if (!config.ext.includes(path.extname(file).substring(1))) {
console.log("skipping " + file);
return;
}
console.log(`File ${file} has been ${eventName}`);
library.checkFile(file, undefined, eventName);
}
//listening for add, change and remove
watcher
.on('add', file => {
check(file, 'added');
})
.on('change', file => {
check(file, 'changed');
})
.on('unlink', file => {
console.log(`File ${file} has been removed`);
library.removeFromLibrary(file, "unlink");
})
.on('ready', () => {
console.log('Watchdog initial scan complete. Listening.')
});
}