-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
703 lines (511 loc) · 19.4 KB
/
node_helper.js
File metadata and controls
703 lines (511 loc) · 19.4 KB
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
'use strict';
//we dont need specific identifiers in all cases, for servers, they need to eb sent back to everyone !!
const NodeHelper = require("node_helper");
const fs = require("fs");
const path = require("path");
const { setDebug, findServers, stopFindingServers, FolderTree, getNodeChildren, allValuesTrue, Media } = require('./findServers.cjs');
var self = null;
//the playlist returned to the main modele will be determined by the use of DLNA and if the DLNA source is selected in the module - this.config.DLNAplaying
module.exports = NodeHelper.create({
start: function ()
{
console.log("SimplePlayer Node Helper started");
this.requestRegistry = {};
this.setInitialValues();
},
setInitialValues()
{
this.servers = []; //must be unique
this.serverId = -1;
this.DLNAtrackPaths = []; // the actual DLNA playlist that is sent back to the module to play, can be added/subtracted, cleared, saved and loaded into
this.DLNAtrackArt = []; //dlna art for each matching track above
this.DLNAImages = []; //dlna images that are currently
this.currentNodeID = null;
this.currentServer = null;
this.currentServerIdx = null;
this.DLNAShowing = false;
},
generateUniqueId() {
return 'req_' + Math.random().toString(36).substr(2, 9);
},
socketNotificationReceived(notification, fullpayload)
{
var identifier = fullpayload.identifier;
var payload = fullpayload.payload;
if (payload && payload.returnPlaylist) { this.DLNAShowing = payload.returnPlaylist };
if (notification === "CONFIG") {
this.config = {};
this.config.debug = payload.config.debug;
setDebug(this.config.debug);
}
if (notification === "SCAN_DIRECTORY") {
const absolutePath = path.resolve(payload);
//get the files for the web side of the module
const files = fs.readdirSync(payload).filter(f => f.match(/\.(mp3|wav|ogg)$/i)).map(f => `${path.join(payload, f)}`);
this.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [files, null,null]);
}
if (notification === "LOAD_PLAYLIST") {
try {
this.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [this.getPlaylist(payload), null, null]);
} catch (err) {
console.error("Error loading playlist:", err);
}
}
if (notification === "GET_DLNA_SERVERS") {
//regardless of when this is called, need to reset some value to defaults
this.setInitialValues();
this.getDLNAServers(identifier);
//wait for 10 seconds and then stop finding servers
setTimeout(() => {
console.log('Stopping server discovery...');
stopFindingServers();
}, 10000);
}
if (notification === "DLNA_ACTION")
{
//determined by actionm handle the passed payload
switch (payload.action) {
case "ScrollDown":
return;
case "ScrollUp":
return;
case "Add":
return;
case "Remove":
return;
case "Clear":
return;
case "Save":
return;
case "Open":
return;
case "ScrollLeft":
//should be able to return details at the same level as the parentid of the passed item
//console.log("left", payload.currentServerID);
this.getDLNAItems(identifier, payload.action, payload.item, payload.currentServerID);
return;
case "ScrollRight":
//if the item passed is a server check for 0 (id of a server is 0)
//otherwise check for children and if present return them and if not present search and return
//console.log("right", payload.currentServerID);
this.getDLNAItems(identifier, payload.action, payload.item, payload.currentServerID);
return;
}
}
if (notification === "GET_METADATA")
{
this.getMetaData(identifier, payload);
}
if (notification === "CLEAR_DLNA_PLAYLIST") {
//clear local playlist
this.DLNAtrackPaths = [];
this.DLNAtrackArt = [];
this.DLNAImages = [];
if (this.DLNAShowing) { this.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [this.DLNAtrackPaths, this.DLNAImages, this.DLNAtrackArt]) }
//reload the servers, server id here shold always be -1
this.setInitialValues();
this.getDLNAServers(identifier);
//wait for 10 seconds and then stop finding servers
setTimeout(() => {
console.log('Stopping server discovery...');
stopFindingServers();
}, 10000);
}
if (notification === "GET_DLNA_PLAYLIST") //send back the current playlist
{
this.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [this.DLNAtrackPaths, this.DLNAImages, this.DLNAtrackArt]);
}
if (notification === "SAVE_DLNA_PLAYLIST") //save the current playlist
{
var DLNAPlaylistPath = path.join(payload.musicDirectory, payload.DLNAPlaylistName);
this.buildM3U(DLNAPlaylistPath, this.DLNAtrackPaths, this.DLNAtrackArt);
}
if (notification === "OPEN_DLNA_PLAYLIST") //save the current playlist
{
var DLNAPlaylistPath = path.join(payload.musicDirectory, payload.DLNAPlaylistName);
[ this.DLNAtrackPaths, this.DLNAtrackArt ] = this.getDLNAPlaylist(DLNAPlaylistPath);
if (payload.returnPlaylist) { this.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [this.DLNAtrackPaths, this.DLNAImages, this.DLNAtrackArt]) };
}
if (notification === "ADD_DLNA_ITEM")
{
//handle the add action: use the passed item to find this and all children nodes, searching for new ones if needed to get all the media and add to the DLNA playlist
//before passing it to the module for playing
this.currentServerIdx = this.findItemIndexById(this.servers, payload.currentServerID);
this.loadDLNAitems(identifier, this.currentServerIdx, payload.item.id , true, this.loadPlaylistCallback);
}
if (notification === "REMOVE_DLNA_ITEM") {
//handle the remove action: use the passed item to find this and all children nodes, searching for new ones if needed to get all the media and remove from the DLNA playlist
//before passing it to the module for playing
this.currentServerIdx = this.findItemIndexById(this.servers, payload.currentServerID);
this.loadDLNAitems(identifier, this.currentServerIdx, payload.item.id, true, this.removePlaylistCallback);
}
},
loadPlaylistCallback: function (err, searchNodes, identifier)
{
if (err)
{
console.error('Err:', err)
return;
}
if (allValuesTrue(searchNodes))
{
//getall the media from this and all child nodes, more recursion
//getall the media from this and all child nodes, more recursion
var parentNode = self.currentServer.folderTree.nodes.get(self.currentNodeID);
self.addMediaToTracks(parentNode);
if (self.DLNAShowing) {
try {
self.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [self.DLNAtrackPaths, self.DLNAImages, self.DLNAtrackArt]);
} catch (err) {
console.error("Error loading playlist:", err);
}
}
}
},
addMediaToTracks: function (parentNode)
{
parentNode.children.forEach(child =>
{
if (!(child.contentType == "media"))
{
self.addMediaToTracks(child)
}
else {
if (child.subType == "audio")
{
self.DLNAtrackPaths.push(child.url);
self.DLNAtrackArt.push(child.art);
}
else if (child.subType == "image")
{
self.DLNAImages.push(child.url);
}
}
});
},
removePlaylistCallback: function (err, searchNodes, identifier) {
if (err) {
console.error('Err:', err)
return;
}
if (allValuesTrue(searchNodes)) {
//getall the media from this and all child nodes, more recursion
var parentNode = self.currentServer.folderTree.nodes.get(self.currentNodeID);
self.removeMediaFromTracks(parentNode);
if (self.DLNAShowing) {
try {
self.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [self.DLNAtrackPaths, self.DLNAImages, self.DLNAtrackArt]);
} catch (err) {
console.error("Error loading playlist:", err);
}
}
}
},
removeMediaFromTracks: function (parentNode) {
parentNode.children.forEach(child => {
if (!(child.contentType == "media")) {
self.addMediaToTracks(child)
}
else {
var index = self.DLNAtrackPaths.indexOf(child.url);
if (index !== -1) {onCompleteCallback
if (child.subType == "audio") {
self.DLNAtrackPaths.splice(index, 1);
self.DLNAtrackArt.splice(index, 1);
}
else if (child.subType == "image") {
self.DLNAImages.splice(index, 1);
}
}
}
});
},
onCompleteCallback: function (err, searchNodes, identifier) {
//searching for node has finished time to check if all nodes completed searching
if (err) {
console.error('Err:', err)
return;
}
if (allValuesTrue(searchNodes)) {
//if we are here then all the searches should be completed and we can process them as we wish
var node = self.currentServer.folderTree.nodes.get(self.currentNodeID);
if (node.children.length == 0) {
//empty node
//add an empty child entry
self.currentServer.folderTree.addChild(node.id, "empty", "Empty Folder", null, null, "media", new Media(null, null, null, null, null));
}
self.sendSocketNotification(identifier+">"+ "NEW_DLNA_ITEMS", self.populateDLNAList_children(node));
}
},
loadDLNAitems: function (identifier, serverIDX, id, recurse = false, callback = '') {
this.currentServer = this.servers[serverIDX];
this.currentNodeID = id;
var searchNode = { id: this.currentNodeID };
var resetSearchNodes = true;
var currentNode = this.servers[serverIDX].folderTree.nodes.get(this.currentNodeID);
if (currentNode.contentType == "media") //just load the media, dont try and get any children // if here we must be in an add situation
{
this.addNodeMedia(currentNode);
if (self.DLNAShowing) {
try {
self.sendSocketNotification(identifier+">"+ "PLAYLIST_READY", [self.DLNAtrackPaths, self.DLNAImages, self.DLNAtrackArt]);
} catch (err) {
console.error("Error loading playlist:", err);
}
}
}
else {
if (callback == '') { callback = this.onCompleteCallback; }
self = this;
getNodeChildren(identifier, this.currentServer, searchNode, recurse, resetSearchNodes, callback)
}
},
addNodeMedia(node) {
if (node.subType == "audio") {
self.DLNAtrackPaths.push(node.url);
self.DLNAtrackArt.push(node.art);
}
else if (node.subType == "image") {
self.DLNAImages.push(node.url);
}
},
getDLNAItems(identifier, action, item, serverID)
{
var DLNAList = [];
//if action is right, find the node with the id -
//if it has children return them
//if there are no children, try and get some using its controlID (server = 0) as long as it isnt an item
var result = this.getSearchNodeId(item, serverID);
//if action is left, then find the node with the parentid and then its parent of the current node and populate children
if (action.toLowerCase() == "scrollleft") {
//get parent
result = this.getSearchNodeId({ id: result.node.parentId, type: null }, serverID); //first parent
result = this.getSearchNodeId({ id: result.node.parentId, type: null }, serverID); //first parent
DLNAList = this.populateDLNAList_children(result.node); // populate with the actual node
}
if (action.toLowerCase() == "scrollright") {
DLNAList = this.populateDLNAList_children(result.node); // populate with this nodes children
}
if (result.node && result.node.children.length>0) {
this.sendSocketNotification(identifier+">"+ "NEW_DLNA_ITEMS", DLNAList);
return;
}
//if node is missing need to add it
//searchid will be the current nodes id, i.e. the parent to any children to be found
this.currentServerIdx = this.findItemIndexById(this.servers, serverID);
this.loadDLNAitems(identifier, this.currentServerIdx,result.node.id);
},
findItemIndexById: function (list, searchId)
{
return list.findIndex(item => item.id === searchId);
},
getSearchNodeId: function (item, serverID) {
//determine the server instance
var server = this.servers.find(server => server.id === serverID);
//now find the item ID - but it may not be present yet
var searchID = item.id;
var node = null;
//if (item.type == "server") searchID = "0";
if (server.folderTree.nodes.size > 0) {
node = server.folderTree.nodes.get(searchID);
}
return {server: server, node: node, searchID: searchID};
},
populateDLNAList_children: function (node)
{
var DLNAList = [];
node.children.forEach(child => {
const newItem = { id: null, type: null, name: null, content: null }; //format of item to store in the list of items ready to return to the calling module
newItem.id = child.id;
newItem.type = child.contentType;
newItem.name = child.friendlyName ? child.friendlyName : child.name; //if a server use friendly name otherwise use the name
newItem.content = child.content;
DLNAList.push(newItem);
})
return DLNAList;
},
getDLNAServers: function (identifier)
{
//get any servers and send them back as part of a list that will be added to as new servers are found
var DLNAList = [];
console.log("Starting server discovery...",identifier);
const requestId = this.generateUniqueId(); // Unique per request
this.requestRegistry[requestId] = identifier;
//console.log("Request ID:", requestId, "Identifier:", identifier, " ", JSON.stringify(this.requestRegistry) );
findServers(identifier,(err, result, identifier) => {
if (err) console.error(err);
else {
const newServer = { id: this.serverId, server: result.details.friendlyName, properties: result, folderTree: new FolderTree() };
if (!this.servers.some(server => server.server === newServer.server)) {
newServer.folderTree.addChild(-99, this.serverId, newServer.server, null, null, "server",null);
this.servers.push(newServer);
this.serverId--;
}
if (!DLNAList.some(server => server.name === newServer.server)) {
const newItem = { id: null, type: null, name: null,address:null }; //format of item to store in the list of items ready to return to the calling module
newItem.id = newServer.id;
newItem.type = "server";
newItem.name = newServer.server;
newItem.address = `${newServer.properties.hostDetails.protocol}//${newServer.properties.hostDetails.host}`;//newServer.properties.hostDetails.protocol;
DLNAList.push(newItem);
}
//send back to all modules that requested the servers
for (const [key, identifier] of Object.entries(this.requestRegistry)) {
console.log("Ending server discovery...", key," ",identifier);
delete this.requestRegistry[key]; // Clean up
this.sendSocketNotification(identifier + ">" + "NEW_DLNA_ITEMS", DLNAList);
};
}
});
},
getPlaylist: function (payload)
{
/*
* Reads M3U/M3U8 playlist files in a directory and extracts all track paths into an array.
* @param {string} dir - The directory to search for playlist files.
* @returns {string[]} - Array of track paths.
*/
const trackPaths = [];
// Find .m3u and .m3u8 files
const playlistFiles = fs.readdirSync(payload[0]).filter(file =>
file.endsWith('.m3u') || file.endsWith('.m3u8')
);
// Parse each playlist
playlistFiles.forEach(file => {
if (payload[1] == file) {
const fullPath = path.join(payload[0], file);
const content = fs.readFileSync(fullPath, 'utf-8');
const lines = content.split(/\r?\n/);
lines.forEach(line => {
const trimmed = line.trim();
// Ignore comments and empty lines
if (trimmed && !trimmed.startsWith('#')) {
//if starts with http or https, keep it as is
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
trackPaths.push(trimmed);
}
else {
// Otherwise, join the music path relative to the playlist file
const resolvedPath = path.join(payload[0], trimmed);
trackPaths.push(resolvedPath);
}
}
});
}
});
return trackPaths;
},
getDLNAPlaylist: function (file) {
/*
* Reads M3U/M3U8 playlist files in a directory and extracts all track paths into an array.
* @param {string} dir - The directory to search for playlist files.
* @returns {string[]} - Array of track paths.
*/
const trackPaths = [];
const trackArt = [];
/*
#EXTM3U
#EXTINF:0,http://192.168.1.39:50002/transcoder/jpegtnscaler.cgi/ebdart/33859.jpg
http://192.168.1.39:50002/m/MP3/33859.mp3
*/
const content = fs.readFileSync(file, 'utf-8');
const lines = content.split(/\r?\n/);
lines.forEach(line => {
const trimmed = line.trim();
// empty lines
if (trimmed && !trimmed.startsWith('#EXTM3U')) {
if (trimmed.startsWith('#EXTINF')) //assume we have an album art entry
{
var albumArtURL = trimmed.split(",")[1];
trackArt.push(albumArtURL);
}
//if starts with http or https, keep it as is
else if (trimmed.startsWith('http://') || trimmed.startsWith('https://'))
{
trackPaths.push(trimmed);
}
else
{
// Otherwise, join the music path relative to the playlist file
const resolvedPath = path.join(payload[0], trimmed);
trackPaths.push(resolvedPath);
}
}
});
return [ trackPaths, trackArt ];
},
buildM3U(filePath, tracks, comments)
{
/*
#EXTM3U
#EXTINF:0,01 Piano Concerto No. 2, Second Movement.mp3
/home/pi/Music/Various Classical Artists/Classic Fm Hall of Fame- The Silver Edition [Disc 1]/01 Piano Concerto No. 2, Second Movement.mp3
*/
var playlistEntries = "#EXTM3U\n";
//iterate through the tracks with an index that is used to access the corresponding entry in comments
for (let i = 0; i < tracks.length; i++) {
playlistEntries += `#EXTINF:0,${comments[i]}\n`
playlistEntries += `${tracks[i]}\n`
}
fs.writeFileSync(filePath, playlistEntries);
},
async getMetaData(identifier, payload)
{
/*
* Reads metadata from a media file using music-metadata library.
* @param {string} payload - The path to the media file.
* if it is a local file uses parsefile
* if it is a URL uses music-metadata
*/
//console.log(payload);
const globalIdentifier = identifier;
const missingMetaData = {
title: "Unknown Title", artist: "Unknown Artist", album: "Unknown Album", track: { name: "Unknown Track", no: 1 } };
if (!payload) { return; }
let common = missingMetaData;
if (payload.toLowerCase().startsWith('http')) {
(async () => {
const { parseWebStream } = await import('music-metadata');
try {
// Fetch the audio file
const response = await fetch(payload);
// Extract the Content-Length header and convert it to a number
const contentLength = response.headers.get('Content-Length');
if (!contentLength)
{
missingMetaData.title = payload;
}
else
{
const size = contentLength ? parseInt(contentLength, 10) : undefined;
// Parse the metadata from the web stream
const metadata = await parseWebStream(response.body, {
mimeType: response.headers.get('Content-Type'),
size // Important to pass the content-length
});
common = metadata.common || missingMetaData;
}
this.sendSocketNotification(globalIdentifier +">"+ "METADATA_RESULT", { common });
}
catch (error)
{
console.error('Error parsing metadata:', error.message);
this.sendSocketNotification(globalIdentifier +">"+ "METADATA_RESULT", { common: missingMetaData });
}
})();
}
else {
(async () => {
const { parseFile } = await import('music-metadata');
try {
const metadata = await parseFile(payload);
const common = metadata.common || missingMetaData;
this.sendSocketNotification(globalIdentifier +">"+ "METADATA_RESULT", { common });
} catch (error) {
console.error('Error reading metadata:', error.message);
this.sendSocketNotification(globalIdentifier +">"+ "METADATA_RESULT", { common: missingMetaData });
}
})();
}
},
});