-
Notifications
You must be signed in to change notification settings - Fork 44
/
wallpanel.js
3999 lines (3627 loc) · 119 KB
/
wallpanel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* (C) 2020-2024 by Jan Schneider ([email protected])
* Released under the GNU General Public License v3.0
*/
class ScreenWakeLock {
constructor() {
this.enabled = false;
this.error = null;
// The Screen Wake Lock API is only available when served over HTTPS
this.nativeWakeLockSupported = "wakeLock" in navigator;
this._lock = null;
this._player = null;
this._isPlaying = false;
const handleVisibilityChange = () => {
logger.debug("handleVisibilityChange");
if (this.enabled && !document.hidden) {
this.enable();
}
};
document.addEventListener("visibilitychange", handleVisibilityChange);
document.addEventListener("fullscreenchange", handleVisibilityChange);
if (!this.nativeWakeLockSupported) {
let videoData = 'data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAA1NtZGF0AAACrwYF//+r3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE2NCByMzA5NSBiYWVlNDAwIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAyMiAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOi0zOi0zIGFuYWx5c2U9MHgzOjB4MTEzIG1lPWhleCBzdWJtZT03IHBzeT0xIHBzeV9yZD0yLjAwOjAuNzAgbWl4ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0xIDh4OGRjdD0xIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PS00IHRocmVhZHM9MSBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVjdD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MiBrZXlpbnQ9MjUwIGtleWludF9taW49MSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMjAAgAAAABFliIQAF85//vfUt8yy7VNwgQAAAAlBmiRsQXzn/vAAAAAJQZ5CeIL5z4aBAAAACQGeYXRBfOeGgAAAAAkBnmNqQXznhoEAAAAPQZpoSahBaJlMCC+c//7xAAAAC0GehkURLBfOf4aBAAAACQGepXRBfOeGgQAAAAkBnqdqQXznhoAAAAAPQZqpSahBbJlMCC+c//7wAAADs21vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAACcQAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAALddHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAACcQAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAnEAAAgAAAAQAAAAACVW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAoAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAgBtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAHAc3RibAAAAMBzdHNkAAAAAAAAAAEAAACwYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAARVMYXZjNTkuMzcuMTAwIGxpYngyNjQAAAAAAAAAAAAAABj//wAAADZhdmNDAWQACv/hABlnZAAKrNlfllwEQAAAAwBAAAADAIPEiWWAAQAGaOvjxMhM/fj4AAAAABBwYXNwAAAAAQAAAAEAAAAUYnRydAAAAAAAAAKiAAACogAAABhzdHRzAAAAAAAAAAEAAAAKAABAAAAAABRzdHNzAAAAAAAAAAEAAAABAAAAYGN0dHMAAAAAAAAACgAAAAEAAIAAAAAAAQABQAAAAAABAACAAAAAAAEAAAAAAAAAAQAAQAAAAAABAAFAAAAAAAEAAIAAAAAAAQAAAAAAAAABAABAAAAAAAEAAIAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAAKAAAAAQAAADxzdHN6AAAAAAAAAAAAAAAKAAACyAAAAA0AAAANAAAADQAAAA0AAAATAAAADwAAAA0AAAANAAAAEwAAABRzdGNvAAAAAAAAAAEAAAAwAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1OS4yNy4xMDA=';
this._player = document.createElement("video");
this._player.setAttribute("id", "ScreenWakeLockVideo");
this._player.setAttribute("src", videoData);
this._player.setAttribute("playsinline", "");
this._player.setAttribute("muted", "");
this._player.addEventListener('ended', (event) => {
logger.debug("Video ended");
if (this.enabled) {
this.enable();
}
});
this._player.addEventListener('playing', (event) => {
logger.debug("Video playing");
this._isPlaying = true;
});
this._player.addEventListener('pause', (event) => {
logger.debug("Video pause");
this._isPlaying = false;
});
}
}
enable() {
if (this.nativeWakeLockSupported) {
logger.debug("Requesting native screen wakelock");
//if (this._lock) {
// this._lock.release();
//}
navigator.wakeLock
.request("screen")
.then((wakeLock) => {
logger.debug("Request screen wakelock successful");
this._lock = wakeLock;
this.enabled = true;
this.error = null;
})
.catch((e) => {
this.enabled = false;
this.error = e;
logger.error(`Failed to request screen wakeLock: ${e}`);
});
}
else {
logger.debug("Starting video player");
if (!this._player.paused && this._player._isPlaying) {
this._player.pause();
}
let playPromise = this._player.play();
if (playPromise) {
playPromise
.then((r) => {
this.enabled = true;
this.error = null;
logger.debug("Video play successful");
})
.catch((e) => {
this.enabled = false;
this.error = e;
logger.error(`Failed to play video: ${e}`);
});
}
}
}
disable() {
if (this.nativeWakeLockSupported) {
logger.debug("Releasing native screen wakelock");
if (this._lock) {
this._lock.release();
}
this._lock = null;
}
else {
logger.debug("Stopping video player");
if (!this._player.paused && this._player._isPlaying) {
this._player.pause();
}
}
this.enabled = false;
}
}
class CameraMotionDetection {
constructor() {
this.enabled = false;
this.width = 64;
this.height = 48;
this.threshold = this.width * this.height * 0.05;
this.captureInterval = 300;
this.videoElement = document.createElement("video");
this.videoElement.setAttribute("id", "wallpanelMotionDetectionVideo");
this.videoElement.style.visibility = 'hidden';
document.body.appendChild(this.videoElement);
this.canvasElement = document.createElement("canvas");
this.canvasElement.setAttribute("id", "wallpanelMotionDetectionCanvas");
document.body.appendChild(this.canvasElement);
this.context = this.canvasElement.getContext('2d', { willReadFrequently: true });
}
capture() {
let diffPixels = 0;
this.context.globalCompositeOperation = 'difference';
this.context.drawImage(this.videoElement, 0, 0, this.width, this.height);
const diffImageData = this.context.getImageData(0, 0, this.width, this.height);
const rgba = diffImageData.data;
for (let i = 0; i < rgba.length; i += 4) {
const pixelDiff = rgba[i] + rgba[i + 1] + rgba[i + 2];
if (pixelDiff >= 256) {
diffPixels ++;
if (diffPixels >= this.threshold) {
break;
}
}
}
if (diffPixels >= this.threshold) {
logger.debug("Motion detetcted:", diffPixels, this.threshold);
wallpanel.motionDetected();
}
this.context.globalCompositeOperation = 'source-over';
this.context.drawImage(this.videoElement, 0, 0, this.width, this.height);
}
start() {
if (this.enabled) {
return;
}
if (!navigator.mediaDevices) {
logger.error("No media devices found");
return;
}
this.enabled = true;
this.width = config.camera_motion_detection_capture_width;
this.height = config.camera_motion_detection_capture_height;
this.threshold = this.width * this.height * config.camera_motion_detection_threshold * 0.01;
this.captureInterval = config.camera_motion_detection_capture_interval * 1000;
this.videoElement.width = this.width;
this.videoElement.height = this.height;
this.canvasElement.width = this.width;
this.canvasElement.height = this.height;
if (config.camera_motion_detection_capture_visible) {
this.canvasElement.style.position = "fixed";
this.canvasElement.style.top = 0;
this.canvasElement.style.left = 0;
this.canvasElement.style.zIndex = 10000;
this.canvasElement.style.border = "1px solid black";
}
else {
this.canvasElement.style.visibility = 'hidden';
}
navigator.mediaDevices.getUserMedia(
{ audio: false, video: { facingMode: { acceptable: "user" }, width: this.width, height: this.height } }
).then((stream) => {
this.videoElement.srcObject = stream
this.videoElement.play();
if (this.enabled) {
setInterval(this.capture.bind(this), this.captureInterval);
}
}).catch((err) => {
logger.error("Camera motion detection error:", err);
});
}
stop() {
if (!this.enabled) {
return;
}
this.enabled = false;
this.videoElement.pause();
this.videoElement.srcObject.getTracks().forEach(track => {
track.stop();
});
}
}
const version = "4.31.1";
const defaultConfig = {
enabled: false,
enabled_on_tabs: [],
debug: false,
log_level_console: "info",
hide_toolbar: false,
hide_toolbar_action_icons: false,
hide_sidebar: false,
fullscreen: false,
z_index: 1000,
idle_time: 15,
fade_in_time: 3.0,
fade_out_time_motion_detected: 1.0,
fade_out_time_screensaver_entity: 3.0,
fade_out_time_browser_mod_popup: 1.0,
fade_out_time_interaction: 0.3,
crossfade_time: 3.0,
display_time: 15.0,
keep_screen_on_time: 0,
black_screen_after_time: 0,
control_reactivation_time: 1.0,
screensaver_stop_navigation_path: '',
screensaver_stop_close_browser_mod_popup: false,
screensaver_entity: '',
stop_screensaver_on_mouse_move: true,
stop_screensaver_on_mouse_click: true,
stop_screensaver_on_key_down: true,
stop_screensaver_on_location_change: true,
disable_screensaver_on_browser_mod_popup: false,
disable_screensaver_on_browser_mod_popup_func: '',
show_images: true,
image_url: "https://picsum.photos/${width}/${height}?random=${timestamp}",
immich_api_key: "",
immich_album_names: [],
immich_resolution: "preview",
image_fit: 'cover', // cover / contain / fill
image_list_update_interval: 3600,
image_order: 'sorted', // sorted / random
image_excludes: [],
image_background: 'color', // color / image
touch_zone_size_next_image: 15,
touch_zone_size_previous_image: 15,
show_progress_bar: false,
show_image_info: false,
fetch_address_data: false,
image_info_template: '${DateTimeOriginal}',
info_animation_duration_x: 0,
info_animation_duration_y: 0,
info_animation_timing_function_x: 'ease',
info_animation_timing_function_y: 'ease',
info_move_pattern: 'random',
info_move_interval: 0,
info_move_fade_duration: 2.0,
image_animation_ken_burns: false,
image_animation_ken_burns_zoom: 1.3,
image_animation_ken_burns_delay: 0,
camera_motion_detection_enabled: false,
camera_motion_detection_threshold: 5,
camera_motion_detection_capture_width: 64,
camera_motion_detection_capture_height: 48,
camera_motion_detection_capture_interval: 0.3,
camera_motion_detection_capture_visible: false,
style: {},
badges: [],
cards: [
{type: 'weather-forecast', entity: 'weather.home', show_forecast: true}
],
card_interaction: false,
profile: '',
profile_entity: '',
profiles: {}
};
let dashboardConfig = {};
let config = {};
let activePanel = null;
let activeTab = null;
let fullscreen = false;
let screenWakeLock = new ScreenWakeLock();
let cameraMotionDetection = new CameraMotionDetection();
let wallpanel = null;
let skipDisableScreensaverOnLocationChanged = false;
let classStyles = {
"wallpanel-screensaver-image-background": {
"filter": "blur(15px)",
"background": "#00000000",
"background-position": "center",
"background-size": "cover"
},
"wallpanel-screensaver-image-info": {
"position": "absolute",
"bottom": "0.5em",
"right": "0.5em",
"padding": "0.1em 0.5em 0.1em 0.5em",
"font-size": "2em",
"background": "#00000055",
"backdrop-filter": "blur(2px)",
"border-radius": "0.1em"
},
"wallpanel-progress": {
"position": "absolute",
"bottom": "0",
"height": "2px",
"width": "100%",
},
"wallpanel-progress-inner": {
"height": "100%",
"background-color": "white"
}
}
let imageInfoCache = {};
let imageInfoCacheKeys = [];
const imageInfoCacheMaxSize = 1000;
let configEntityStates = {};
const elHass = document.querySelector("body > home-assistant");
const LitElement = Object.getPrototypeOf(customElements.get("hui-masonry-view"));
const HuiView = customElements.get("hui-view");
let elHaMain = null;
let browserId = null;
if (window.browser_mod) {
if (window.browser_mod.entity_id) {
// V1
browserId = window.browser_mod.entity_id;
}
else if (window.browser_mod.browserID) {
// V2
browserId = window.browser_mod.browserID.replace('-', '_');
}
}
function getActiveBrowserModPopup() {
if (!browserId) {
return null;
}
const bmp = document.getElementsByTagName("browser-mod-popup");
if (!bmp || !bmp[0] || !bmp[0].shadowRoot || bmp[0].shadowRoot.children.length == 0) {
return null;
}
return bmp[0];
}
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
function stringify(obj) {
let processedObjects = [];
let json = JSON.stringify(obj, function(key, value) {
if (typeof value === "object" && value !== null) {
if (processedObjects.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
processedObjects.push(value);
}
return value;
});
return json;
}
const logger = {
messages: [],
addMessage: function(level, args) {
if (!config.debug) {
return;
}
let msg = {
"level": level,
"date": (new Date()).toISOString(),
"text": "",
"objs": [],
"stack": ""
}
const err = new Error();
if (err.stack) {
msg.stack = err.stack.toString().replace(/^Error\r?\n/, '');
}
for (let i = 0; i < args.length; i++) {
if (i == 0 && (typeof args[0] === 'string' || args[0] instanceof String)) {
msg.text = args[i];
}
else {
msg.objs.push(args[i]);
}
}
logger.messages.push(msg);
if (logger.messages.length > 1000) {
// Max 1000 messages
logger.messages.shift();
}
},
downloadMessages: function() {
const data = new Blob([stringify(logger.messages)], {type: 'text/plain'});
const url = window.URL.createObjectURL(data);
const el = document.createElement('a');
el.href = url;
el.target = '_blank';
el.download = 'wallpanel_log.txt';
el.click();
},
purgeMessages: function() {
logger.messages = [];
},
log: function(text){
console.log.apply(this, arguments);
logger.addMessage("info", arguments);
},
debug: function (text) {
if (["debug"].includes(config.log_level_console)) {
console.debug.apply(this, arguments);
}
logger.addMessage("debug", arguments);
},
info: function (text) {
if (["debug", "info"].includes(config.log_level_console)) {
console.info.apply(this, arguments);
}
logger.addMessage("info", arguments);
},
warn: function (text) {
if (["debug", "info", "warn"].includes(config.log_level_console)) {
console.warn.apply(this, arguments);
}
logger.addMessage("warn", arguments);
},
error: function (text) {
if (["debug", "info", "warn", "error"].includes(config.log_level_console)) {
console.error.apply(this, arguments);
}
logger.addMessage("error", arguments);
}
};
function mergeConfig(target, ...sources) {
// https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeConfig(target[key], source[key]);
} else {
let val = source[key];
function replacer(match, entityId, offset, string) {
if (!(entityId in configEntityStates)) {
configEntityStates[entityId] = "";
const entity = elHass.__hass.states[entityId];
if (entity) {
configEntityStates[entityId] = entity.state;
}
else {
logger.error(`Entity used in placeholder not found: ${entityId} (${match})`)
}
}
const state = configEntityStates[entityId];
logger.debug(`Replace ${match} with ${state}`);
return state;
}
if (typeof val === 'string' || val instanceof String) {
val = val.replace("${browser_id}", browserId ? browserId : "browser-id-unset");
val = val.replace(/\$\{entity:\s*([^}]+\.[^}]+)\}/g, replacer);
}
if (typeof target[key] === 'boolean') {
val = ["true", "on", "yes", "1"].includes(val.toString());
}
Object.assign(target, { [key]: val });
}
}
}
return mergeConfig(target, ...sources);
}
function updateConfig() {
const params = new URLSearchParams(window.location.search);
const user = elHass.__hass.user.name ? elHass.__hass.user.name.toLowerCase().replace(/\s/g, '_') : null;
let oldConfig = config;
config = {};
mergeConfig(config, defaultConfig);
if (Object.keys(dashboardConfig).length === 0) {
dashboardConfig = getHaPanelLovelaceConfig();
}
mergeConfig(config, dashboardConfig);
let paramConfig = {}
for (let [key, value] of params) {
if (key.startsWith("wp_")) {
key = key.substring(3);
if (key in defaultConfig && value) {
// Convert to the right type
paramConfig[key] = defaultConfig[key].constructor(JSON.parse(value));
}
}
}
config = mergeConfig(config, paramConfig);
const profile = config.profile;
if (config.profiles && profile && config.profiles[profile]) {
config = mergeConfig(config, config.profiles[profile]);
logger.debug(`Profile set from config: ${profile}`);
}
if (config.profiles && browserId && config.profiles[`device.${browserId}`]) {
let profile = `device.${browserId}`;
config = mergeConfig(config, config.profiles[profile]);
logger.debug(`Profile set from device: ${profile}`);
}
if (config.profiles && user && config.profiles[`user.${user}`]) {
let profile = `user.${user}`;
config = mergeConfig(config, config.profiles[profile]);
logger.debug(`Profile set from user: ${profile}`);
}
config = mergeConfig(config, paramConfig);
const profile_entity = config.profile_entity;
if (config.profiles && profile_entity && elHass.__hass.states[profile_entity] && config.profiles[elHass.__hass.states[profile_entity].state]) {
let profile = elHass.__hass.states[profile_entity].state;
config = mergeConfig(config, config.profiles[profile]);
logger.debug(`Profile set from entity state: ${profile}`);
}
if (config.card_interaction) {
config.stop_screensaver_on_mouse_move = false;
}
if (config.image_url) {
if (config.image_url.startsWith("/")) {
config.image_url = `media-source://media_source${config.image_url}`;
}
if (imageSourceType() == "media-source") {
config.image_url = config.image_url.replace(/\/+$/, '');
}
if (imageSourceType() == "unsplash-api" && config.image_list_update_interval < 90) {
// Unsplash API currently places a limit of 50 requests per hour
config.image_list_update_interval = 90;
}
}
else {
config.show_images = false;
}
if (!config.enabled) {
config.debug = false;
config.hide_toolbar = false;
config.hide_sidebar = false;
config.hide_toolbar_action_icons = false;
config.fullscreen = false;
config.show_images = false;
}
logger.debug("Wallpanel config is now:", config);
if (wallpanel) {
if (isActive()) {
wallpanel.reconfigure(oldConfig);
}
else if (wallpanel.screensaverRunning && wallpanel.screensaverRunning()) {
wallpanel.stopScreensaver();
}
}
}
function isActive() {
const params = new URLSearchParams(window.location.search);
if (params.get("edit") == "1") {
return false;
}
if (!config.enabled) {
return false;
}
if (config.enabled_on_tabs && config.enabled_on_tabs.length > 0 && activeTab && !config.enabled_on_tabs.includes(activeTab)) {
return false;
}
if (wallpanel &&
wallpanel.disable_screensaver_on_browser_mod_popup_function &&
getActiveBrowserModPopup() &&
wallpanel.disable_screensaver_on_browser_mod_popup_function(getActiveBrowserModPopup())) {
return false;
}
if (config.disable_screensaver_on_browser_mod_popup && getActiveBrowserModPopup()) {
return false;
}
return true;
}
function imageSourceType() {
if ((!config.show_images) || (!config.image_url)) {
return "";
}
if (config.image_url.startsWith("media-entity://")) return "media-entity";
if (config.image_url.startsWith("media-source://")) return "media-source";
if (config.image_url.startsWith("https://api.unsplash")) return "unsplash-api";
if (config.image_url.startsWith("immich+")) return "immich-api";
return "url";
}
function getHaPanelLovelace() {
try {
return elHaMain.shadowRoot.querySelector('ha-panel-lovelace')
}
catch (e) {
logger.error(e);
}
}
function getHaPanelLovelaceConfig() {
let pl = getHaPanelLovelace();
let conf = {};
if (pl && pl.lovelace && pl.lovelace.config && pl.lovelace.config.wallpanel) {
for (let key in pl.lovelace.config.wallpanel) {
if (key in defaultConfig) {
conf[key] = pl.lovelace.config.wallpanel[key];
}
}
}
return conf;
}
function getCurrentView() {
try {
return elHaMain.shadowRoot
.querySelector('ha-panel-lovelace').shadowRoot
.querySelector('hui-root').shadowRoot
.querySelector('hui-view')
}
catch (e) {
logger.error(e);
}
}
function setSidebarHidden(hidden) {
try {
const panelLovelace = elHaMain.shadowRoot.querySelector("ha-panel-lovelace");
if (!panelLovelace) {
return;
}
const huiRoot = panelLovelace.shadowRoot.querySelector("hui-root");
if (huiRoot) {
const menuButton = huiRoot.shadowRoot.querySelector("ha-menu-button");
if (menuButton) {
if (hidden) {
menuButton.style.display = "none";
}
else {
menuButton.style.removeProperty("display");
}
}
}
}
catch (e) {
logger.warn(e);
}
try {
const aside = elHaMain.shadowRoot.querySelector("ha-drawer").shadowRoot.querySelector("aside");
aside.style.display = (hidden ? "none" : "");
if (hidden) {
elHaMain.style.setProperty("--mdc-drawer-width", "env(safe-area-inset-left)");
}
else {
elHaMain.style.removeProperty("--mdc-drawer-width");
}
window.dispatchEvent(new Event('resize'));
}
catch (e) {
logger.warn(e);
}
}
function setToolbarHidden(hidden) {
try {
const panelLovelace = elHaMain.shadowRoot.querySelector("ha-panel-lovelace");
if (!panelLovelace) {
return;
}
let huiRoot = panelLovelace.shadowRoot.querySelector("hui-root");
if (!huiRoot) {
return;
}
huiRoot = huiRoot.shadowRoot;
const view = huiRoot.querySelector("#view");
let appToolbar = huiRoot.querySelector("app-toolbar");
if (!appToolbar) {
// Changed with 2023.04
appToolbar = huiRoot.querySelector("div.toolbar");
}
if (hidden) {
appToolbar.style.setProperty("display", "none");
view.style.minHeight = "100vh";
view.style.marginTop = "0";
view.style.paddingTop = "0";
}
else {
appToolbar.style.removeProperty("display");
view.style.removeProperty("min-height");
view.style.removeProperty("margin-top");
view.style.removeProperty("padding-top");
const actionItems = appToolbar.querySelector("div.action-items");
if (config.hide_toolbar_action_icons) {
actionItems.style.setProperty("display", "none");
}
else {
actionItems.style.setProperty("display", "flex");
}
}
window.dispatchEvent(new Event('resize'));
}
catch (e) {
logger.warn(e);
}
}
function navigate(path, keepSearch=true) {
if (keepSearch && (!path.includes('?'))) {
path += window.location.search;
}
history.pushState(null, "", path);
elHass.dispatchEvent(
new Event(
"location-changed", {
bubbles: true,
cancelable: false,
composed: true,
}
)
);
}
document.addEventListener('fullscreenerror', (event) => {
logger.error('Failed to enter fullscreen');
});
document.addEventListener('fullscreenchange', (event) => {
fullscreen = Boolean(document.fullscreenElement);
});
function enterFullscreen() {
logger.debug("Enter fullscreen");
// Will need user input event to work
let el = document.documentElement;
if (el.requestFullscreen) {
el.requestFullscreen().then(
result => {
logger.debug("Successfully requested fullscreen");
},
error => {
logger.error(error);
}
)
}
else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
}
else if (el.msRequestFullscreen) {
el.msRequestFullscreen();
}
else if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen();
}
}
function exitFullscreen() {
logger.debug("Exit fullscreen");
if (document.fullscreenElement) {
document.fullscreenElement.exitFullscreen().then(
result => {
logger.debug("Successfully exited from fullscreen mode");
},
error => {
logger.error(error);
}
)
}
}
class WallpanelView extends HuiView {
constructor() {
super();
this.imageList = [];
this.imageIndex = -1;
this.imageListDirection = "forwards"; // forwards, backwards
this.lastImageListUpdate;
this.updatingImageList = false;
this.cancelUpdatingImageList = false;
this.lastImageUpdate = 0;
this.messageBoxTimeout = null;
this.blockEventsUntil = 0;
this.screensaverStartedAt;
this.screensaverStoppedAt = new Date();
this.infoBoxContentCreatedDate;
this.idleSince = Date.now();
this.lastProfileSet = config.profile;
this.lastMove = null;
this.lastCorner = 0; // 0 - top left, 1 - bottom left, 2 - bottom right, 3 - top right
this.translateInterval = null;
this.lastClickTime = 0;
this.clickCount = 0;
this.energyCollectionUpdateEnabled = false;
this.energyCollectionUpdateInterval = 60;
this.lastEnergyCollectionUpdate = 0;
this.screensaverStopNavigationPathTimeout = null;
this.disable_screensaver_on_browser_mod_popup_function = null;
this.lovelace = null;
this.__hass = elHass.__hass;
this.__cards = [];
this.__badges = [];
elHass.provideHass(this);
setInterval(this.timer.bind(this), 1000);
}
// Whenever the state changes, a new `hass` object is set.
set hass(hass) {
logger.debug("Update hass");
this.__hass = hass;
let changed = false;
for (const entityId in configEntityStates) {
const entity = this.__hass.states[entityId];
if (entity && entity.state != configEntityStates[entityId]) {
configEntityStates[entityId] = entity.state;
changed = true;
}
}
let profileUpdated = this.updateProfile();
if (!profileUpdated && changed) {
updateConfig();
}
if (!isActive()) {
return;
}
const screensaver_entity = config.screensaver_entity;
if (screensaver_entity && this.__hass.states[screensaver_entity]) {
let lastChanged = new Date(this.__hass.states[screensaver_entity].last_changed);
let state = this.__hass.states[screensaver_entity].state;
if (state == "off" && this.screensaverStartedAt && lastChanged.getTime() - this.screensaverStartedAt > 0) {
this.stopScreensaver(config.fade_out_time_screensaver_entity);
}
else if (state == "on" && this.screensaverStoppedAt && lastChanged.getTime() - this.screensaverStoppedAt > 0) {
this.startScreensaver();
}
}
if (this.screensaverRunning()) {
this.__cards.forEach(card => {
card.hass = this.hass;
});
this.__badges.forEach(badge => {
badge.hass = this.hass;
});
}
}
get hass() {
return this.__hass;
}
setScreensaverEntityState() {
const screensaver_entity = config.screensaver_entity;
if (!screensaver_entity || !this.__hass.states[screensaver_entity]) return;
if (this.screensaverRunning() && this.__hass.states[screensaver_entity].state == 'on') return;
if (!this.screensaverRunning() && this.__hass.states[screensaver_entity].state == 'off') return;
this.__hass.callService('input_boolean', this.screensaverRunning() ? "turn_on" : "turn_off", {
entity_id: screensaver_entity
}).then(
result => {
logger.debug(result);
},
error => {
logger.error("Failed to set screensaver entity state:", error);
}
);
}
updateProfile() {
const profile_entity = config.profile_entity;
if (profile_entity && this.__hass.states[profile_entity]) {
const profile = this.__hass.states[profile_entity].state;
if ((profile && profile != this.lastProfileSet) || (!profile && this.lastProfileSet)) {
logger.debug(`Set profile to ${profile}`);
this.lastProfileSet = profile;
updateConfig();
return true;
}
}
return false;
}
timer() {
if (!config.enabled || !activePanel) {
return;
}
if (this.screensaverRunning()) {
if (config.disable_screensaver_on_browser_mod_popup && getActiveBrowserModPopup()) {
this.stopScreensaver(config.fade_out_time_browser_mod_popup);
}
else {
this.updateScreensaver();
}
}
else if (isActive()) {
if (config.idle_time > 0 && Date.now() - this.idleSince >= config.idle_time*1000) {
this.startScreensaver();
}
}
}
setDefaultStyle() {
this.messageBox.removeAttribute('style');
this.messageBox.style.position = 'fixed';
this.messageBox.style.pointerEvents = "none";
this.messageBox.style.top = 0;
this.messageBox.style.left = 0;
this.messageBox.style.width = '100%';
this.messageBox.style.height = '10%';
this.messageBox.style.zIndex = this.style.zIndex + 1;
if (!this.screensaverRunning()) {
this.messageBox.style.visibility = 'hidden';
}
//this.messageBox.style.margin = '5vh auto auto auto';
this.messageBox.style.padding = '5vh 0 0 0';
this.messageBox.style.fontSize = '5vh';
this.messageBox.style.textAlign = 'center';
this.messageBox.style.transition = 'visibility 200ms ease-in-out';
this.debugBox.removeAttribute('style');
this.debugBox.style.position = 'fixed';
this.debugBox.style.pointerEvents = "none";
this.debugBox.style.top = '0%';
this.debugBox.style.left = '0%';
this.debugBox.style.width = '100%';
this.debugBox.style.height = '100%';
this.debugBox.style.background = '#00000099';
this.debugBox.style.color = '#ffffff';
this.debugBox.style.zIndex = this.style.zIndex + 2;
if (!this.screensaverRunning()) {
this.debugBox.style.visibility = 'hidden';
}
this.debugBox.style.fontFamily = 'monospace';
this.debugBox.style.fontSize = '12px';
this.debugBox.style.overflowWrap = 'break-word';
this.debugBox.style.overflowY = 'auto';
this.screensaverContainer.removeAttribute('style');
this.screensaverContainer.style.position = 'fixed';
this.screensaverContainer.style.top = 0;
this.screensaverContainer.style.left = 0;
this.screensaverContainer.style.width = '100vw';
this.screensaverContainer.style.height = '100vh';
this.screensaverContainer.style.background = '#000000';
if (!this.screensaverRunning()) {
this.imageOneContainer.removeAttribute('style');
this.imageOneContainer.style.opacity = 1;
}
this.imageOneContainer.style.position = 'absolute';
this.imageOneContainer.style.pointerEvents = 'none';
this.imageOneContainer.style.top = 0;
this.imageOneContainer.style.left = 0;
this.imageOneContainer.style.width = '100%';
this.imageOneContainer.style.height = '100%';
this.imageOneContainer.style.border = 'none';
this.imageOneBackground.style.position = 'absolute';
this.imageOneBackground.style.pointerEvents = 'none';
this.imageOneBackground.style.top = 0;
this.imageOneBackground.style.left = 0;
this.imageOneBackground.style.width = '100%';
this.imageOneBackground.style.height = '100%';
this.imageOneBackground.style.border = 'none';