Repository navigation
Expand file tree
/
Copy pathMMM-BackgroundSlideshow.js
More file actions
executable file
·913 lines (849 loc) · 34.3 KB
/
Copy pathMMM-BackgroundSlideshow.js
File metadata and controls
executable file
·913 lines (849 loc) · 34.3 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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
/*
* MMM-BackgroundSlideshow.js
*
* MagicMirror²
* Module: MMM-BackgroundSlideshow
*
* MagicMirror² By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*
* Module MMM-Slideshow By Darick Carpenter
* MIT Licensed.
*/
Module.register('MMM-BackgroundSlideshow', {
// Default module config.
defaults: {
// an array of strings, each is a path to a directory with images
imagePaths: ['modules/MMM-BackgroundSlideshow/exampleImages'],
// do not recurse into these subdirectory names when scanning.
excludePaths: ['@eaDir'],
// the speed at which to switch between images, in milliseconds
slideshowSpeed: 10 * 1000,
// if true randomize image order, otherwise use sortImagesBy and sortImagesDescending
randomizeImageOrder: false,
// if true will randomize the order of all images and then create a filelist so that the images will ordered to show one image from each subfolder before next image index is shown. Subfolders with fewer images will loop so that all subfolders will get equal amount of time in the spotlight
randomizeImagesLoopFolders: false,
// keeps track of shown images to make sure you have seen them all before an image is shown twice.
showAllImagesBeforeRestart: false,
// if true (and randomizeImageOrder is true), the images shown at the end of a cycle are moved to the end of the next cycle, so an image is not repeated right after a new cycle starts
avoidRepeatsAcrossCycles: false,
// how to sort images: name, random, created, modified
sortImagesBy: 'created',
// whether to sort in ascending (default) or descending order
sortImagesDescending: false,
// if false each path with be viewed separately in the order listed
recursiveSubDirectories: false,
// list of valid file extensions, separated by commas
validImageFileExtensions: 'bmp,jpg,jpeg,gif,png',
// show a panel containing information about the image currently displayed.
showImageInfo: false,
// a comma separated list of values to display: description, name, desc_name (description with fallback to name), date, position, imagecount
imageInfo: 'name, date, imagecount',
// moment.js format string used when displaying imageInfo date values
imageInfoDateFormat: 'dddd MMMM D, YYYY HH:mm',
// location of the info div
imageInfoLocation: 'bottomRight', // Other possibilities are: bottomLeft, topLeft, topRight
// transition speed from one image to the other, transitionImages must be true
transitionSpeed: '2s',
// show a progress bar indicating how long till the next image is displayed.
showProgressBar: false,
// the sizing of the background image
// cover: Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges
// contain: Resize the background image to make sure the image is fully visible
backgroundSize: 'cover', // cover or contain
// if true, shows a blurred copy of the image behind the main image to fill empty space
backgroundBlurEnabled: false,
// if backgroundSize contain, determine where to zoom the picture. Towards top, center or bottom
backgroundPosition: 'center', // Most useful options: "top" or "center" or "bottom"
// transition from one image to the other (may be a bit choppy on slower devices, or if the images are too big)
transitionImages: false,
// the gradient to make the text more visible
gradient: [
'rgba(0, 0, 0, 0.75) 0%',
'rgba(0, 0, 0, 0) 40%',
'rgba(0, 0, 0, 0) 80%',
'rgba(0, 0, 0, 0.75) 100%'
],
horizontalGradient: [
'rgba(0, 0, 0, 0.75) 0%',
'rgba(0, 0, 0, 0) 40%',
'rgba(0, 0, 0, 0) 80%',
'rgba(0, 0, 0, 0.75) 100%'
],
radialGradient: [
'rgba(0,0,0,0) 0%',
'rgba(0,0,0,0) 75%',
'rgba(0,0,0,0.25) 100%'
],
// the direction the gradient goes, vertical, horizontal, both or radial
gradientDirection: 'vertical',
// Whether to scroll larger pictures rather than cut them off
backgroundAnimationEnabled: false,
// How long the scrolling animation should take - if this is more than slideshowSpeed, then images do not scroll fully.
// If it is too fast, then the image may apear gittery. For best result, by default we match this to slideshowSpeed.
// For now, it is not documented and will default to match slideshowSpeed.
backgroundAnimationDuration: '1s',
// How many times to loop the scrolling back and forth. If the value is set to anything other than infinite, the
// scrolling will stop at some point since we reuse the same div1.
// For now, it is not documentd and is defaulted to infinite.
backgroundAnimationLoopCount: 'infinite',
// Transitions to use
transitions: [
'opacity',
'slideFromRight',
'slideFromLeft',
'slideFromTop',
'slideFromBottom',
'slideFromTopLeft',
'slideFromTopRight',
'slideFromBottomLeft',
'slideFromBottomRight',
'flipX',
'flipY'
],
transitionTimingFunction: 'cubic-bezier(.17,.67,.35,.96)',
animations: ['slide', 'zoomOut', 'zoomIn'],
changeImageOnResume: false,
resizeImages: false,
maxWidth: 1920,
maxHeight: 1080,
// remove the file extension from image name
imageInfoNoFileExt: false,
googleMapsApiKey: '', // for goecoding position
addressCacheFile: '', // to cache geocoding results
// look up a place name for photos with GPS in their EXIF data via OpenStreetMap (free, no API key)
useOpenStreetMap: false,
openStreetMapCacheFile: 'modules/MMM-BackgroundSlideshow/geoCache.json', // editable cache of place names
openStreetMapLanguage: 'en', // language for place names
photoSignalUrl: '', // URL to send photo's Google URL (found in json metadata)to a server to signal issues
// (for instance, bad pictures, , needs a backend)
excludeDescriptionsRegexps: [/uploaded with Flickr Uploader/u], // descriptions matching are not kept (array of regexps)
cleanImageName: false // remove all words (separated by spaces or /) that contain at least one number
},
// load function
start () {
// add identifier to the config
this.config.identifier = this.identifier;
// ensure file extensions are lower case
this.config.validImageFileExtensions =
this.config.validImageFileExtensions.toLowerCase();
// ensure image order is in lower case
this.config.sortImagesBy = this.config.sortImagesBy.toLowerCase();
// commented out since this was not doing anything
// set no error
// this.errorMessage = null;
// validate imageinfo property. This will make sure we have at least 1 valid value
if (this.config.showImageInfo) {
const validImageInfo = ['name', 'date', 'description', 'desc_name', 'desc_or_name', 'position', 'imagecount'];
// convert to lower case and split on commas and/or spaces, so we get an array back
// even if the user provided space separated values
const requestedImageInfo = String(this.config.imageInfo)
.toLowerCase()
.split(/[\s,]+/u)
.filter((n) => n);
const invalidImageInfo = requestedImageInfo.filter((n) => !validImageInfo.includes(n));
if (invalidImageInfo.length > 0) {
Log.warn(`[MMM-BackgroundSlideshow] ignoring invalid imageInfo value(s): ${invalidImageInfo.join(', ')}`);
}
this.config.imageInfo = requestedImageInfo.filter((n) => validImageInfo.includes(n));
if (this.config.imageInfo.length === 0) {
Log.warn('[MMM-BackgroundSlideshow] showImageInfo is set, but imageInfo does not have a valid value.');
// Use name as the default
this.config.imageInfo = ['name'];
}
}
if (!this.config.transitionImages) {
this.config.transitionSpeed = '0';
}
if (typeof this.config.transitions === 'string') {
this.config.transitions = this.config.transitions
.replace(/\s/gu, ',')
.split(',')
.filter((transition) => transition);
}
// Lets make sure the backgroundAnimation duration matches the slideShowSpeed unless it has been
// overriden
if (this.config.backgroundAnimationDuration === '1s') {
this.config.backgroundAnimationDuration = `${this.config.slideshowSpeed / 1000}s`;
}
// Chrome versions < 81 do not support EXIF orientation natively. A CSS transformation
// needs to be applied for the image to display correctly - see http://crbug.com/158753 .
this.browserSupportsExifOrientationNatively = CSS.supports('image-orientation: from-image');
this.playingVideo = false;
},
getScripts () {
return [
`modules/${this.name}/node_modules/exif-js/exif.js`,
'moment.js'
];
},
getStyles () {
// the css contains the make grayscale code
return ['BackgroundSlideshow.css'];
},
getTranslations () {
return {
en: 'translations/en.json',
fr: 'translations/fr.json',
de: 'translations/de.json',
};
},
updateImageListWithArray (urls) {
this.imageList = urls.splice(0);
this.imageIndex = 0;
this.updateImage();
if (
!this.playingVideo &&
(this.timer || this.savedImages && this.savedImages.length === 0)
) {
// Restart timer only if timer was already running
this.resume();
}
},
// Setup receiver for global notifications (other modules etc)
// Use for example with MMM-Remote-Control API: https://github.com/Jopyth/MMM-Remote-Control/tree/master/API
// to change image from buttons or curl:
// curl http://[your ip address]:8080/api/notification/BACKGROUNDSLIDESHOW_PREVIOUS or NEXT
// make sure to set address: "0.0.0.0", and secureEndpoints: false (or setup security according to readme!)
notificationReceived (notification, payload) {
if (notification === 'BACKGROUNDSLIDESHOW_NEXT') {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_NEXT_IMAGE');
} else if (notification === 'BACKGROUNDSLIDESHOW_PREVIOUS') { // was PREV, and did not worked
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PREV_IMAGE');
} else if (notification === 'BACKGROUNDSLIDESHOW_PAUSE') {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PAUSE');
this.sendNotification('SHOW_ALERT', {
title: this.translate('NOTIFICATIONS_TITLE'),
type: 'notification',
message: this.translate('PAUSED'),
timer: 5000
});
} else if (notification === 'BACKGROUNDSLIDESHOW_PLAY') {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PLAY');
} else if (notification === 'BACKGROUNDSLIDESHOW_SIGNAL_PHOTO') {
this.sendSocketNotification(
'BACKGROUNDSLIDESHOW_SIGNAL_PHOTO_HANDLER',
this.currentImageInfo
);
this.sendNotification('SHOW_ALERT', {
title: this.translate('NOTIFICATIONS_TITLE'),
message: this.translate('SIGNAL_PHOTO'),
imageFA: 'exclamation-triangle', // seulement pour les alertes
timer: 5000
});
} else if (notification === 'BACKGROUNDSLIDESHOW_UPDATE_IMAGE_LIST') {
this.imageIndex = -1;
this.updateImageList();
this.updateImage();
} else if (notification === 'BACKGROUNDSLIDESHOW_URL') {
if (payload && payload.url) {
// Stop timer.
if (payload.resume) {
if (this.timer) {
// Restart timer only if timer was already running
this.resume();
}
} else {
this.suspend();
}
this.updateImage(false, payload.url);
}
} else if (notification === 'BACKGROUNDSLIDESHOW_URLS') {
Log.log(`[MMM-BackgroundSlideshow] Notification Received: BACKGROUNDSLIDESHOW_URLS. Payload: ${JSON.stringify(payload)}`);
if (payload && payload.urls && payload.urls.length) {
// check if image list has been saved. If not, this is the first time the notification is received
// save the image list and index.
if (this.savedImages) {
// check if there the sent urls are the same, or different.
const temp = [...new Set([...payload.urls, ...this.imageList])];
// if they are the same length, then they haven't changed, so don't do anything.
if (temp.length !== payload.urls.length) {
this.updateImageListWithArray(payload.urls);
}
} else {
this.savedImages = this.imageList;
this.savedIndex = this.imageIndex;
this.updateImageListWithArray(payload.urls);
}
// no urls sent, see if there is saved data.
} else if (this.savedImages) {
this.imageList = this.savedImages;
this.imageIndex = this.savedIndex;
this.savedImages = null;
this.savedIndex = null;
this.updateImage();
if (this.timer && !this.playingVideo) {
// Restart timer only if timer was already running
this.resume();
}
}
}
},
// the socket handler from node_helper.js
socketNotificationReceived (notification, payload) {
// if an update was received
// check this is for this module based on the woeid
if (notification === 'BACKGROUNDSLIDESHOW_READY') {
// // Log.info('[MMM-BackgroundSlideshow] Returning Images, payload:' + JSON.stringify(payload));
// // set the image list
// if (this.savedImages) {
// this.savedImages = payload.imageList;
// this.savedIndex = 0;
// } else {
// this.imageList = payload.imageList;
// // if image list actually contains images
// // set loaded flag to true and update dom
// if (this.imageList.length > 0) {
// this.updateImage(); //Added to show the image at least once, but not change it within this.resume()
// if (!this.playingVideo) {
// this.resume();
// }
// }
// }
if (payload.identifier === this.identifier) {
if (!this.playingVideo) {
this.resume();
}
}
} else if (notification === 'BACKGROUNDSLIDESHOW_REGISTER_CONFIG') {
// Update config in backend
this.updateImageList();
} else if (notification === 'BACKGROUNDSLIDESHOW_PLAY') {
// Change to next image and start timer.
this.updateImage();
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PLAY');
if (!this.playingVideo) {
this.resume();
}
} else if (notification === 'BACKGROUNDSLIDESHOW_DISPLAY_IMAGE') {
// check this is for this module based on the woeid
if (payload.identifier === this.identifier) {
this.displayImage(payload);
}
} else if (notification === 'BACKGROUNDSLIDESHOW_GEOCODE_RESULT') {
this.showPositionResult(payload);
} else if (notification === 'BACKGROUNDSLIDESHOW_FILELIST') {
// bubble up filelist notifications to other modules
this.sendNotification('BACKGROUNDSLIDESHOW_FILELIST', payload);
} else if (notification === 'BACKGROUNDSLIDESHOW_IMAGE_UPDATE') {
Log.log('[MMM-BackgroundSlideshow] Changing Background');
this.suspend();
this.updateImage();
if (!this.playingVideo) {
this.resume();
}
} else if (notification === 'BACKGROUNDSLIDESHOW_NEXT') {
// Change to next image
this.updateImage();
if (this.timer && !this.playingVideo) {
// Restart timer only if timer was already running
this.resume();
}
} else if (notification === 'BACKGROUNDSLIDESHOW_PREVIOUS') {
// Change to previous image
this.updateImage(/* skipToPrevious= */ true);
if (this.timer && !this.playingVideo) {
// Restart timer only if timer was already running
this.resume();
}
} else if (notification === 'BACKGROUNDSLIDESHOW_PAUSE') {
// Stop timer.
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PAUSE');
}
},
// Override dom generator.
getDom () {
const wrapper = document.createElement('div');
this.imagesDiv = document.createElement('div');
this.imagesDiv.className = 'images';
wrapper.appendChild(this.imagesDiv);
if (
this.config.gradientDirection === 'vertical' ||
this.config.gradientDirection === 'both'
) {
this.createGradientDiv('bottom', this.config.gradient, wrapper);
}
if (
this.config.gradientDirection === 'horizontal' ||
this.config.gradientDirection === 'both'
) {
this.createGradientDiv('right', this.config.horizontalGradient, wrapper);
}
if (
this.config.gradientDirection === 'radial'
) {
this.createRadialGradientDiv('ellipse at center', this.config.radialGradient, wrapper);
}
if (this.config.showImageInfo) {
this.imageInfoDiv = this.createImageInfoDiv(wrapper);
}
if (this.config.showProgressBar) {
this.createProgressbarDiv(wrapper, this.config.slideshowSpeed);
}
if (this.config.imagePaths.length === 0) {
Log.error('[MMM-BackgroundSlideshow] Missing required parameter imagePaths.');
} else {
// create an empty image list
this.imageList = [];
// set beginning image index to 0, as it will auto increment on start
this.imageIndex = 0;
this.updateImageList();
}
return wrapper;
},
createGradientDiv (direction, gradient, wrapper) {
const div = document.createElement('div');
div.style.backgroundImage =
`linear-gradient( to ${direction}, ${gradient.join()})`;
div.className = 'gradient';
wrapper.appendChild(div);
},
createRadialGradientDiv (type, gradient, wrapper) {
const div = document.createElement('div');
div.style.backgroundImage =
`radial-gradient( ${type}, ${gradient.join()})`;
div.className = 'gradient';
wrapper.appendChild(div);
},
createDiv () {
const div = document.createElement('div');
div.style.backgroundSize = this.config.backgroundSize;
div.style.backgroundPosition = this.config.backgroundPosition;
div.className = 'image';
return div;
},
createBlurredBackgroundDiv () {
const div = document.createElement('div');
div.style.backgroundSize = 'cover';
div.style.backgroundPosition = 'center';
div.className = 'image image-background';
return div;
},
createImageInfoDiv (wrapper) {
const div = document.createElement('div');
div.className = `info ${this.config.imageInfoLocation}`;
wrapper.appendChild(div);
return div;
},
createProgressbarDiv (wrapper, slideshowSpeed) {
const div = document.createElement('div');
div.className = 'progress';
const inner = document.createElement('div');
inner.className = 'progress-inner';
inner.style.display = 'none';
inner.style.animation = `move ${slideshowSpeed}ms linear`;
div.appendChild(inner);
wrapper.appendChild(div);
},
displayImage (imageinfo) {
const mwLc = imageinfo.path.toLowerCase();
if (mwLc.endsWith('.mp4') || mwLc.endsWith('.m4v')) {
const payload = [imageinfo.path, 'PLAY'];
imageinfo.data = 'modules/MMM-BackgroundSlideshow/transparent1080p.png';
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PLAY_VIDEO', payload);
this.playingVideo = true;
this.suspend();
} else {
this.playingVideo = false;
}
const image = new Image();
const showImage = () => {
// check if there are more than 2 elements and remove the first one
if (this.imagesDiv.childNodes.length > 1) {
this.imagesDiv.removeChild(this.imagesDiv.childNodes[0]);
}
if (this.imagesDiv.childNodes.length > 0) {
this.imagesDiv.childNodes[0].style.opacity = '0';
}
const transitionDiv = document.createElement('div');
transitionDiv.className = 'transition';
let transitionAnimationName;
if (this.config.transitionImages && this.config.transitions.length > 0) {
const randomNumber = Math.floor(Math.random() * this.config.transitions.length);
transitionAnimationName = this.config.transitions[randomNumber];
if (transitionAnimationName === 'opacity') {
transitionDiv.style.animationDuration = this.config.transitionSpeed;
transitionDiv.style.animationName = transitionAnimationName;
transitionDiv.style.animationTimingFunction = this.config.transitionTimingFunction;
transitionAnimationName = null;
}
transitionDiv.style.transition = `opacity ${this.config.transitionSpeed} ease-in-out`;
}
let backgroundDiv;
if (this.config.backgroundBlurEnabled) {
backgroundDiv = this.createBlurredBackgroundDiv();
backgroundDiv.style.backgroundImage = `url("${image.src}")`;
}
const foregroundDiv = document.createElement('div');
foregroundDiv.className = 'image-foreground-transition';
if (transitionAnimationName) {
foregroundDiv.style.animationDuration = this.config.transitionSpeed;
foregroundDiv.style.animationName = transitionAnimationName;
foregroundDiv.style.animationTimingFunction = this.config.transitionTimingFunction;
}
const imageDiv = this.createDiv();
imageDiv.style.backgroundImage = `url("${image.src}")`;
// imageDiv.style.transform = 'rotate(0deg)';
// this.div1.style.backgroundImage = `url("${image.src}")`;
// this.div1.style.opacity = '1';
if (this.config.showProgressBar) {
// Restart css animation
const oldDiv = document.querySelector('.progress-inner');
const newDiv = oldDiv.cloneNode(true);
oldDiv.parentNode.replaceChild(newDiv, oldDiv);
newDiv.style.display = '';
}
// Check to see if we need to animate the background
if (
this.config.backgroundAnimationEnabled &&
this.config.animations.length
) {
const randomNumber = Math.floor(Math.random() * this.config.animations.length);
const animation = this.config.animations[randomNumber];
imageDiv.style.animationDuration = this.config.backgroundAnimationDuration;
imageDiv.style.animationDelay = this.config.transitionSpeed;
if (animation === 'slide') {
// check to see if the width of the picture is larger or the height
const {width} = image;
const {height} = image;
const adjustedWidth = width * window.innerHeight / height;
const adjustedHeight = height * window.innerWidth / width;
imageDiv.style.backgroundPosition = '';
imageDiv.style.animationIterationCount = this.config.backgroundAnimationLoopCount;
imageDiv.style.backgroundSize = 'cover';
if (
adjustedWidth / window.innerWidth >
adjustedHeight / window.innerHeight
) {
// Scrolling horizontally...
if (Math.floor(Math.random() * 2)) {
imageDiv.className += ' slideH';
} else {
imageDiv.className += ' slideHInv';
}
} else {
// Scrolling vertically...
if (Math.floor(Math.random() * 2)) {
imageDiv.className += ' slideV';
} else {
imageDiv.className += ' slideVInv';
}
}
} else {
imageDiv.className += ` ${animation}`;
}
}
EXIF.getData(image, () => {
if (this.config.showImageInfo) {
let dateTime = EXIF.getTag(image, 'DateTimeOriginal');
// attempt to parse the date if possible
if (dateTime !== null) {
dateTime = this.formatImageInfoDate(dateTime);
}
this.addExifDescription(image, imageinfo);
this.currentImageInfo = this.updateImageInfo(imageinfo, dateTime);
this.requestPositionFromExif(image, imageinfo, dateTime);
}
if (!this.browserSupportsExifOrientationNatively) {
const exifOrientation = EXIF.getTag(image, 'Orientation');
imageDiv.style.transform = this.getImageTransformCss(exifOrientation);
}
});
if (backgroundDiv) {
transitionDiv.appendChild(backgroundDiv);
}
foregroundDiv.appendChild(imageDiv);
transitionDiv.appendChild(foregroundDiv);
this.imagesDiv.appendChild(transitionDiv);
};
// Decode the image before it replaces the current one. Otherwise slow devices
// (e.g. a Raspberry Pi without GPU acceleration) visibly paint it piece by piece.
image.onload = () => {
image
.decode()
.catch((error) => Log.debug(`[MMM-BackgroundSlideshow] Could not decode image in advance: ${error}`))
.then(showImage);
};
image.src = imageinfo.data;
// let other modules know which image is shown
this.sendNotification('BACKGROUNDSLIDESHOW_IMAGE_UPDATED', {
url: imageinfo.path
});
},
updateImage (backToPreviousImage = false, imageToDisplay = null) {
if (imageToDisplay) {
this.displayImage({
path: imageToDisplay,
data: imageToDisplay,
index: 1,
total: 1
});
return;
}
if (this.imageList.length > 0) {
this.imageIndex += 1;
if (this.config.randomizeImageOrder) {
this.imageIndex = Math.floor(Math.random() * this.imageList.length);
}
imageToDisplay = this.imageList.splice(this.imageIndex, 1);
this.displayImage({
path: imageToDisplay[0],
data: imageToDisplay[0],
index: 1,
total: 1
});
return;
}
if (backToPreviousImage) {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_PREV_IMAGE');
} else {
this.sendSocketNotification('BACKGROUNDSLIDESHOW_NEXT_IMAGE');
}
},
// Use the EXIF ImageDescription as the image description when the Google Takeout metadata has none.
// Placeholders written by cameras (e.g. 'OLYMPUS DIGITAL CAMERA') and descriptions
// matching excludeDescriptionsRegexps are ignored.
addExifDescription (image, imageinfo) {
if (!imageinfo.metadata || imageinfo.metadata.description) {
return;
}
const description = this.getExifDescription(image);
if (description) {
imageinfo.metadata.description = description;
}
},
getExifDescription (image) {
const rawDescription = EXIF.getTag(image, 'ImageDescription');
if (typeof rawDescription !== 'string') {
return null;
}
// exif-js reads strings byte by byte, so decode them as UTF-8 (falling back to Latin-1)
let description = rawDescription;
try {
const bytes = Uint8Array.from(rawDescription, (char) => char.charCodeAt(0));
description = new TextDecoder('utf-8', {fatal: true}).decode(bytes);
} catch {
// not valid UTF-8, keep the Latin-1 string
}
description = description.replace(/\0/gu, '').trim();
if (!description) {
return null;
}
const cameraNames = [EXIF.getTag(image, 'Make'), EXIF.getTag(image, 'Model')]
.map((name) => String(name || '')
.trim()
.toLowerCase());
if (
(/^(?:\w+ )?digital (?:still )?camera$|^(?:sony dsc|exif_jpeg_picture|pentax image|default|picasa)$/iu).test(description) ||
cameraNames.includes(description.toLowerCase())
) {
return null;
}
if (this.config.excludeDescriptionsRegexps?.some((regexp) => (regexp instanceof RegExp
? regexp
: new RegExp(regexp, 'u')).test(description))) {
return null;
}
return description;
},
getImageTransformCss (exifOrientation) {
switch (exifOrientation) {
case 2:
return 'scaleX(-1)';
case 3:
return 'scaleX(-1) scaleY(-1)';
case 4:
return 'scaleY(-1)';
case 5:
return 'scaleX(-1) rotate(90deg)';
case 6:
return 'rotate(90deg)';
case 7:
return 'scaleX(-1) rotate(-90deg)';
case 8:
return 'rotate(-90deg)';
case 1: // Falls through.
default:
return 'rotate(0deg)';
}
},
formatImageInfoDate (dateTime) {
const parsedDate = moment(
dateTime,
[moment.ISO_8601, 'YYYY-MM-DD HH:mm', 'YYYY:MM:DD HH:mm:ss'],
true
);
if (!parsedDate.isValid()) {
Log.log(`[MMM-BackgroundSlideshow] Failed to parse dateTime: ${
dateTime
}`);
return '';
}
return parsedDate.format(this.config.imageInfoDateFormat);
},
// EXIF GPS is [degrees, minutes, seconds] plus an N/S or E/W reference
gpsToDecimal (gpsData, ref) {
if (!gpsData || gpsData.length !== 3 || !ref) {
return null;
}
const [degrees, minutes, seconds] = gpsData.map(Number);
const decimal = degrees + minutes / 60 + seconds / 3600;
return ref === 'S' || ref === 'W'
? -decimal
: decimal;
},
// Ask the node_helper for a place name when the photo has EXIF GPS but no position
// from Google Takeout metadata. The info box is refreshed when the answer arrives.
requestPositionFromExif (image, imageinfo, imageDate) {
this.pendingPosition = null;
if (!this.config.useOpenStreetMap || !this.config.imageInfo.includes('position') || imageinfo.metadata.position) {
return;
}
const lat = this.gpsToDecimal(EXIF.getTag(image, 'GPSLatitude'), EXIF.getTag(image, 'GPSLatitudeRef'));
const lon = this.gpsToDecimal(EXIF.getTag(image, 'GPSLongitude'), EXIF.getTag(image, 'GPSLongitudeRef'));
if (lat === null || lon === null || Number.isNaN(lat) || Number.isNaN(lon)) {
return;
}
this.pendingPosition = {
imageinfo,
imageDate
};
this.sendSocketNotification('BACKGROUNDSLIDESHOW_GEOCODE', {
path: imageinfo.path,
lat: lat.toFixed(3),
lon: lon.toFixed(3)
});
},
// Show the place name from the node_helper, if that image is still on screen
showPositionResult (payload) {
const pending = this.pendingPosition;
if (pending && pending.imageinfo.path === payload.path && payload.position) {
pending.imageinfo.metadata.position = payload.position;
this.currentImageInfo = this.updateImageInfo(pending.imageinfo, pending.imageDate);
}
},
updateImageInfo (imageinfo, imageDate) {
// build the image info string based on imageinfo and EXIF data
// return the updated imageinfo object
const imageProps = [];
let correctTime = imageDate;
// build name, because used in 'name' AND 'desc_name'
// Only display last path component as image name if recurseSubDirectories is not set.
let imageName = imageinfo.path.split('/').pop();
// Otherwise display path relative to the path in configuration.
if (this.config.recursiveSubDirectories) {
for (const path of this.config.imagePaths) {
if (!imageinfo.path.includes(path)) {
continue;
}
imageName = imageinfo.path.split(path).pop();
if (imageName.startsWith('/')) {
imageName = imageName.substr(1);
}
break;
}
}
// Remove file extension from image name.
if (this.config.imageInfoNoFileExt) {
imageName = imageName.substring(0, imageName.lastIndexOf('.'));
}
if (this.config.cleanImageName) {
// now remove all words (separated by spaces or /) that contain at least one number
const imageNameCleaned = imageName
.split(/[\s/]+/u)
.filter((word) => !(/\d/gu).test(word))
.join(' ');
// if the cleaned name is not empty or only spaces, use it
if (imageNameCleaned.trim().length > 0) {
imageName = imageNameCleaned;
}
}
imageinfo.metadata.displayedName = imageName;
this.config.imageInfo.forEach((prop) => {
switch (prop) {
// possibles : description, name, desc_name, date, position, imagecount,
case 'date':
// by priority : photoTakenTime, EXIF dateTime, creationTime
if (imageinfo.metadata && imageinfo.metadata.photoTakenTime) {
correctTime = this.formatImageInfoDate(imageinfo.metadata.photoTakenTime);
if (correctTime) {
imageProps.push(correctTime);
}
} else if (imageDate && imageDate !== 'Invalid date') {
imageProps.push(imageDate);
imageinfo.metadata.EXIFTime = imageDate;
correctTime = imageDate;
} else if (imageinfo.metadata && imageinfo.metadata.creationTime) {
correctTime = this.formatImageInfoDate(imageinfo.metadata.creationTime);
if (correctTime) {
imageProps.push(correctTime);
}
}
// Save displayed time for other uses
if (correctTime) {
imageinfo.metadata.displayedTime = correctTime;
}
break;
case 'name': // default is name
imageProps.push(imageinfo.metadata.displayedName);
break;
case 'imagecount':
imageProps.push(`${imageinfo.index} of ${imageinfo.total}`);
break;
case 'description':
if (imageinfo.metadata && imageinfo.metadata.description) {
imageProps.push(`${imageinfo.metadata.description}`);
imageinfo.metadata.displayedDescription =
imageinfo.metadata.description;
}
break;
case 'desc_name':
case 'desc_or_name': // kept for backwards compatibility
if (imageinfo.metadata && imageinfo.metadata.description) {
imageProps.push(`${imageinfo.metadata.description}`);
imageinfo.metadata.displayedDescription =
imageinfo.metadata.description;
} else {
imageProps.push(imageinfo.metadata.displayedName);
}
break;
case 'position':
if (imageinfo.metadata && imageinfo.metadata.position) {
imageProps.push(`${imageinfo.metadata.position}`);
imageinfo.metadata.displayedPosition = imageinfo.metadata.position;
}
break;
default:
Log.warn(`[MMM-BackgroundSlideshow] ${prop
} is not a valid value for imageInfo. Please check your configuration`);
}
});
let innerHTML = `<header class="infoDivHeader">${this.translate('PICTURE_INFO')}</header>`;
imageProps.forEach((val) => {
innerHTML += `${val}<br/>`;
});
this.imageInfoDiv.innerHTML = innerHTML;
// hide the box entirely (it has padding and a background) when there is nothing to show
this.imageInfoDiv.style.display = imageProps.length > 0
? ''
: 'none';
return imageinfo;
},
resume () {
// this.updateImage(); //Removed to prevent image change whenever MMM-Carousel changes slides
this.suspend();
const self = this;
if (self.config.changeImageOnResume) {
self.updateImage();
}
},
updateImageList () {
this.suspend();
Log.debug('[MMM-BackgroundSlideshow] Getting images');
// ask helper function to get the image list
this.sendSocketNotification(
'BACKGROUNDSLIDESHOW_REGISTER_CONFIG',
this.config
);
}
});