-
Notifications
You must be signed in to change notification settings - Fork 12
/
dataModule.js
617 lines (593 loc) · 21.5 KB
/
dataModule.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
const fs = require("fs");
const path = require("path");
const config = require("./config.json"); // 設定檔
const pokaLog = require("./log") // 可愛控制台輸出
const express = require("express")
const router = express.Router();
const db = require("./db/db.js");
const lyricdb = require("./db/lyric.js");
const { addLog } = require("./db/log");
if (config.PokaPlayer.debug) {
router.use(require('cors')({
credentials: true,
origin: 'http://localhost:8080'
}))
}
router.use(db.session);
router.use(express.json());
let moduleList = {};
fs.readdir(__dirname + "/dataModule", (err, files) => {
if (err) return console.error(err);
files.forEach(async file => {
if (path.extname(file) == ".js" && !file.match(/^._/)) {
let uri = __dirname + "/dataModule/" + file,
_module = require(uri);
let moduleData = {
name: _module.name,
active: Object.keys(_module),
js: uri
};
let enabled = moduleData.active.indexOf("onLoaded") > -1 && _module.enabled ?
await _module.onLoaded() :
true;
if (enabled && _module.enabled) moduleList[moduleData.name] = moduleData;
else if (moduleData.name) pokaLog.logDB('dataModule', `Module ${moduleData.name} disabled`)
}
});
});
// 首頁
router.get("/", (req, res) => {
res.send("PokaPlayer API");
});
// 先在這裡蹦蹦蹦再轉交給其他好朋友
router.use((req, res, next) => {
if (req.path == "/v2/user/login/" || req.path == "/v2/user/logout/") {
return next();
}
if (req.session.user) {
return next();
} else {
return res.status(403).send("Permission Denied Desu");
}
});
// router
router.use("/playlist", require("./router/playlist"));
router.use("/v2", require("./router/index"));
//-----------------------------> 首頁
// 取得想推薦的東西(?
router.get("/home/", async (req, res) => {
//http://localhost:3000/pokaapi/home
let resData = [];
await Promise.all(
Object.values(moduleList)
.filter(x => x.active.includes("getHome"))
.map(async x => {
try {
let results = (await require(x.js).getHome(req.session.user)) || null;
for (let result of results) {
if (result) {
if (Object.values(result).filter(v => v.length).length > 0)
resData.push(result)
}
}
} catch (e) {
showError(x.name, e)
}
})
)
return res.json(resData);
});
//-----------------------------> 資料夾
// 取得資料夾清單(根目錄)
router.get("/folders/", async (req, res) => {
//http://localhost:3000/pokaapi/folders
let resData = {
folders: [],
songs: []
};
await Promise.all(
Object.values(moduleList)
.filter(x => x.active.includes("getFolders"))
.map(async x => {
try {
let result = (await require(x.js).getFolders()) || null;
if (result) {
for (let item of Object.keys(result)) {
resData[item] = resData[item].concat(result[item])
}
}
} catch (e) {
showError(x.name, e)
}
})
)
res.json(resData);
});
// 透過取得資料夾內檔案清單
router.get("/folderFiles/", async (req, res) => {
//http://localhost:3000/pokaapi/folderFiles/?moduleName=DSM&id=dir_636
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getFolderFiles") == -1)
return res.status(501).send("The required module is currently unavailable :(");
let resData = { folders: [], songs: [] };
try {
resData = await _module.getFolderFiles(req.query.id);
} catch (e) {
showError(moduleName, e)
}
return res.json(resData);
});
//-----------------------------> 搜尋
// 搜尋
router.get("/search/", async (req, res) => {
//http://localhost:3000/pokaapi/search/?keyword=a
let resData = {
folders: [],
songs: [],
albums: [],
artists: [],
composers: [],
playlists: []
};
await Promise.all(
Object.values(moduleList)
.filter(x => x.active.includes("search"))
.map(async x => {
try {
let result = (await require(x.js).search(req.query.keyword)) || null;
if (result) {
for (let item of Object.keys(result)) {
resData[item] = resData[item].concat(result[item])
}
}
} catch (e) {
showError(x.name, e)
}
})
)
return res.json(resData);
});
//-----------------------------> 專輯
// 取得專輯清單
router.get("/albums/", async (req, res) => {
//http://localhost:3000/pokaapi/albums
let resData = [];
await Promise.all(
Object.values(moduleList)
.filter(x => x.active.includes("getAlbums"))
.map(async x => {
try {
let { albums } = (await require(x.js).getAlbums()) || null;
if (albums) {
resData = resData.concat(albums)
}
} catch (e) {
showError(x.name, e)
}
})
)
res.json({ albums: resData });
});
// 取得專輯歌曲
router.get("/albumSongs/", async (req, res) => {
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getAlbumSongs") == -1)
return res.status(501).send("The required module is currently unavailable :(");
//http://localhost:3000/pokaapi/albumSongs/?moduleName=DSM&data={%22album_name%22:%22%E2%8A%BF%22,%22artist_name%22:%22Perfume%22,%22album_artist_name%22:%22Perfume%22}
// -> {"album_name":"⊿","artist_name":"Perfume","album_artist_name":"Perfume"}
let albumSongs;
try {
albumSongs = await _module.getAlbumSongs(req.query.data);
} catch (e) {
albumSongs = {
songs: []
};
showError(moduleName, e)
}
return res.json(albumSongs);
});
// 取得專輯資料
router.get("/album/", async (req, res) => {
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getAlbum") == -1)
return res.status(501).send("The required module is currently unavailable :(");
//http://localhost:3000/pokaapi/album/?moduleName=Netease2&id=34841226
// -> Album + Songs
let album;
try {
album = await _module.getAlbum(req.query.id);
} catch (e) {
showError(x.name, e)
}
return res.json(album);
});
//-----------------------------> 播放清單
// 取得播放清單的清單
router.get("/playlists/", async (req, res) => {
//http://localhost:3000/pokaapi/playlists
let r = {
playlists: [],
playlistFolders: []
};
res.header("Cache-Control", "max-age=7200") //快取 2hr
await Promise.all(
Object.values(moduleList)
.filter(x => x.active.includes("getPlaylists"))
.map(async x => {
try {
let res = (await require(x.js).getPlaylists(req.session.user)) || null;
if (res) {
if (res.playlists)
r.playlists = r.playlists.concat(res.playlists);
if (res.playlistFolders)
r.playlistFolders = r.playlistFolders.concat(res.playlistFolders);
}
} catch (e) {
showError(x.name, e)
}
})
)
res.json(r);
});
// 取得播放清單的歌曲
router.get("/playlistSongs/", async (req, res) => {
//http://localhost:3000/pokaapi/playlistSongs/?moduleName=DSM&id=playlist_shared_normal/15
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getPlaylistSongs") == -1)
return res.status(501).send("The required module is currently unavailable :(");
let r;
try {
r = await _module.getPlaylistSongs(req.query.id, req.session.user);
} catch (e) {
showError(moduleName, e)
}
return res.json(r || null);
});
//-----------------------------> 演出者
// 取得演出者資料
router.get("/artist/", async (req, res) => {
//http://localhost:3000/pokaapi/artist/?moduleName=Netease2&id=19859
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getArtist") == -1)
return res.status(501).send("The required module is currently unavailable :(");
let r;
try {
r = await _module.getArtist(req.query.id);
} catch (e) {
showError(moduleName, e)
}
return res.json(r || null);
});
// 取得演出者清單
router.get("/artists/", async (req, res) => {
//http://localhost:3000/pokaapi/artists
let r = {
artists: []
};
for (var i in Object.keys(moduleList)) {
let x = moduleList[Object.keys(moduleList)[i]];
let y = require(x.js);
if (x.active.indexOf("getArtists") > -1) {
try {
let list = (await y.getArtists()) || null;
if (list) {
for (i = 0; i < list.artists.length; i++) r.artists.push(list.artists[i]);
}
} catch (e) {
showError(x.name, e)
}
}
}
res.json(r);
});
// 取得演出者的專輯
router.get("/artistAlbums/", async (req, res) => {
//http://localhost:3000/pokaapi/artistAlbums/?moduleName=DSM&id=ひいらぎ
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getArtistAlbums") == -1)
return res.status(501).send("The required module is currently unavailable :(");
let r;
try {
r = await _module.getArtistAlbums(req.query.id);
} catch (e) {
showError(moduleName, e)
}
return res.json(r);
});
//-----------------------------> 作曲者
router.get("/composer/", async (req, res) => {
//http://localhost:3000/pokaapi/composers/?moduleName=DSN&id=19859
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getComposer") == -1)
return res.status(501).send("The required module is currently unavailable :(");
let r;
try {
r = await _module.getComposer(req.query.id);
} catch (e) {
showError(moduleName, e)
}
return res.json(r || null);
});
// 取得作曲者清單
router.get("/composers/", async (req, res) => {
//http://localhost:3000/pokaapi/composers
let r = {
composers: []
};
for (var i in Object.keys(moduleList)) {
let x = moduleList[Object.keys(moduleList)[i]];
let y = require(x.js);
if (x.active.indexOf("getComposers") > -1) {
try {
let list = (await y.getComposers()) || null;
if (list) {
for (i = 0; i < list.composers.length; i++) r.composers.push(list.composers[i]);
}
} catch (e) {
showError(x.name, e)
}
}
}
res.json(r);
});
// 取得作曲者的專輯
router.get("/composerAlbums/", async (req, res) => {
//http://localhost:3000/pokaapi/composerAlbums/?moduleName=DSM&id=飛内将大
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getComposerAlbums") == -1)
return res.status(501).send("The required module is currently unavailable :(");
let r;
try {
r = await _module.getComposerAlbums(req.query.id);
} catch (e) {
showError(moduleName, e)
}
return res.json(r || {
albums: []
});
});
//-----------------------------> 歌曲
// 取得歌曲串流
router.get("/song/", async (req, res) => {
// http://localhost:3000/pokaapi/song/?moduleName=DSM&songRes=original&songId=music_758 //這首 Chrome 會出錯
// http://localhost:3000/pokaapi/song/?moduleName=DSM&songRes=original&songId=music_941
// -> getSong(req, "original", "music_758")
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module) return res.status(501).send("The required module is currently unavailable :(");
let song = await _module.getSong(req, req.query.songRes, req.query.songId, res);
if (typeof song == "string") return res.redirect(song);
else if (song) {
let { headers: resHeaders } = song
let ifNull = x => x ?? "";
//針對 Audio 寫入 Header 避免 Chrome 時間軸不能跳
let headers = {
"Accept-Ranges": ifNull(resHeaders["accept-ranges"]),
"Content-Length": ifNull(resHeaders["content-length"]),
"Content-Range": ifNull(resHeaders["content-range"]),
"Content-Type": ifNull(resHeaders["content-type"]),
}
// fix for iOS AVPlayer
if (headers["Content-Type"] == "audio/x-flac") {
headers["Content-Type"] = "audio/flac";
}
// disable keep-alive
headers["Connection"] = "close";
// send data
res.writeHead(206, headers);
return song.data.pipe(res);
}
});
//-----------------------------> 封面
// 取得封面
router.get("/cover/", async (req, res) => {
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("getCover") == -1)
return res.status(501).send("The required module is currently unavailable :(");
//http://localhost:3000/pokaapi/cover/?moduleName=DSM&data={%22type%22:%22artist%22,%22info%22:%22%E3%82%8D%E3%82%93%22}
// -> {"type":"artist","info":"ろん"}
//http://localhost:3000/pokaapi/cover/?moduleName=DSM&data={%22type%22:%22album%22,%22info%22:{%22album_name%22:%22%E6%AE%BF%E5%A0%82%E2%85%A2%22,%22artist_name%22:%22%E7%BA%AF%E7%99%BD,%20Digger%20feat.%20%E4%B9%90%E6%AD%A3%E7%BB%AB,%20%E6%B4%9B%E5%A4%A9%E4%BE%9D%22,%22album_artist_name%22:%22Various%20Artists%22}}
// -> {"type":"album","info":{"album_name":"殿堂Ⅲ","artist_name":"纯白, Digger feat. 乐正绫, 洛天依","album_artist_name":"Various Artists"}}
let cover = await _module.getCover(req.query.data);
res.header("Cache-Control", "max-age=7200") //快取 2hr
return cover.pipe(res);
});
router.get("/req/", async (req, res) => {
let moduleName = req.query.moduleName;
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!_module || moduleList[moduleName].active.indexOf("req") == -1)
return res.status(501).send("The required module is currently unavailable :(");
//http://localhost:3000/pokaapi/req/?moduleName=Netease2&data=http%3A%2F%2Fp3.music.126.net%2FJB1yLZyVMPsbbSlSkfJdRw%3D%3D%2F6630055116648156.jpg
// -> Image
let cover = await _module.req(req.query.data);
if (!cover) return res.sendStatus(404);
if (typeof cover == "string" && cover.startsWith("http")) return res.redirect(cover);
if (cover.pipe) {
res.header("Cache-Control", "max-age=7200") //快取 2hr
return cover.pipe(res);
}
if (cover instanceof Buffer) {
res.header("Cache-Control", "max-age=7200") //快取 2hr
return res.send(cover);
}
return res.sendStatus(500);
});
//-----------------------------> 歌詞
// 搜尋歌詞
router.get("/searchLyrics/", async (req, res) => {
//http://localhost:3000/pokaapi/searchLyrics/?keyword=a
let resData = {
lyrics: []
};
await Promise.all(
Object.values(moduleList)
.filter(x => x.active.includes("searchLyrics"))
.map(async x => new Promise(async (resolve, reject) => {
let timeout = 10
const timer = setTimeout(() => {
console.log(`${x.name} timed out after ${timeout}s`)
return resolve()
}, timeout * 1000);
try {
let { lyrics } = (await require(x.js).searchLyrics(req.query.keyword)) || null;
if (lyrics) resData.lyrics = [...resData.lyrics, ...lyrics]
clearTimeout(timer);
resolve()
}
catch (e) {
showError(x.name, e)
}
}))
)
function similarity(s1, s2) {
function editDistance(s1, s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
let costs = new Array();
for (var i = 0; i <= s1.length; i++) {
let lastValue = i;
for (let j = 0; j <= s2.length; j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
let newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length] = lastValue;
}
return costs[s2.length];
}
let longer = s1;
let shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
let longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}
resData.lyrics = resData.lyrics
.map(item => {
let rate = similarity(req.query.keyword, `${item.name} ${item.artist}`)
return { ...item, rate }
})
.sort((a, b) => b.rate - a.rate)
return res.json(resData);
});
router.post("/lyric/", async (req, res) => {
let {
title,
artist,
songId,
source,
lyric
} = req.body
res.json(await lyricdb.saveLyric({
title,
artist,
songId,
source,
lyric
}))
})
router.get("/lyric/", async (req, res) => {
//http://localhost:3000/pokaapi/lyric/?moduleName=DSM&id=music_1801
let moduleName = req.query.moduleName;
let lyric = ``;
try {
lyric = await lyricdb.getLyric({
songId: req.query.id,
source: moduleName
});
if (!lyric) {
let _module = moduleName in moduleList ? require(moduleList[moduleName].js) : null;
// 沒這東西
if (!(!_module || moduleList[moduleName].active.indexOf("getLyric") == -1))
lyric = await _module.getLyric(req.query.id);
}
} catch (e) {
showError(moduleName, e)
}
return res.json({
lyrics: lyric ? [{
source: req.query.moduleName,
id: req.query.id,
lyric: lyric
}] : []
});
});
//-----------------------------> 隨機
// 隨機歌曲
router.get("/randomSongs/", async (req, res) => {
//http://localhost:3000/pokaapi/randomSongs/
let resData = {
songs: []
};
for (var i in Object.keys(moduleList)) {
let x = moduleList[Object.keys(moduleList)[i]];
let y = require(x.js);
if (x.active.indexOf("getRandomSongs") > -1) {
try {
let result = (await y.getRandomSongs(req.query.keyword)) || null;
if (result && result.songs)
for (i = 0; i < result.songs.length; i++) resData.songs.push(result.songs[i]);
} catch (e) {
showError(x.name, e)
}
}
}
return res.json(resData);
});
router.use((req, res, next) => {
res.status(404).send("PokaPlayer API - 404");
});
function showError(moduleName = false, error) {
pokaLog.logDMErr(moduleName || '?', error)
addLog({
level: "error",
type: "system",
event: `${moduleName} Error`,
description: error.stack
})
}
// catch err
process.on('uncaughtException', err => {
pokaLog.logErr('ERROR', err)
addLog({
level: "error",
type: "system",
event: `uncaughtException`,
description: err.stack
})
});
module.exports = router;