forked from darickc/MMM-BackgroundSlideshow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
executable file
·341 lines (310 loc) · 10.3 KB
/
node_helper.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
/*
* node_helper.js
*
* MagicMirror²
* Module: MMM-BackgroundSlideshow
*
* MagicMirror² By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*
* Module MMM-BackgroundSlideshow By Darick Carpenter
* MIT Licensed.
*/
// call in the required classes
const NodeHelper = require('node_helper');
const FileSystemImageSlideshow = require('fs');
const {exec} = require('child_process');
const express = require('express');
const Log = require('../../js/logger.js');
const basePath = '/images/';
const sharp = require('sharp');
const path = require('path');
// the main module helper create
module.exports = NodeHelper.create({
// subclass start method, clears the initial config array
start () {
this.excludePaths = new Set();
this.validImageFileExtensions = new Set();
this.expressInstance = this.expressApp;
this.imageList = [];
this.index = 0;
this.timer = null;
self = this;
},
// shuffles an array at random and returns it
shuffleArray (array) {
for (let i = array.length - 1; i > 0; i--) {
// j is a random index in [0, i].
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
},
// sort by filename attribute
sortByFilename (a, b) {
const aL = a.path.toLowerCase();
const bL = b.path.toLowerCase();
if (aL > bL) return 1;
return -1;
},
// sort by created attribute
sortByCreated (a, b) {
const aL = a.created;
const bL = b.created;
if (aL > bL) return 1;
return -1;
},
// sort by created attribute
sortByModified (a, b) {
const aL = a.modified;
const bL = b.modified;
if (aL > bL) return 1;
return -1;
},
sortImageList (imageList, sortBy, sortDescending) {
let sortedList = imageList;
switch (sortBy) {
case 'created':
// Log.log('Sorting by created date...');
sortedList = imageList.sort(this.sortByCreated);
break;
case 'modified':
// Log.log('Sorting by modified date...');
sortedList = imageList.sort(this.sortByModified);
break;
default:
// sort by name
// Log.log('Sorting by name...');
sortedList = imageList.sort(this.sortByFilename);
}
// If the user chose to sort in descending order then reverse the array
if (sortDescending === true) {
// Log.log('Reversing sort order...');
sortedList = sortedList.reverse();
}
return sortedList;
},
// checks there's a valid image file extension
checkValidImageFileExtension (filename) {
if (!filename.includes('.')) {
// No file extension.
return false;
}
const fileExtension = filename.split('.').pop()
.toLowerCase();
return this.validImageFileExtensions.has(fileExtension);
},
// gathers the image list
gatherImageList (config, sendNotification) {
// Invalid config. retrieve it again
if (typeof config === 'undefined' || !Object.hasOwn(Object(config), 'imagePaths')) {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_REGISTER_CONFIG');
return;
}
// create an empty main image list
this.imageList = [];
for (let i = 0; i < config.imagePaths.length; i++) {
this.getFiles(config.imagePaths[i], this.imageList, config);
}
this.imageList = config.randomizeImageOrder
? this.shuffleArray(this.imageList)
: this.sortImageList(
this.imageList,
config.sortImagesBy,
config.sortImagesDescending
);
Log.info(`BACKGROUNDSLIDESHOW: ${this.imageList.length} files found`);
this.index = 0;
// let other modules know about slideshow images
this.sendSocketNotification('BACKGROUNDSLIDESHOW_FILELIST', {
imageList: this.imageList
});
// build the return payload
const returnPayload = {
identifier: config.identifier
};
// signal ready
if (sendNotification) {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_READY', returnPayload);
}
},
getNextImage () {
if (!this.imageList.length || this.index >= this.imageList.length) {
// if there are no images or all the images have been displayed, try loading the images again
this.gatherImageList(this.config);
}
//
if (!this.imageList.length) {
// still no images, search again after 10 mins
setTimeout(() => {
this.getNextImage(this.config);
}, 600000);
return;
}
const image = this.imageList[this.index++];
Log.info(`BACKGROUNDSLIDESHOW: reading path "${image.path}"`);
self = this;
this.readFile(image.path, (data) => {
const returnPayload = {
identifier: self.config.identifier,
path: image.path,
data,
index: self.index,
total: self.imageList.length
};
self.sendSocketNotification(
'BACKGROUNDSLIDESHOW_DISPLAY_IMAGE',
returnPayload
);
});
// (re)set the update timer
this.startOrRestartTimer();
},
// stop timer if it's running
stopTimer () {
if (this.timer) {
Log.debug('BACKGROUNDSLIDESHOW: stopping update timer');
const it = this.timer;
this.timer = null;
clearTimeout(it);
}
},
// resume timer if it's not running; reset if it is
startOrRestartTimer () {
this.stopTimer();
Log.debug('BACKGROUNDSLIDESHOW: restarting update timer');
this.timer = setTimeout(() => {
self.getNextImage();
}, self.config?.slideshowSpeed || 10000);
},
getPrevImage () {
// imageIndex is incremented after displaying an image so -2 is needed to
// get to previous image index.
this.index -= 2;
// Case of first image, go to end of array.
if (this.index < 0) {
this.index = 0;
}
this.getNextImage();
},
resizeImage (input, callback) {
Log.log(`resizing image to max: ${this.config.maxWidth}x${this.config.maxHeight}`);
const transformer = sharp()
.rotate()
.resize({
width: parseInt(this.config.maxWidth, 10),
height: parseInt(this.config.maxHeight, 10),
fit: 'inside',
})
.keepMetadata()
.jpeg({quality: 80});
// Streama image data from file to transformation and finally to buffer
const outputStream = [];
FileSystemImageSlideshow.createReadStream(input)
.pipe(transformer) // Stream to Sharp för att resizea
.on('data', (chunk) => {
outputStream.push(chunk); // add chunks in a buffer array
})
.on('end', () => {
const buffer = Buffer.concat(outputStream);
callback(`data:image/jpg;base64, ${buffer.toString('base64')}`);
Log.log('resizing done!');
})
.on('error', (err) => {
Log.error('Error resizing image:', err);
});
},
readFile (filepath, callback) {
const ext = filepath.split('.').pop();
if (this.config.resizeImages) {
this.resizeImage(filepath, callback);
} else {
Log.log('resizeImages: false');
// const data = FileSystemImageSlideshow.readFileSync(filepath, { encoding: 'base64' });
// callback(`data:image/${ext};base64, ${data}`);
const chunks = [];
FileSystemImageSlideshow.createReadStream(filepath)
.on('data', (chunk) => {
chunks.push(chunk); // Samla chunkar av data
})
.on('end', () => {
const buffer = Buffer.concat(chunks);
callback(`data:image/${ext.slice(1)};base64, ${buffer.toString('base64')}`);
})
.on('error', (err) => {
Log.error('Error reading file:', err);
})
.on('close', () => {
Log.log('Stream closed.');
});
}
},
getFiles (imagePath, imageList, config) {
Log.info(`BACKGROUNDSLIDESHOW: Reading directory "${imagePath}" for images.`);
const contents = FileSystemImageSlideshow.readdirSync(imagePath);
for (let i = 0; i < contents.length; i++) {
if (this.excludePaths.has(contents[i])) {
continue;
}
const currentItem = `${imagePath}/${contents[i]}`;
const stats = FileSystemImageSlideshow.lstatSync(currentItem);
if (stats.isDirectory() && config.recursiveSubDirectories) {
this.getFiles(currentItem, imageList, config);
} else if (stats.isFile()) {
const isValidImageFileExtension =
this.checkValidImageFileExtension(currentItem);
if (isValidImageFileExtension) {
imageList.push({
path: currentItem,
created: stats.ctimeMs,
modified: stats.mtimeMs
});
}
}
}
},
// subclass socketNotificationReceived, received notification from module
socketNotificationReceived (notification, payload) {
if (notification === 'BACKGROUNDSLIDESHOW_REGISTER_CONFIG') {
const config = payload;
this.expressInstance.use(
basePath + config.imagePaths[0],
express.static(config.imagePaths[0], {maxAge: 3600000})
);
// Create set of excluded subdirectories.
this.excludePaths = new Set(config.excludePaths);
// Create set of valid image extensions.
const validExtensionsList = config.validImageFileExtensions
.toLowerCase()
.split(',');
this.validImageFileExtensions = new Set(validExtensionsList);
// Get the image list in a non-blocking way since large # of images would cause
// the MagicMirror startup banner to get stuck sometimes.
this.config = config;
setTimeout(() => {
this.gatherImageList(config, true);
this.getNextImage();
}, 200);
} else if (notification === 'BACKGROUNDSLIDESHOW_PLAY_VIDEO') {
Log.info('mw got BACKGROUNDSLIDESHOW_PLAY_VIDEO');
Log.info(`cmd line: omxplayer --win 0,0,1920,1080 --alpha 180 ${payload[0]}`);
exec(
`omxplayer --win 0,0,1920,1080 --alpha 180 ${payload[0]}`,
(e, stdout, stderr) => {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PLAY', null);
Log.info('mw video done');
}
);
} else if (notification === 'BACKGROUNDSLIDESHOW_NEXT_IMAGE') {
Log.info('BACKGROUNDSLIDESHOW_NEXT_IMAGE');
this.getNextImage();
} else if (notification === 'BACKGROUNDSLIDESHOW_PREV_IMAGE') {
Log.info('BACKGROUNDSLIDESHOW_PREV_IMAGE');
this.getPrevImage();
} else if (notification === 'BACKGROUNDSLIDESHOW_PAUSE') {
this.stopTimer();
} else if (notification === 'BACKGROUNDSLIDESHOW_PLAY') {
this.startOrRestartTimer();
}
}
});