Repository navigation
Expand file tree
/
Copy pathnode_helper.js
More file actions
executable file
·814 lines (765 loc) · 30.5 KB
/
Copy pathnode_helper.js
File metadata and controls
executable file
·814 lines (765 loc) · 30.5 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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
/*
* node_helper.js
*
* MagicMirror²
* Module: MMM-BackgroundSlideshow
*
* MagicMirror² By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*
* Module MMM-BackgroundSlideshow By Darick Carpenter
* MIT Licensed.
*/
const FileSystemImageSlideshow = require('node:fs');
const {createHash} = require('node:crypto');
const {exec} = require('node:child_process');
const NodeHelper = require('node_helper');
const Log = require('../../js/logger.js');
const fs = require('fs');
const path = require('path');
const imageRoute = '/modules/MMM-BackgroundSlideshow/image';
/*
* sharp is only needed for resizeImages. Load it on first use, so the module still works
* (without resizing) on systems where sharp's native binaries cannot be loaded,
* e.g. 32-bit Raspberry Pi OS older than Bookworm.
*/
let sharp = null;
let sharpLoadFailed = false;
const loadSharp = () => {
if (!sharp && !sharpLoadFailed) {
try {
sharp = require('sharp');
} catch (error) {
sharpLoadFailed = true;
Log.error('[MMM-BackgroundSlideshow] resizeImages is set, but the "sharp" module could not be loaded, so images are shown in their original size:', error.message);
}
}
return sharp;
};
// OpenStreetMap places whose name makes a poor photo caption (roads, shops, offices, parking, ...)
const OSM_SKIP_NAME_CATEGORIES = ['highway', 'aeroway', 'railway', 'office', 'shop'];
const OSM_SKIP_NAME_TYPES = ['fast_food', 'parking', 'parking_entrance', 'parking_space', 'fuel', 'house', 'memorial'];
const OSM_MAX_POSITION_LENGTH = 40;
// / ? FIXME const {json} = require('node:stream/consumers');
/*
* Find the Google Takeout sidecar JSON of an image among the files of its directory.
* Takeout names the JSON after the original file name including its extension, with a varying
* (sometimes truncated) suffix, e.g. 'p2200111.jpg.json' or 'p2200111.jpg.supplemental-metadata.json'.
* When an album contains two images with the same name, the second one is saved as
* 'p2200111(1).jpg' and its JSON as 'p2200111.jpg.supplemental-metadata(1).json' (or 'p2200111.jpg(1).json'),
* so the counter has to sit right before '.json' exactly when the image name is numbered.
*/
const findTakeoutJsonFile = (imageFilename, files) => {
const extension = path.extname(imageFilename);
const stem = path.basename(imageFilename, extension);
const find = (originalStem, counter) => {
const originalFilename = `${originalStem}${extension}`;
const [jsonFile] = files
.filter((file) => {
if (!file.startsWith(originalFilename) || !file.toLowerCase().endsWith('.json')) {
return false;
}
let suffix = file.slice(originalFilename.length, -'.json'.length);
if (counter) {
if (!suffix.endsWith(counter)) {
return false;
}
suffix = suffix.slice(0, -counter.length);
} else if ((/\(\d+\)$/u).test(suffix)) {
// this is the JSON of a numbered duplicate
return false;
}
return suffix === '' || suffix.startsWith('.');
})
.sort();
// fall back to a JSON named after the file name without extension, e.g. 'p2200111(1).json'
return jsonFile ?? files.find((file) => file.toLowerCase() === `${originalStem}${counter}.json`.toLowerCase());
};
const match = stem.match(/^(?<originalStem>.+?)\s*(?<counter>\(\d+\))$/u);
// a numbered image is most likely a duplicate, but its name may also contain the counter itself
if (match) {
const jsonFile = find(match.groups.originalStem, match.groups.counter);
if (jsonFile) {
return jsonFile;
}
}
return find(stem, '');
};
// 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.imageList = [];
this.imageFiles = new Map();
this.alreadyShownSet = new Set();
this.index = 0;
this.timer = null;
this.expressApp.get(`${imageRoute}/:imageId`, (request, response) => {
this.sendImage(request, response);
});
self = this;
},
getImageId (imagePath) {
return createHash('sha256')
.update(imagePath)
.digest('hex');
},
getImageUrl (image) {
const imageId = this.getImageId(image.path);
const imageVersion = this.config.resizeImages
? `${image.modified}-${this.config.maxWidth}x${this.config.maxHeight}`
: `${image.modified}-original`;
this.imageFiles.set(imageId, image.path);
return `${imageRoute}/${imageId}?v=${imageVersion}`;
},
sendImage (request, response) {
const imagePath = this.imageFiles.get(request.params.imageId);
if (!imagePath) {
response.sendStatus(404);
return;
}
response.set('Cache-Control', 'private, max-age=3600');
if (this.config.resizeImages && loadSharp()) {
response.type('image/jpeg');
sharp(imagePath)
.rotate()
.resize({
width: parseInt(this.config.maxWidth, 10),
height: parseInt(this.config.maxHeight, 10),
fit: 'inside',
})
.keepMetadata()
.jpeg({quality: 80})
.on('error', (error) => {
Log.error(`Error serving image "${imagePath}":`, error);
if (response.headersSent) {
response.destroy(error);
} else {
response.sendStatus(500);
}
})
.pipe(response);
return;
}
response.sendFile(path.resolve(imagePath));
},
// 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;
},
shuffleImagesLoopFolders (filePaths) {
Log.log('shuffleImagesLoopFolders = true!');
Log.debug(`filePaths: \n${filePaths.map((img) => `${img.path}\n`)}`);
const groupedByFolder = new Map();
for (const imgobject of filePaths) {
const parts = imgobject.path.split('/');
const folder = parts[parts.length - 2]; // or use the config.imagePaths?
if (!groupedByFolder.has(folder)) {
groupedByFolder.set(folder, []);
}
groupedByFolder.get(folder).push(imgobject);
}
// find subfolder with max amount of images:
let maxLength = 0;
for (const imageArray of groupedByFolder.values()) {
maxLength = Math.max(maxLength, imageArray.length);
}
// shuffle all subfolders individually
for (const folderPaths of groupedByFolder.values()) {
this.shuffleArray(folderPaths);
}
const result = [];
const folderKeys = Array.from(groupedByFolder.keys());
// map of pointers to keep track of image index for subfolders
const pointers = new Map(folderKeys.map((key) => [key, 0]));
let lastPickedFolder = null;
for (let i = 0; i < maxLength; i++) {
// re-shuffle subfolders so that the order is not the same
const pickableFolders = this.shuffleArray(folderKeys);
if (pickableFolders[0] === lastPickedFolder) {
// simply swap first/last if lastpickedfolder happened to be first
[pickableFolders[0], pickableFolders[pickableFolders.length - 1]] =
[pickableFolders[pickableFolders.length - 1], pickableFolders[0]];
}
for (const nextFolder of pickableFolders) {
const imagePointer = pointers.get(nextFolder);
const image = groupedByFolder.get(nextFolder)[imagePointer];
result.push(image);
if (imagePointer + 1 === groupedByFolder.get(nextFolder).length) {
// current folder has run out of images, restart this folder
this.shuffleArray(groupedByFolder.get(nextFolder));
pointers.set(nextFolder, 0);
} else {
pointers.set(nextFolder, imagePointer + 1);
}
lastPickedFolder = nextFolder; // we dont want the same folder in a row
}
}
return result;
},
// 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;
switch (sortBy) {
case 'created':
Log.debug('Sorting by created date...');
sortedList = imageList.sort(this.sortByCreated);
break;
case 'modified':
Log.debug('Sorting by modified date...');
sortedList = imageList.sort(this.sortByModified);
break;
default:
Log.debug('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.debug('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);
},
excludedFiles (currentDir) {
try {
const excludedFile = FileSystemImageSlideshow.readFileSync(`${currentDir}/excludeImages.txt`, 'utf8');
const listOfExcludedFiles = excludedFile.split(/\r?\n/u);
Log.info(`Found excluded images list: in dir: ${currentDir} containing: ${listOfExcludedFiles.length} files`);
return listOfExcludedFiles;
} catch {
Log.debug('No "excludeImages.txt" in current folder.');
return [];
}
},
isExcluded (filename, excludedImagesList) {
if (excludedImagesList.includes(filename.replace(/\.[a-zA-Z]{3,4}$/u, ''))) {
Log.info(`${filename} is excluded in excludedImages.txt!`);
return true;
}
return false;
},
readEntireShownFile () {
const filepath = 'modules/MMM-BackgroundSlideshow/filesShownTracker.txt';
try {
const filesShown = FileSystemImageSlideshow.readFileSync(filepath, 'utf8');
const listOfShownFiles = filesShown.split(/\r?\n/u).filter((line) => line.trim() !== '');
Log.info(`Found filesShownTracker: in path: ${filepath} containing: ${listOfShownFiles.length} files`);
return new Set(listOfShownFiles);
} catch {
Log.info(`Error reading filesShownTracker: in path: ${filepath}`);
return new Set();
}
},
addImageToShown (imgPath) {
self.alreadyShownSet.add(imgPath);
const filePath = 'modules/MMM-BackgroundSlideshow/filesShownTracker.txt';
if (FileSystemImageSlideshow.existsSync(filePath)) {
FileSystemImageSlideshow.appendFileSync(filePath, `${imgPath}\n`);
} else {
FileSystemImageSlideshow.writeFileSync(filePath, `${imgPath}\n`, {flag: 'wx'});
}
},
resetShownImagesFile () {
try {
FileSystemImageSlideshow.writeFileSync('modules/MMM-BackgroundSlideshow/filesShownTracker.txt', '', 'utf8');
} catch (err) {
Log.error('Error writing empty filesShownTracker.txt', err);
}
},
// returns the paths of the most recently shown half of the images of the cycle that just ended
getRecentlyShownPaths () {
const shownPaths = this.config.showAllImagesBeforeRestart
? Array.from(this.readEntireShownFile())
: this.imageList.slice(0, this.index).map((image) => image.path);
return new Set(shownPaths.slice(-Math.floor(shownPaths.length / 2)));
},
// moves recently shown images to the end of a freshly shuffled list, keeping the random order
// within both parts, so an image is not shown again right after a new cycle has started
moveRecentlyShownToEnd (imageList, recentlyShownPaths) {
if (!recentlyShownPaths.size) {
return imageList;
}
const notRecent = [];
const recent = [];
for (const image of imageList) {
if (recentlyShownPaths.has(image.path)) {
recent.push(image);
} else {
notRecent.push(image);
}
}
Log.info(`Moved ${recent.length} recently shown files to the end of the new cycle`);
return notRecent.concat(recent);
},
// gathers the image list
gatherImageList (config, sendNotification, recentlyShownPaths = new Set()) {
// 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 = [];
if (config.showAllImagesBeforeRestart) {
this.alreadyShownSet = this.readEntireShownFile();
}
for (let i = 0; i < config.imagePaths.length; i++) {
const excludedImagesList = this.excludedFiles(config.imagePaths[i]);
this.getFiles(config.imagePaths[i], this.imageList, excludedImagesList, config);
}
const imageListToUse = config.showAllImagesBeforeRestart
? this.imageList.filter((image) => !this.alreadyShownSet.has(image.path))
: this.imageList;
Log.info(`Skipped ${this.imageList.length - imageListToUse.length} files since already seen!`);
let finalImageList;
if (config.randomizeImagesLoopFolders) {
finalImageList = this.shuffleImagesLoopFolders(imageListToUse);
} else if (config.randomizeImageOrder) {
finalImageList = this.shuffleArray(imageListToUse);
if (config.avoidRepeatsAcrossCycles) {
finalImageList = this.moveRecentlyShownToEnd(finalImageList, recentlyShownPaths);
}
} else {
finalImageList = this.sortImageList(
imageListToUse,
config.sortImagesBy,
config.sortImagesDescending
);
}
this.imageList = finalImageList;
Log.info(`${this.imageList.length} files found`);
Log.log(`${this.imageList.map((img) => `${img.path}\n`)}`);
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
const recentlyShownPaths = this.config.avoidRepeatsAcrossCycles
? this.getRecentlyShownPaths()
: new Set();
if (this.config.showAllImagesBeforeRestart) {
this.resetShownImagesFile();
}
this.gatherImageList(this.config, false, recentlyShownPaths);
}
//
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(`Reading path "${image.path}"`);
self = this;
const imageDirectory = path.dirname(image.path);
const imageFilename = path.basename(image.path);
// get infos from Google TakeOut JSON file
let jsonFilePath = '';
let json_metadata = {};
try {
if (fs.existsSync(imageDirectory)) {
const files = fs.readdirSync(imageDirectory);
const jsonFilename = findTakeoutJsonFile(imageFilename, files);
if (jsonFilename) {
jsonFilePath = path.join(imageDirectory, jsonFilename);
Log.log('JSON:', jsonFilePath);
const jsonData = fs.readFileSync(jsonFilePath, 'utf8');
json_metadata = JSON.parse(jsonData);
}
} else {
Log.warn('Directory does not exist:', imageDirectory);
}
} catch (error) {
Log.error('Error reading directory ', imageDirectory, ':', error);
}
const metadata = {};
let latitude = null;
let longitude = null;
if (jsonFilePath !== '') {
if (
json_metadata.description &&
!this.config.excludeDescriptionsRegexps?.some((regexp) => new RegExp(regexp).test(json_metadata.description))
) {
Log.debug('Image description:', json_metadata.description);
metadata.description = json_metadata.description;
}
if (json_metadata.photoTakenTime && json_metadata.photoTakenTime.timestamp) {
let {timestamp} = json_metadata.photoTakenTime;
// Convert to number and handle both seconds and milliseconds timestamps
timestamp = typeof timestamp === 'string'
? parseFloat(timestamp)
: timestamp;
// If timestamp is in seconds (typical for Unix timestamps), convert to milliseconds
if (timestamp < 10000000000) {
timestamp *= 1000;
}
const dateTime = new Date(timestamp);
metadata.photoTakenTime = dateTime.toISOString().slice(0, 16)
.replace('T', ' ');
Log.debug('Photo taken time:', metadata.photoTakenTime, json_metadata.photoTakenTime.formatted);
} else if (json_metadata.creationTime && json_metadata.creationTime.timestamp) {
let {timestamp} = json_metadata.creationTime;
// Convert to number and handle both seconds and milliseconds timestamps
timestamp = typeof timestamp === 'string'
? parseFloat(timestamp)
: timestamp;
// If timestamp is in seconds (typical for Unix timestamps), convert to milliseconds
if (timestamp < 10000000000) {
timestamp *= 1000;
}
const dateTime = new Date(timestamp);
metadata.creationTime = dateTime.toISOString().slice(0, 16)
.replace('T', ' ');
Log.debug('Photo creation time:', metadata.creationTime, json_metadata.creationTime.formatted);
}
if (json_metadata.geoDataExif && json_metadata.geoDataExif.latitude && json_metadata.geoDataExif.longitude) {
Log.debug('Image Exif position:', json_metadata.geoDataExif.longitude, json_metadata.geoDataExif.latitude);
latitude = json_metadata.geoDataExif.latitude;
longitude = json_metadata.geoDataExif.longitude;
} else if (json_metadata.geoData && json_metadata.geoData.latitude && json_metadata.geoData.longitude) {
Log.debug('Image position:', json_metadata.geoData.longitude, json_metadata.geoData.latitude);
latitude = json_metadata.geoData.latitude;
longitude = json_metadata.geoData.longitude;
}
if (json_metadata.url) {
Log.debug('Image URL:', json_metadata.url);
metadata.url = json_metadata.url;
}
// now let us search the friendly position name
if (latitude && longitude) {
const address = this.getAddressFromCoordinates(latitude, longitude);
if (address) {
metadata.position = address;
// clean the first part of address if its a street number (numbers + space, or numbers+comma+space, or numbers + bis,ter + space)
metadata.position = metadata.position.replace(/^[0-9]+(,[ ]|[ ]|(bis|ter)[ ])+/u, '');
// clean the first part of address if its a "Plus Code Google" (4 alphanum + space + 3 alphanum + space)
metadata.position = metadata.position.replace(/^[A-Za-z0-9]{4}[ \+][A-Za-z0-9]+[ ]+/u, '');
} else {
metadata.position = `${Math.round(latitude * 100) / 100}, ${Math.round(longitude * 100) / 100}`;
}
}
}
const returnPayload = {
identifier: self.config.identifier,
path: image.path,
data: this.getImageUrl(image),
index: self.index,
total: self.imageList.length,
metadata
};
self.sendSocketNotification(
'BACKGROUNDSLIDESHOW_DISPLAY_IMAGE',
returnPayload
);
// (re)set the update timer
this.startOrRestartTimer();
if (this.config.showAllImagesBeforeRestart) {
this.addImageToShown(image.path);
}
},
getAddressFromCoordinates (latitude, longitude) {
// Read the address cache from file if it exists
let addressCache = {};
try {
const cacheData = fs.readFileSync(this.config.addressCacheFile, 'utf8');
addressCache = JSON.parse(cacheData);
} catch (error) {
// File doesn't exist or is invalid, use empty cache
addressCache = {};
}
// Check if the address is already cached
const cacheKey = `${latitude},${longitude}`;
if (addressCache[cacheKey]) {
Log.log('Address found in cache:', addressCache[cacheKey]);
return addressCache[cacheKey];
}
// If not cached, make a request to Google Maps Geocoding API
const mapsApiKey = this.config.googleMapsApiKey || '';
if (mapsApiKey === '') {
Log.log('No Google Maps API key provided.');
return null;
}
const mapsApiUrl = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${mapsApiKey}`;
const https = require('https');
https.get(mapsApiUrl, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const geoData = JSON.parse(data);
if (geoData.status === 'OK' && geoData.results.length > 0) {
const address = geoData.results[0].formatted_address;
Log.log('Resolved address with Google Maps API:', address);
// Update the address cache and write it back to file
addressCache[`${latitude},${longitude}`] = address;
fs.writeFileSync(this.config.addressCacheFile, JSON.stringify(addressCache), 'utf8');
return address;
}
Log.debug('No address found for the given coordinates.');
} catch (error) {
Log.error('Error parsing geocode response:', error);
}
});
});
return null;
},
// Resolve a place name for EXIF GPS coordinates with OpenStreetMap Nominatim (no API key needed).
// lat/lon arrive rounded to 3 decimals (~100 m), which is also the cache key. The cache file is
// re-read on every lookup, so hand-edited names apply without a restart.
async getPositionFromOpenStreetMap (lat, lon) {
const cacheKey = `${lat},${lon}`;
const cache = this.readOpenStreetMapCache();
if (cache[cacheKey]) {
return cache[cacheKey];
}
try {
const language = encodeURIComponent(this.config.openStreetMapLanguage || 'en');
const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&accept-language=${language}&lat=${lat}&lon=${lon}`;
const response = await fetch(url, {
headers: {'User-Agent': 'MMM-BackgroundSlideshow (MagicMirror module; https://github.com/darickc/MMM-BackgroundSlideshow)'}
});
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
const position = this.formatOpenStreetMapPlace(await response.json());
if (position) {
const freshCache = this.readOpenStreetMapCache();
freshCache[cacheKey] = position;
fs.writeFileSync(this.config.openStreetMapCacheFile, JSON.stringify(freshCache, null, 2), 'utf8');
Log.debug(`OpenStreetMap position for ${cacheKey}: ${position}`);
}
return position;
} catch (error) {
Log.warn(`OpenStreetMap lookup failed for ${cacheKey}: ${error.message}`);
return null;
}
},
readOpenStreetMapCache () {
try {
return JSON.parse(fs.readFileSync(this.config.openStreetMapCacheFile, 'utf8'));
} catch {
return {};
}
},
// Landmark name if there is a meaningful one, otherwise "neighbourhood/street, city".
// Never shows house numbers or cuts a name mid-word.
formatOpenStreetMapPlace (data) {
const address = data.address || {};
const locality = address.city || address.town || address.village || address.suburb ||
address.hamlet || address.county || address.state || '';
if (data.name && !OSM_SKIP_NAME_CATEGORIES.includes(data.category) && !OSM_SKIP_NAME_TYPES.includes(data.type)) {
return data.name;
}
const area = address.neighbourhood || address.quarter || address.suburb || address.road || '';
const parts = [area, locality].filter((part, i, arr) => part && arr.indexOf(part) === i);
if (parts.length > 0) {
const label = parts.join(', ');
return label.length > OSM_MAX_POSITION_LENGTH && locality
? locality
: label;
}
// Fall back to the first parts of the full address, cut at a comma
return (data.display_name || '').split(', ')
.slice(0, 2)
.join(', ');
},
// stop timer if it's running
stopTimer () {
if (this.timer) {
Log.debug('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('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();
},
// visitedDirectories holds the real paths of the directories already scanned, so symbolic links
// pointing to a parent directory (or to the same directory twice) do not cause endless loops or duplicates
getFiles (imagePath, imageList, excludedImagesList, config, visitedDirectories = new Set([FileSystemImageSlideshow.realpathSync(imagePath)])) {
// handle symbolic links last, so a directory reached directly and through a link is listed by its real path
const contents = FileSystemImageSlideshow.readdirSync(imagePath, {withFileTypes: true})
.sort((a, b) => Number(a.isSymbolicLink()) - Number(b.isSymbolicLink()))
.map((entry) => entry.name);
Log.info(`Reading directory "${imagePath}" for images, found ${contents.length} files and directories`);
for (let i = 0; i < contents.length; i++) {
if (this.excludePaths.has(contents[i])) {
continue;
}
const currentItem = `${imagePath}/${contents[i]}`;
let stats;
try {
// statSync follows symbolic links, so linked directories and images are included
stats = FileSystemImageSlideshow.statSync(currentItem);
} catch (error) {
Log.warn(`Skipping "${currentItem}": ${error.message}`);
continue;
}
if (stats.isDirectory() && config.recursiveSubDirectories) {
const realPath = FileSystemImageSlideshow.realpathSync(currentItem);
if (visitedDirectories.has(realPath)) {
Log.info(`Skipping "${currentItem}", directory was already scanned`);
continue;
}
visitedDirectories.add(realPath);
this.getFiles(currentItem, imageList, this.excludedFiles(currentItem), config, visitedDirectories);
} else if (stats.isFile()) {
const isValidImageFileExtension = this.checkValidImageFileExtension(currentItem);
const isExcluded = this.isExcluded(contents[i], excludedImagesList);
if (isValidImageFileExtension && !isExcluded) {
imageList.push({
path: currentItem,
created: stats.ctimeMs,
modified: stats.mtimeMs
});
}
}
}
},
// Function to signal a photo as not interesting
signalPhoto (payload) {
// todo
// savoir quelle image est affichée actuellement
// récupérer l'url de l'image courante, et le filename
Log.log(`Signaling photo: ${payload.path} on URL: ${this.config.photoSignalUrl}`);
// Log.log(`metadata: ${JSON.stringify(payload.metadata)}`);
if (!payload.metadata || !payload.metadata.url) {
Log.error('No photo URL found in metadata, cannot signal photo');
// FIXME je ne comprends pas pourquoi parfois l'URL n'est pas là
return;
}
const formData = new FormData();
formData.append('photoUrl', payload.metadata.url || '');
formData.append('filename', payload.metadata.displayedName || '');
formData.append('creationTime', payload.metadata.displayedTime || '');
fetch(this.config.photoSignalUrl, {
method: 'POST',
body: formData
})
.then((response) => {
Log.log('Success signaling photo');
})
.catch((error) => {
Log.error('Error signaling photo', error);
});
},
// subclass socketNotificationReceived, received notification from module
socketNotificationReceived (notification, payload) {
if (notification === 'BACKGROUNDSLIDESHOW_REGISTER_CONFIG') {
const config = payload;
this.imageFiles.clear();
// 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]}`,
() => {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PLAY', null);
Log.info('mw video done');
}
);
} else if (notification === 'BACKGROUNDSLIDESHOW_NEXT_IMAGE') {
Log.debug('BACKGROUNDSLIDESHOW_NEXT_IMAGE');
this.getNextImage();
} else if (notification === 'BACKGROUNDSLIDESHOW_PREV_IMAGE') {
Log.debug('BACKGROUNDSLIDESHOW_PREV_IMAGE');
this.getPrevImage();
} else if (notification === 'BACKGROUNDSLIDESHOW_PAUSE') {
this.stopTimer();
} else if (notification === 'BACKGROUNDSLIDESHOW_PLAY') {
this.startOrRestartTimer();
} else if (notification === 'BACKGROUNDSLIDESHOW_SIGNAL_PHOTO_HANDLER') {
this.signalPhoto(payload);
} else if (notification === 'BACKGROUNDSLIDESHOW_GEOCODE') {
this.getPositionFromOpenStreetMap(payload.lat, payload.lon).then((position) => {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_GEOCODE_RESULT', {
path: payload.path,
position
});
});
}
}
});