-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1158 lines (963 loc) · 40 KB
/
app.py
File metadata and controls
1158 lines (963 loc) · 40 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
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
import json
import logging
import os
import threading
import time
from datetime import datetime as dt_datetime
from datetime import timedelta as dt_timedelta
from datetime import time as dt_time
from typing import Any, Dict, List, Optional
import requests
from flask import Flask, jsonify, request, send_from_directory, g
try:
import paho.mqtt.client as mqtt
MQTT_AVAILABLE = True
except ImportError:
MQTT_AVAILABLE = False
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
app = Flask(__name__, static_folder='.', static_url_path='')
SITE_NAME = os.getenv("SITE_NAME", "FPP Lichtershow")
FPP_BASE_URL = os.getenv("FPP_BASE_URL", "http://fpp.local")
PLAYLIST_1 = os.getenv("FPP_PLAYLIST_1", "show 1")
PLAYLIST_2 = os.getenv("FPP_PLAYLIST_2", "show 2")
PLAYLIST_REQUESTS = os.getenv("FPP_PLAYLIST_REQUESTS", "all songs")
BACKGROUND_EFFECT = os.getenv("FPP_BACKGROUND_EFFECT", "background")
SHOW_START_DATE = os.getenv("FPP_SHOW_START_DATE")
SHOW_END_DATE = os.getenv("FPP_SHOW_END_DATE")
SHOW_START_TIME = os.getenv("FPP_SHOW_START_TIME", "16:30")
SHOW_END_TIME = os.getenv("FPP_SHOW_END_TIME", "22:00")
SCHEDULED_SHOWS_ENABLED = os.getenv("SCHEDULED_SHOWS_ENABLED", "true").lower() in ["true", "1", "yes", "on"]
PREVIEW_MODE = os.getenv("PREVIEW_MODE", "false").lower() in ["true", "1", "yes", "on"]
POLL_INTERVAL_SECONDS = max(5, int(os.getenv("FPP_POLL_INTERVAL_MS", "15000")) // 1000)
REQUEST_TIMEOUT = 8
# Notification Configuration
NOTIFY_ENABLED = os.getenv("NOTIFY_ENABLED", "false").lower() in ["true", "1", "yes", "on"]
NOTIFY_MQTT_ENABLED = os.getenv("NOTIFY_MQTT_ENABLED", "false").lower() in ["true", "1", "yes", "on"]
NOTIFY_MQTT_BROKER = os.getenv("NOTIFY_MQTT_BROKER", "")
NOTIFY_MQTT_PORT = int(os.getenv("NOTIFY_MQTT_PORT", "1883"))
NOTIFY_MQTT_USERNAME = os.getenv("NOTIFY_MQTT_USERNAME", "")
NOTIFY_MQTT_PASSWORD = os.getenv("NOTIFY_MQTT_PASSWORD", "")
NOTIFY_MQTT_TOPIC = os.getenv("NOTIFY_MQTT_TOPIC", "fpp-control/notifications")
NOTIFY_MQTT_USE_TLS = os.getenv("NOTIFY_MQTT_USE_TLS", "false").lower() in ["true", "1", "yes", "on"]
NOTIFY_NTFY_ENABLED = os.getenv("NOTIFY_NTFY_ENABLED", "false").lower() in ["true", "1", "yes", "on"]
NOTIFY_NTFY_URL = os.getenv("NOTIFY_NTFY_URL", "https://ntfy.sh")
NOTIFY_NTFY_TOPIC = os.getenv("NOTIFY_NTFY_TOPIC", "")
NOTIFY_NTFY_TOKEN = os.getenv("NOTIFY_NTFY_TOKEN", "")
NOTIFY_HOMEASSISTANT_ENABLED = os.getenv("NOTIFY_HOMEASSISTANT_ENABLED", "false").lower() in ["true", "1", "yes", "on"]
NOTIFY_HOMEASSISTANT_URL = os.getenv("NOTIFY_HOMEASSISTANT_URL", "")
NOTIFY_HOMEASSISTANT_TOKEN = os.getenv("NOTIFY_HOMEASSISTANT_TOKEN", "")
NOTIFY_WEBHOOK_ENABLED = os.getenv("NOTIFY_WEBHOOK_ENABLED", "false").lower() in ["true", "1", "yes", "on"]
NOTIFY_WEBHOOK_URL = os.getenv("NOTIFY_WEBHOOK_URL", "")
NOTIFY_WEBHOOK_METHOD = os.getenv("NOTIFY_WEBHOOK_METHOD", "POST").upper()
NOTIFY_WEBHOOK_HEADERS = os.getenv("NOTIFY_WEBHOOK_HEADERS", "")
# Initialize MQTT client if enabled
mqtt_client = None
if NOTIFY_ENABLED and NOTIFY_MQTT_ENABLED and MQTT_AVAILABLE and NOTIFY_MQTT_BROKER:
try:
mqtt_client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
if NOTIFY_MQTT_USERNAME and NOTIFY_MQTT_PASSWORD:
mqtt_client.username_pw_set(NOTIFY_MQTT_USERNAME, NOTIFY_MQTT_PASSWORD)
if NOTIFY_MQTT_USE_TLS:
mqtt_client.tls_set()
mqtt_client.connect(NOTIFY_MQTT_BROKER, NOTIFY_MQTT_PORT, 60)
mqtt_client.loop_start()
except (AttributeError, TypeError):
# Fallback for older paho-mqtt versions without CallbackAPIVersion
try:
mqtt_client = mqtt.Client()
if NOTIFY_MQTT_USERNAME and NOTIFY_MQTT_PASSWORD:
mqtt_client.username_pw_set(NOTIFY_MQTT_USERNAME, NOTIFY_MQTT_PASSWORD)
if NOTIFY_MQTT_USE_TLS:
mqtt_client.tls_set()
mqtt_client.connect(NOTIFY_MQTT_BROKER, NOTIFY_MQTT_PORT, 60)
mqtt_client.loop_start()
except Exception as e:
logger.error(f"Failed to connect to MQTT broker: {e}")
mqtt_client = None
except Exception as e:
logger.error(f"Failed to connect to MQTT broker: {e}")
mqtt_client = None
def _load_access_code_from_config() -> str:
"""Return access code from generated frontend config if available."""
config_path = os.path.join(os.path.dirname(__file__), "config.js")
if not os.path.exists(config_path):
return ""
try:
with open(config_path, "r", encoding="utf-8") as f:
raw = f.read().strip()
prefix = "window.FPP_CONFIG ="
if not raw.startswith(prefix):
return ""
json_part = raw[len(prefix) :].strip()
if json_part.endswith(";"):
json_part = json_part[:-1]
config = json.loads(json_part)
return str(config.get("accessCode", "")).strip()
except Exception:
return ""
ACCESS_CODE = os.getenv("ACCESS_CODE", "").strip() or _load_access_code_from_config()
def send_notification(title: str, message: str, action_type: str = "info", extra_data: Optional[Dict[str, Any]] = None) -> None:
"""Send notification via configured channels.
This function sends notifications through all enabled notification channels
simultaneously. Channels include MQTT, ntfy.sh, Home Assistant webhooks,
and generic webhooks. Each channel operates independently, so a failure
in one channel does not affect others.
Args:
title: Short notification title (e.g., "Show gestartet")
message: Full notification message body
action_type: Type of action for categorization. Common values:
- "show_start": Show was started via button
- "song_request": Song was requested by visitor
- "info": General information notification
extra_data: Optional dict with additional data to include in payload.
For show_start: {"playlist": "show1", "playlist_type": "playlist1"}
For song_request: {"song_title": "...", "duration": 180, "queue_position": 2}
Example:
>>> send_notification(
... title="Hauptshow gestartet",
... message="Ein Besucher hat 'show 1' gestartet.",
... action_type="show_start",
... extra_data={"playlist": "show 1"}
... )
Note:
- All notification failures are logged but do not raise exceptions
- Notifications are sent asynchronously (non-blocking)
- Requires NOTIFY_ENABLED=true in environment configuration
"""
if not NOTIFY_ENABLED:
return
# Skip notifications in preview mode
if PREVIEW_MODE:
logger.info(f"Preview mode: Skipping notification - {title}")
return
timestamp = dt_datetime.now().isoformat()
payload = {
"title": title,
"message": message,
"action_type": action_type,
"timestamp": timestamp,
"site_name": SITE_NAME,
}
if extra_data:
payload.update(extra_data)
# Send via MQTT
if NOTIFY_MQTT_ENABLED and mqtt_client:
try:
mqtt_payload = json.dumps(payload, ensure_ascii=False)
result = mqtt_client.publish(NOTIFY_MQTT_TOPIC, mqtt_payload, qos=1, retain=False)
# Check if message was successfully queued (result code 0 = success)
if result.rc != 0:
logger.error(f"MQTT publish failed with return code: {result.rc}")
except Exception as e:
logger.error(f"Failed to send MQTT notification: {e}")
# Send via ntfy.sh
if NOTIFY_NTFY_ENABLED and NOTIFY_NTFY_TOPIC:
try:
# ntfy.sh API: POST to topic URL with message as text body
# Headers are used for title, priority, and tags
url = f"{NOTIFY_NTFY_URL}/{NOTIFY_NTFY_TOPIC}"
headers = {
"Title": title,
"Priority": "default",
"Tags": action_type
}
if NOTIFY_NTFY_TOKEN:
headers["Authorization"] = f"Bearer {NOTIFY_NTFY_TOKEN}"
# Send message as plain text body (not JSON)
response = requests.post(
url,
data=message,
headers=headers,
timeout=5
)
if response.status_code != 200:
logger.error(f"ntfy.sh notification failed: HTTP {response.status_code} - {response.text}")
except requests.exceptions.Timeout:
logger.error(f"Failed to send ntfy notification: Timeout after 5 seconds")
except requests.exceptions.ConnectionError as e:
logger.error(f"Failed to send ntfy notification: Connection error - {e}")
except Exception as e:
logger.error(f"Failed to send ntfy notification: {e}")
# Send via Home Assistant
if NOTIFY_HOMEASSISTANT_ENABLED and NOTIFY_HOMEASSISTANT_URL and NOTIFY_HOMEASSISTANT_TOKEN:
try:
headers = {
"Authorization": f"Bearer {NOTIFY_HOMEASSISTANT_TOKEN}",
"Content-Type": "application/json",
}
ha_payload = {
"title": title,
"message": message,
"data": payload,
}
requests.post(NOTIFY_HOMEASSISTANT_URL, json=ha_payload, headers=headers, timeout=5)
except Exception as e:
logger.error(f"Failed to send Home Assistant notification: {e}")
# Send via generic webhook
if NOTIFY_WEBHOOK_ENABLED and NOTIFY_WEBHOOK_URL:
try:
headers = {"Content-Type": "application/json"}
if NOTIFY_WEBHOOK_HEADERS:
try:
custom_headers = json.loads(NOTIFY_WEBHOOK_HEADERS)
headers.update(custom_headers)
except json.JSONDecodeError as e:
logger.warning(f"Failed to parse NOTIFY_WEBHOOK_HEADERS as JSON: {e}")
if NOTIFY_WEBHOOK_METHOD == "GET":
requests.get(NOTIFY_WEBHOOK_URL, params=payload, headers=headers, timeout=5)
else:
requests.post(NOTIFY_WEBHOOK_URL, json=payload, headers=headers, timeout=5)
except Exception as e:
logger.error(f"Failed to send webhook notification: {e}")
state_lock = threading.RLock()
state: Dict[str, Any] = {
"queue": [],
"current_request": None,
"scheduled_show_active": False,
"last_status": {},
"next_show": None,
"note": "",
"background_active": False,
}
# Statistics storage
# STATISTICS_FILE uses a data directory that can be mounted as a volume in Docker
# Falls back to app directory if data directory doesn't exist (for development)
STATISTICS_DIR = os.path.join(os.path.dirname(__file__), "data")
if not os.path.exists(STATISTICS_DIR):
os.makedirs(STATISTICS_DIR, exist_ok=True)
STATISTICS_FILE = os.path.join(STATISTICS_DIR, "statistics.json")
statistics_lock = threading.RLock()
def load_statistics() -> Dict[str, Any]:
"""Load statistics from persistent storage."""
if not os.path.exists(STATISTICS_FILE):
return {"show_starts": [], "song_requests": []}
try:
with open(STATISTICS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.error(f"Failed to load statistics: {e}")
return {"show_starts": [], "song_requests": []}
def save_statistics(stats: Dict[str, Any]) -> None:
"""Save statistics to persistent storage with atomic write.
Note: Writes immediately on each event. For typical home automation usage with low
event frequency (few show starts/song requests per hour), this is acceptable.
For high-traffic scenarios, consider implementing a write buffer.
"""
try:
# Atomic write: write to temp file first, then rename
temp_file = STATISTICS_FILE + ".tmp"
with open(temp_file, "w", encoding="utf-8") as f:
json.dump(stats, f, ensure_ascii=False, indent=2)
os.replace(temp_file, STATISTICS_FILE)
except Exception as e:
logger.error(f"Failed to save statistics: {e}")
def log_show_start(playlist: str, playlist_type: str) -> None:
"""Log a show start event."""
with statistics_lock:
stats = load_statistics()
stats["show_starts"].append({
"timestamp": dt_datetime.now().isoformat(),
"playlist": playlist,
"playlist_type": playlist_type
})
save_statistics(stats)
def log_song_request(song_title: str, duration: Optional[int]) -> None:
"""Log a song request event."""
with statistics_lock:
stats = load_statistics()
stats["song_requests"].append({
"timestamp": dt_datetime.now().isoformat(),
"song_title": song_title,
"duration": duration
})
save_statistics(stats)
def normalize(name: Optional[str]) -> str:
if isinstance(name, str):
return name.strip().lower()
if isinstance(name, dict):
for key in ["playlist", "name", "title"]:
if isinstance(name.get(key), str):
return name[key].strip().lower()
return str(name or "").strip().lower() if name is not None else ""
def format_duration(duration: Optional[int]) -> str:
"""Format duration in seconds to MM:SS string.
Args:
duration: Duration in seconds, or None
Returns:
Formatted string like "3:25" or "unbekannt" if duration is None
"""
if duration is None:
return "unbekannt"
minutes = duration // 60
seconds = duration % 60
return f"{minutes}:{seconds:02d}"
def extract_playlist_name(payload: Dict[str, Any]) -> str:
for key in ["playlist", "current_playlist", "playlist_name"]:
value = payload.get(key)
if isinstance(value, str) and value:
return value
if isinstance(value, dict):
for inner_key in ["playlist", "name", "title"]:
inner_value = value.get(inner_key)
if isinstance(inner_value, str) and inner_value:
return inner_value
return ""
def local_now() -> dt_datetime:
return dt_datetime.now().astimezone()
def _parse_date(date_str: Optional[str]):
if not date_str:
return None
try:
return dt_datetime.fromisoformat(date_str).date()
except ValueError:
return None
SHOW_START = _parse_date(SHOW_START_DATE)
SHOW_END = _parse_date(SHOW_END_DATE)
def _parse_time(time_str: Optional[str], default_hour: int, default_minute: int) -> dt_time:
"""Parse a time string in HH:MM format."""
if not time_str:
return dt_time(hour=default_hour, minute=default_minute)
try:
parts = time_str.split(":")
hour = int(parts[0])
minute = int(parts[1]) if len(parts) > 1 else 0
return dt_time(hour=hour, minute=minute)
except (ValueError, IndexError):
return dt_time(hour=default_hour, minute=default_minute)
SHOW_TIME_START = _parse_time(SHOW_START_TIME, 16, 30)
SHOW_TIME_END = _parse_time(SHOW_END_TIME, 22, 0)
def is_within_show_window(moment: Optional[dt_datetime] = None) -> bool:
now = moment or local_now()
current_date = now.date()
if SHOW_START and current_date < SHOW_START:
return False
if SHOW_END and current_date > SHOW_END:
return False
return True
def is_quiet_hours(now: Optional[dt_datetime] = None) -> bool:
"""Return True if controls/playback should be disabled for quiet time.
Quiet hours are outside the configured show time window (SHOW_TIME_START to SHOW_TIME_END).
"""
current = now or local_now()
start_t = SHOW_TIME_START.replace(tzinfo=current.tzinfo)
end_t = SHOW_TIME_END.replace(tzinfo=current.tzinfo)
current_t = current.timetz()
# If end is after start (e.g., 16:30 to 22:00), we're in quiet hours if outside that range
if start_t <= end_t:
return current_t < start_t or current_t >= end_t
else:
# If end is before start (crosses midnight), we're in quiet hours if current >= end and current < start
return current_t >= end_t and current_t < start_t
def compute_next_show(now: Optional[dt_datetime] = None) -> Dict[str, Any]:
now = now or local_now()
if not is_within_show_window(now):
# If we are before the window, calculate from the first valid day.
if SHOW_START and now.date() < SHOW_START:
now = dt_datetime.combine(SHOW_START, dt_time(0, tzinfo=now.tzinfo))
else:
return {}
schedule = [
(17, PLAYLIST_2, PLAYLIST_2),
(18, PLAYLIST_1, PLAYLIST_1),
(19, PLAYLIST_1, PLAYLIST_1),
(20, PLAYLIST_1, PLAYLIST_1),
(21, PLAYLIST_1, PLAYLIST_1),
]
for day_offset in range(0, 14):
day = (now + dt_timedelta(days=day_offset)).date()
if SHOW_START and day < SHOW_START:
continue
if SHOW_END and day > SHOW_END:
break
for hour, playlist, label in schedule:
candidate = dt_datetime.combine(day, dt_time(hour=hour, tzinfo=now.tzinfo))
if candidate > now:
return {"time": candidate, "playlist": playlist, "label": label}
return {}
def compute_locks(status: Dict[str, Any], queue: List[Dict[str, Any]], current_request: Any) -> Dict[str, Any]:
playlist_norm = normalize(status.get("playlist_name"))
playlist1_norm = normalize(PLAYLIST_1)
playlist2_norm = normalize(PLAYLIST_2)
request_norm = normalize(PLAYLIST_REQUESTS)
temp_norm = normalize("__wish_single__")
standard_running = status.get("is_running") and playlist_norm in {playlist1_norm, playlist2_norm}
wish_running = (status.get("is_running") and playlist_norm in {request_norm, temp_norm}) or bool(current_request)
quiet = is_quiet_hours()
outside_window = not is_within_show_window()
# Format show period info for display
start_time_str = SHOW_TIME_START.strftime("%H:%M")
end_time_str = SHOW_TIME_END.strftime("%H:%M")
start_date_str = SHOW_START.strftime("%d.%m.%Y") if SHOW_START else ""
end_date_str = SHOW_END.strftime("%d.%m.%Y") if SHOW_END else ""
reason = None
if outside_window:
date_range = f"{start_date_str} - {end_date_str}" if start_date_str and end_date_str else ""
time_range = f"{start_time_str} - {end_time_str}"
period_info = f"{date_range} | {time_range}" if date_range else time_range
reason = f"Außerhalb des Showzeitraums\n{period_info}\nAktuell keine Wiedergabe möglich."
elif quiet:
reason = f"Ruhezeit {end_time_str}–{start_time_str} – keine Wiedergabe möglich."
elif standard_running:
reason = "Aktuell läuft eine Show – alle Aktionen sind gesperrt."
elif wish_running:
reason = "Ein Wunsch läuft – Shows können nicht gestartet werden."
return {
"disableAllButtons": bool(standard_running or quiet or outside_window),
"disableShowButtons": bool(standard_running or wish_running or quiet or outside_window),
"outsideShowWindow": outside_window,
"quiet": quiet,
"reason": reason,
"showPeriod": {
"startDate": start_date_str,
"endDate": end_date_str,
"startTime": start_time_str,
"endTime": end_time_str,
},
}
def enforce_access_code(payload: Optional[Dict[str, Any]] = None):
if not ACCESS_CODE:
return None
provided_code = (
request.headers.get("X-Access-Code")
or request.headers.get("X-Access-Token")
or request.args.get("accessCode")
or request.args.get("access_code")
)
if provided_code is None and payload:
provided_code = payload.get("accessCode") or payload.get("access_code")
if provided_code == ACCESS_CODE:
return None
return jsonify({"ok": False, "message": "Access code required."}), 403
def _get_cached_payload() -> Dict[str, Any]:
if hasattr(g, "_cached_json_payload"):
return g._cached_json_payload
payload = request.get_json(force=True, silent=True) or {}
g._cached_json_payload = payload
return payload
PROTECTED_ENDPOINTS = {("api_show", "POST"), ("api_requests", "POST")}
PROTECTED_PATHS = {"/api/show", "/api/requests"}
@app.before_request
def enforce_access_code_on_control_routes():
if not ACCESS_CODE:
return None
if request.method == "OPTIONS":
return None
endpoint = request.endpoint
if (endpoint, request.method) not in PROTECTED_ENDPOINTS and request.path not in PROTECTED_PATHS:
return None
payload = _get_cached_payload()
denied = enforce_access_code(payload)
if denied:
return denied
def fetch_fpp_status() -> Dict[str, Any]:
resp = requests.get(f"{FPP_BASE_URL}/api/fppd/status", timeout=REQUEST_TIMEOUT)
resp.raise_for_status()
payload = resp.json()
name = normalize(payload.get("status_name") or payload.get("status") or "")
playlist_raw = extract_playlist_name(payload)
playlist_name = normalize(playlist_raw)
is_running = name in {"playing", "running", "playing playlist", "playlist"}
return {
"raw": payload,
"is_running": is_running,
"playlist_name": playlist_name,
"mode_name": payload.get("mode_name") or payload.get("mode"),
"current_sequence": payload.get("current_sequence") or payload.get("current_song"),
"playlist_label": playlist_raw,
}
def start_playlist(name: str) -> None:
"""Start a playlist using documented FPP endpoints.
Preferred path is the documented ``GET /api/playlist/:PlaylistName/start``.
For older command-driven flows, fall back to the command API using
``Start Playlist`` as described in the commands list.
"""
playlist_slug = requests.utils.quote(name, safe="")
errors: List[str] = []
# Documented playlist start endpoint.
try:
resp = requests.get(
f"{FPP_BASE_URL}/api/playlist/{playlist_slug}/start", timeout=REQUEST_TIMEOUT
)
resp.raise_for_status()
return
except requests.RequestException as exc:
errors.append(str(exc))
# Fallback via command API.
try:
resp = requests.post(
f"{FPP_BASE_URL}/api/command/Start%20Playlist/{playlist_slug}",
timeout=REQUEST_TIMEOUT,
)
resp.raise_for_status()
return
except requests.RequestException as exc:
errors.append(str(exc))
raise requests.RequestException("; ".join(errors))
def stop_effects_and_blackout() -> None:
stop_background_effect()
for path in ["StopEffects", "StopPlaylist", "DisableOutputs"]:
try:
requests.get(f"{FPP_BASE_URL}/api/command/{path}", timeout=REQUEST_TIMEOUT)
except requests.RequestException:
continue
try:
requests.get(f"{FPP_BASE_URL}/api/playlists/stop", timeout=REQUEST_TIMEOUT)
except requests.RequestException:
pass
def stop_background_effect() -> None:
if not BACKGROUND_EFFECT:
return
slug = requests.utils.quote(BACKGROUND_EFFECT, safe="")
for path in [
f"{FPP_BASE_URL}/api/command/Stop%20Effect/{slug}",
f"{FPP_BASE_URL}/api/command/StopEffect/{slug}",
]:
try:
requests.get(path, timeout=REQUEST_TIMEOUT)
break
except requests.RequestException:
continue
with state_lock:
state["background_active"] = False
def start_background_effect() -> None:
if not BACKGROUND_EFFECT or is_quiet_hours():
return
with state_lock:
if state.get("background_active"):
return
slug = requests.utils.quote(BACKGROUND_EFFECT, safe="")
for path in [
f"{FPP_BASE_URL}/api/command/Start%20Effect/{slug}",
f"{FPP_BASE_URL}/api/command/StartEffect/{slug}",
]:
try:
resp = requests.get(path, timeout=REQUEST_TIMEOUT)
resp.raise_for_status()
with state_lock:
state["background_active"] = True
return
except requests.RequestException:
continue
def resume_background_effect() -> None:
if is_quiet_hours():
stop_background_effect()
return
start_background_effect()
def delete_playlist(name: str) -> None:
slug = requests.utils.quote(name, safe="")
try:
requests.delete(f"{FPP_BASE_URL}/api/playlist/{slug}", timeout=REQUEST_TIMEOUT)
except requests.RequestException:
pass
def build_single_song_playlist(entry: Dict[str, Any]) -> str:
"""Create a temporary playlist containing only the requested song.
Returns the name of the temporary playlist.
"""
temp_name = "__wish_single__"
delete_playlist(temp_name)
seq = entry.get("sequenceName") or entry.get("sequence")
media = entry.get("mediaName") or entry.get("media")
duration = entry.get("duration")
body = {
"name": temp_name,
"mainPlaylist": [
{
"type": "both" if seq and media else "sequence",
"enabled": 1,
"playOnce": 1,
"sequenceName": seq,
"mediaName": media,
"duration": duration,
}
],
"playlistInfo": {"total_items": 1},
}
slug = requests.utils.quote(temp_name, safe="")
resp = requests.post(
f"{FPP_BASE_URL}/api/playlist/{slug}", json=body, timeout=REQUEST_TIMEOUT
)
resp.raise_for_status()
return temp_name
def start_request_song(entry: Dict[str, Any]) -> None:
stop_effects_and_blackout()
seq = entry.get("sequenceName") or entry.get("sequence")
media = entry.get("mediaName") or entry.get("media")
if seq or media:
playlist_name = build_single_song_playlist(entry)
start_playlist(playlist_name)
else:
# Fallback: play the full wishlist playlist when sequence/media are missing.
start_playlist(PLAYLIST_REQUESTS)
def update_next_show():
with state_lock:
state["next_show"] = compute_next_show()
def mark_note(message: str) -> None:
with state_lock:
state["note"] = message
def status_worker():
update_next_show()
while True:
try:
status = fetch_fpp_status()
except Exception:
time.sleep(POLL_INTERVAL_SECONDS)
continue
# Plan actions without holding the lock during network calls.
action = None
entry_to_start: Optional[Dict[str, Any]] = None
delete_temp = False
with state_lock:
state["last_status"] = status
queue: List[Dict[str, Any]] = state["queue"]
current_request = state.get("current_request")
scheduled_active = state.get("scheduled_show_active", False)
playlist_match_requests = normalize(PLAYLIST_REQUESTS) == status.get("playlist_name")
playlist_match_temp = normalize("__wish_single__") == status.get("playlist_name")
if status.get("is_running"):
# If a scheduled show is running, ensure queue is paused.
if scheduled_active and (playlist_match_requests or playlist_match_temp):
# Unexpected playlist; mark for restart after schedule.
state["current_request"] = None
if current_request and not (playlist_match_requests or playlist_match_temp):
# request was interrupted
state["current_request"] = None
else:
delete_temp = True
# No playlist running: advance queue or resume after schedule.
if is_quiet_hours():
state["current_request"] = None
action = "stop_background"
elif scheduled_active:
state["scheduled_show_active"] = False
if queue:
# resume queued wishes
entry_to_start = queue[0]
action = "start_entry"
else:
action = "resume_background"
elif current_request:
# request finished
if queue and queue[0] == current_request:
queue.pop(0)
state["current_request"] = None
if queue:
entry_to_start = queue[0]
action = "start_entry"
else:
action = "resume_background"
elif queue and not is_quiet_hours():
entry_to_start = queue[0]
action = "start_entry"
else:
action = "resume_background"
# Execute slow operations outside the lock to avoid blocking /api/state.
if delete_temp:
delete_playlist("__wish_single__")
if action == "stop_background":
stop_background_effect()
elif action == "resume_background":
resume_background_effect()
elif action == "start_entry" and entry_to_start:
try:
start_request_song(entry_to_start)
with state_lock:
state["current_request"] = entry_to_start
except requests.RequestException:
with state_lock:
state["current_request"] = None
time.sleep(POLL_INTERVAL_SECONDS)
def scheduler_worker():
update_next_show()
while True:
# Skip scheduled shows if disabled - use longer sleep since no work is needed
if not SCHEDULED_SHOWS_ENABLED:
time.sleep(300)
continue
with state_lock:
info = state.get("next_show")
now = local_now()
if info and info.get("time") <= now:
if is_quiet_hours(info.get("time")):
update_next_show()
time.sleep(1)
continue
playlist = info.get("playlist")
with state_lock:
state["scheduled_show_active"] = True
state["current_request"] = None
try:
stop_effects_and_blackout()
start_playlist(playlist)
except requests.RequestException:
mark_note("Geplante Show konnte nicht gestartet werden.")
update_next_show()
time.sleep(1)
@app.route("/")
def root():
return send_from_directory(".", "index.html")
@app.route("/styles.css")
def styles():
return send_from_directory(".", "styles.css")
@app.route("/donation")
def donation_page():
return send_from_directory(".", "donation.html")
@app.route("/requests")
def requests_page():
return send_from_directory(".", "requests.html")
@app.route("/statistics")
def statistics_page():
return send_from_directory(".", "statistics.html")
@app.route("/config.js")
def config_js():
return send_from_directory(".", "config.js")
@app.route("/api/state")
def api_state():
with state_lock:
info = state.copy()
next_show = info.get("next_show")
next_show_time = next_show["time"].isoformat() if next_show else None
locks = compute_locks(info.get("last_status", {}), info.get("queue", []), info.get("current_request"))
return jsonify(
{
"siteName": SITE_NAME,
"queue": info.get("queue", []),
"currentRequest": info.get("current_request"),
"scheduledShowActive": info.get("scheduled_show_active", False),
"scheduledShowsEnabled": SCHEDULED_SHOWS_ENABLED,
"note": info.get("note", ""),
"status": info.get("last_status", {}),
"nextShow": {
"time": next_show_time,
"playlist": next_show.get("playlist") if next_show else None,
"label": next_show.get("label") if next_show else None,
},
"locks": locks,
}
)
@app.route("/api/show", methods=["POST"])
def api_show():
payload = _get_cached_payload()
denied = enforce_access_code(payload)
if denied:
return denied
kind = payload.get("type", "playlist1")
playlist = PLAYLIST_2 if kind == "playlist2" else PLAYLIST_1
playlist_label = "Hauptshow" if kind == "playlist1" else "Kids-Show"
# Log show start to statistics
log_show_start(playlist, kind)
# Send notification (before FPP operations, so it works in preview mode too)
send_notification(
title=f"{playlist_label} gestartet",
message=f"Ein Besucher hat '{playlist}' gestartet.",
action_type="show_start",
extra_data={"playlist": playlist, "playlist_type": kind}
)
with state_lock:
state["scheduled_show_active"] = False
try:
stop_effects_and_blackout()
start_playlist(playlist)
mark_note(f"Playlist '{playlist}' wurde gestartet.")
return jsonify({"ok": True, "message": f"{playlist} gestartet."})
except requests.RequestException as exc:
return jsonify({"ok": False, "message": str(exc)}), 502
def _extract_song(entry: Dict[str, Any], idx: int) -> Dict[str, Any]:
title = (
entry.get("note")
or entry.get("name")
or entry.get("song")
or entry.get("title")
or entry.get("sequenceName")
or entry.get("mediaName")
or f"Titel {idx + 1}"
)
duration = entry.get("duration")
if duration is None:
duration = entry.get("seconds") or entry.get("length") or entry.get("time")
try:
duration = int(duration) if duration is not None else None
except (TypeError, ValueError):
duration = None
return {
"title": title,
"duration": duration,
"sequenceName": entry.get("sequenceName") or entry.get("sequence"),
"mediaName": entry.get("mediaName") or entry.get("media"),
}
def _extract_entries(data: Any) -> List[Dict[str, Any]]:
"""Return playlist entries regardless of FPP schema variants.
Different FPP versions expose playlist contents under slightly different
keys/shapes. This helper tries common shapes before falling back to an
empty list.
"""
candidates: List[Any] = []
# Raw list response
if isinstance(data, list):
return data
if isinstance(data, dict):
# Direct keys on root
for key in [
"playlist",
"entries",
"sequence",
"sequences",
"items",
"entry",
"Seqs",
"mainPlaylist",
]:
if key in data:
candidates.append(data.get(key))
# Nested playlist object
playlist_obj = data.get("playlist") or data.get("Playlist")
if isinstance(playlist_obj, dict):
for key in [
"playlist",
"entries",
"sequence",
"sequences",
"items",
"entry",
"Seqs",
"mainPlaylist",
]:
if key in playlist_obj:
candidates.append(playlist_obj.get(key))
for candidate in candidates:
if isinstance(candidate, list):
return candidate
return []
@app.route("/api/requests/songs")