Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
1898 lines (1523 loc) · 66.2 KB
/
Copy pathserver.py
File metadata and controls
1898 lines (1523 loc) · 66.2 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
from __future__ import annotations
import asyncio
import hmac
import json
import os
import re
import secrets
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import bcrypt
from aiohttp import ClientSession, ClientTimeout, web
from plugins import load_plugins
from plugins.base import PluginContext, PluginField, ScreenPlugin
PROJECT_ROOT = Path(__file__).resolve().parent
USER_DATA_DIR = Path.home() / '.flipoff'
CONFIG_PATH = USER_DATA_DIR / 'config.json'
SCREENS_PATH = USER_DATA_DIR / 'screens.json'
DEFAULT_BOARD_SLUG = 'main'
DEFAULT_BOARD_NAME = 'Main Board'
# Load defaults from config.json (same file the frontend uses).
# This keeps messages, grid size, and timing in sync between server and client.
_FRONTEND_CONFIG_PATH = PROJECT_ROOT / 'config.json'
_FRONTEND_DEFAULTS: dict[str, Any] = {}
try:
if _FRONTEND_CONFIG_PATH.exists():
with _FRONTEND_CONFIG_PATH.open('r', encoding='utf-8') as _f:
_FRONTEND_DEFAULTS = json.load(_f)
except (json.JSONDecodeError, OSError):
pass
_GRID = _FRONTEND_DEFAULTS.get('grid', {})
_TIMING = _FRONTEND_DEFAULTS.get('timing', {})
DEFAULT_COLS = int(_GRID.get('cols', 22))
DEFAULT_ROWS = int(_GRID.get('rows', 5))
DEFAULT_MESSAGE_DURATION_SECONDS = int(_TIMING.get('messageDurationSeconds', 4))
DEFAULT_API_MESSAGE_DURATION_SECONDS = int(_TIMING.get('apiMessageDurationSeconds', 30))
# Filter out dynamic markers ({"dynamic": "..."}) — the server only handles static messages.
_RAW_MESSAGES = _FRONTEND_DEFAULTS.get('messages', [])
DEFAULT_MESSAGES = [m for m in _RAW_MESSAGES if isinstance(m, list)]
if not DEFAULT_MESSAGES:
DEFAULT_MESSAGES = [
['', '🏛️ GOD IS IN', 'THE DETAILS .', '(LUDWIG MIES)', ''],
['', '🍎 STAY HUNGRY', 'STAY FOOLISH', '(STEVE JOBS)', ''],
['', '🎯 MAKE IT SIMPLE', 'BUT SIGNIFICANT', '(DON DRAPER)', ''],
]
SLUG_PATTERN = re.compile(r'^[a-z0-9]+(?:-[a-z0-9]+)*$')
RESERVED_BOARD_SLUGS = {'admin', 'api', 'css', 'js', 'ws', 'screenshot.png', 'favicon.ico', 'index.html'}
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
@dataclass(slots=True)
class DisplayConfig:
slug: str
name: str
cols: int
rows: int
default_messages: list[list[str]]
message_duration_seconds: int
api_message_duration_seconds: int
def serialize(self) -> dict[str, Any]:
return {
'boardSlug': self.slug,
'boardName': self.name,
'cols': self.cols,
'rows': self.rows,
'defaultMessages': [message.copy() for message in self.default_messages],
'messageDurationSeconds': self.message_duration_seconds,
'apiMessageDurationSeconds': self.api_message_duration_seconds,
}
def serialize_settings(self) -> dict[str, Any]:
return {
'slug': self.slug,
'name': self.name,
'cols': self.cols,
'rows': self.rows,
'messageDurationSeconds': self.message_duration_seconds,
'apiMessageDurationSeconds': self.api_message_duration_seconds,
}
@dataclass(slots=True)
class MessageState:
has_override: bool = False
lines: list[str] = field(default_factory=list)
updated_at: str | None = None
def serialize(self) -> dict[str, Any]:
return {
'hasOverride': self.has_override,
'lines': self.lines.copy(),
'updatedAt': self.updated_at,
}
def set_override(self, lines: list[str]) -> None:
self.has_override = True
self.lines = lines.copy()
self.updated_at = _utc_now()
def clear(self, rows: int) -> None:
self.has_override = False
self.lines = [''] * rows
self.updated_at = None
@dataclass(slots=True)
class AdminPasswordState:
password_hash: str # bcrypt hash
generated: bool = False
_plaintext_for_announce: str | None = None # only set on generated passwords, cleared after announce
@dataclass(slots=True)
class ScreenState:
screens: list[dict[str, Any]] = field(default_factory=list)
common_settings: dict[str, Any] = field(default_factory=dict)
refresh_tasks: dict[str, asyncio.Task] = field(default_factory=dict)
@dataclass(slots=True)
class BoardState:
config: DisplayConfig
screens: list[dict[str, Any]] = field(default_factory=list)
message_state: MessageState = field(default_factory=MessageState)
refresh_tasks: dict[str, asyncio.Task] = field(default_factory=dict)
override_task: asyncio.Task | None = None
@dataclass(slots=True)
class BoardRegistry:
boards: dict[str, BoardState] = field(default_factory=dict)
default_board_slug: str = DEFAULT_BOARD_SLUG
common_settings: dict[str, Any] = field(default_factory=dict)
DISPLAY_CONFIG_KEY = web.AppKey('display_config', object)
MESSAGE_STATE_KEY = web.AppKey('message_state', object)
SCREEN_STATE_KEY = web.AppKey('screen_state', object)
BOARD_REGISTRY_KEY = web.AppKey('board_registry', BoardRegistry)
WS_CLIENTS_KEY = web.AppKey('ws_clients', dict)
ADMIN_PASSWORD_STATE_KEY = web.AppKey('admin_password_state', AdminPasswordState)
ADMIN_LOCK_KEY = web.AppKey('admin_lock', asyncio.Lock)
MAX_SESSION_TOKENS = 100
def hash_password(password: str) -> str:
"""Hash a password with bcrypt."""
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def verify_password(password: str, password_hash: str) -> bool:
"""Constant-time password verification."""
try:
return bcrypt.checkpw(password.encode(), password_hash.encode())
except (ValueError, TypeError):
return False
SESSION_TOKENS_KEY = web.AppKey('session_tokens', set)
CONFIG_PATH_KEY = web.AppKey('config_path', object)
SCREENS_PATH_KEY = web.AppKey('screens_path', object)
PLUGINS_KEY = web.AppKey('plugins', dict)
PLUGIN_HTTP_SESSION_KEY = web.AppKey('plugin_http_session', object)
def slugify(value: str) -> str:
normalized = re.sub(r'[^a-z0-9]+', '-', value.strip().lower())
normalized = re.sub(r'-{2,}', '-', normalized).strip('-')
return normalized
def _coerce_slug(value: Any, field_name: str) -> str:
if not isinstance(value, str):
raise ValueError(f"'{field_name}' must be a string.")
normalized = slugify(value)
if not normalized:
raise ValueError(f"'{field_name}' must contain letters or numbers.")
if normalized in RESERVED_BOARD_SLUGS:
raise ValueError(f"'{field_name}' uses a reserved slug.")
if not SLUG_PATTERN.fullmatch(normalized):
raise ValueError(f"'{field_name}' must contain only lowercase letters, numbers, and hyphens.")
return normalized
def _suggest_slug(value: Any, fallback: str) -> str:
if isinstance(value, str):
normalized = slugify(value)
if normalized:
return normalized
return fallback
def _make_unique_slug(base_slug: str, seen_slugs: set[str]) -> str:
candidate = base_slug
suffix = 2
while candidate in seen_slugs:
candidate = f'{base_slug}-{suffix}'
suffix += 1
return candidate
def _coerce_int(value: Any, field_name: str, minimum: int, maximum: int) -> int:
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"'{field_name}' must be an integer.")
if not minimum <= value <= maximum:
raise ValueError(f"'{field_name}' must be between {minimum} and {maximum}.")
return value
def _coerce_bool(value: Any, field_name: str) -> bool:
if not isinstance(value, bool):
raise ValueError(f"'{field_name}' must be a boolean.")
return value
def _coerce_optional_string(value: Any, field_name: str) -> str:
if value is None:
return ''
if not isinstance(value, str):
raise ValueError(f"'{field_name}' must be a string.")
return value.strip()
def pad_lines(lines: list[str], rows: int) -> list[str]:
return lines + [''] * max(0, rows - len(lines))
def center_lines(lines: list[str], rows: int) -> list[str]:
top_padding = max(0, (rows - len(lines)) // 2)
bottom_padding = max(0, rows - len(lines) - top_padding)
return [''] * top_padding + lines + [''] * bottom_padding
def trim_message_lines(message: list[str]) -> list[str]:
trimmed = message.copy()
while len(trimmed) > 1 and trimmed[-1] == '':
trimmed.pop()
return trimmed
def normalize_message_lines(
lines: Any,
*,
cols: int,
rows: int,
field_name: str,
allow_empty: bool = False,
) -> list[str]:
if not isinstance(lines, list):
raise ValueError(f"'{field_name}' must be an array of strings.")
if not lines and allow_empty:
return []
if not 1 <= len(lines) <= rows:
raise ValueError(f"'{field_name}' must contain between 1 and {rows} items.")
normalized: list[str] = []
for index, line in enumerate(lines, start=1):
if not isinstance(line, str):
raise ValueError(f"{field_name} line {index} must be a string.")
normalized_line = line.strip().upper()
if len(normalized_line) > cols:
raise ValueError(f"{field_name} line {index} exceeds {cols} characters.")
normalized.append(normalized_line)
return trim_message_lines(normalized)
def normalize_default_messages(messages: Any, cols: int, rows: int) -> list[list[str]]:
if not isinstance(messages, list) or len(messages) == 0:
raise ValueError("'defaultMessages' must be a non-empty array of message arrays.")
return [
pad_lines(
normalize_message_lines(
message,
cols=cols,
rows=rows,
field_name=f'defaultMessages[{index}]',
),
rows,
)
for index, message in enumerate(messages)
]
def normalize_runtime_settings_payload(payload: Any) -> tuple[int, int, int, int]:
if not isinstance(payload, dict):
raise ValueError('Request body must be a JSON object.')
cols = _coerce_int(payload.get('cols'), 'cols', 6, 256)
rows = _coerce_int(payload.get('rows'), 'rows', 1, 128)
message_duration_seconds = _coerce_int(
payload.get('messageDurationSeconds', DEFAULT_MESSAGE_DURATION_SECONDS),
'messageDurationSeconds',
1,
86400,
)
api_message_duration_seconds = _coerce_int(
payload.get('apiMessageDurationSeconds'),
'apiMessageDurationSeconds',
1,
86400,
)
return cols, rows, message_duration_seconds, api_message_duration_seconds
def default_display_config(
*,
slug: str = DEFAULT_BOARD_SLUG,
name: str = DEFAULT_BOARD_NAME,
) -> DisplayConfig:
return DisplayConfig(
slug=slug,
name=name,
cols=DEFAULT_COLS,
rows=DEFAULT_ROWS,
default_messages=[message.copy() for message in DEFAULT_MESSAGES],
message_duration_seconds=DEFAULT_MESSAGE_DURATION_SECONDS,
api_message_duration_seconds=DEFAULT_API_MESSAGE_DURATION_SECONDS,
)
def load_config_payload(config_path: Path | None) -> dict[str, Any]:
if config_path is None or not config_path.exists():
return {}
with config_path.open('r', encoding='utf-8') as config_file:
payload = json.load(config_file)
if not isinstance(payload, dict):
raise ValueError('Config file must contain a JSON object.')
return payload
def normalize_board_settings_entry(payload: Any, *, index: int, seen_slugs: set[str]) -> DisplayConfig:
if not isinstance(payload, dict):
raise ValueError(f'Board {index} must be a JSON object.')
requested_slug = payload.get('slug')
if requested_slug is None:
slug = _make_unique_slug(
_suggest_slug(payload.get('name'), f'board-{index}'),
seen_slugs,
)
else:
slug = _coerce_slug(requested_slug, f'boards[{index}].slug')
if slug in seen_slugs:
raise ValueError(f"Duplicate board slug '{slug}' is not allowed.")
seen_slugs.add(slug)
name = _coerce_optional_string(payload.get('name'), f'boards[{index}].name') or slug.replace('-', ' ').title()
cols, rows, message_duration_seconds, api_message_duration_seconds = normalize_runtime_settings_payload(payload)
8
retur
10BC8
n DisplayConfig(
slug=slug,
name=name,
cols=cols,
rows=rows,
default_messages=[],
message_duration_seconds=message_duration_seconds,
api_message_duration_seconds=api_message_duration_seconds,
)
def load_board_configs(config_path: Path | None) -> tuple[list[DisplayConfig], str]:
payload = load_config_payload(config_path)
if not payload:
return [default_display_config()], DEFAULT_BOARD_SLUG
if isinstance(payload.get('boards'), list):
seen_slugs: set[str] = set()
boards = [
normalize_board_settings_entry(raw_board, index=index, seen_slugs=seen_slugs)
for index, raw_board in enumerate(payload['boards'], start=1)
]
if not boards:
raise ValueError("'boards' must contain at least one board.")
default_board_slug = payload.get('defaultBoardSlug')
if not isinstance(default_board_slug, str) or default_board_slug not in {board.slug for board in boards}:
default_board_slug = boards[0].slug
return boards, default_board_slug
legacy_slug = DEFAULT_BOARD_SLUG
cols, rows, message_duration_seconds, api_message_duration_seconds = normalize_runtime_settings_payload(payload)
return [
DisplayConfig(
slug=legacy_slug,
name=DEFAULT_BOARD_NAME,
cols=cols,
rows=rows,
default_messages=[],
message_duration_seconds=message_duration_seconds,
api_message_duration_seconds=api_message_duration_seconds,
)
], legacy_slug
def save_board_settings(
config_path: Path | None,
registry: BoardRegistry,
*,
admin_password_hash: str,
) -> None:
if config_path is None:
return
config_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
'defaultBoardSlug': registry.default_board_slug,
'boards': [board.config.serialize_settings() for board in registry.boards.values()],
'pluginCommonSettings': registry.common_settings,
'adminPasswordHash': admin_password_hash,
}
with config_path.open('w', encoding='utf-8') as config_file:
json.dump(payload, config_file, indent=2)
config_file.write('\n')
def load_admin_password_hash(config_path: Path | None) -> str | None:
"""Load the bcrypt hash from persisted config. Also handles legacy plaintext passwords by rehashing them."""
payload = load_config_payload(config_path)
# New format: bcrypt hash
raw_hash = payload.get('adminPasswordHash')
if isinstance(raw_hash, str) and raw_hash.strip():
return raw_hash.strip()
# Legacy format: plaintext password — migrate on next save
raw_password = payload.get('adminPassword')
if isinstance(raw_password, str) and raw_password.strip():
return hash_password(raw_password.strip())
return None
def collect_common_settings_schemas(plugins: dict[str, ScreenPlugin]) -> dict[str, tuple[PluginField, ...]]:
schemas: dict[str, tuple[PluginField, ...]] = {}
for plugin in plugins.values():
namespace = plugin.manifest.common_settings_namespace
if not namespace:
continue
schemas.setdefault(namespace, plugin.manifest.common_settings_schema)
return schemas
def normalize_schema_values(
values: Any,
schema: tuple[PluginField, ...],
*,
section_name: str,
) -> dict[str, Any]:
if values is None:
values = {}
if not isinstance(values, dict):
raise ValueError(f"'{section_name}' must be a JSON object.")
normalized: dict[str, Any] = {}
for field in schema:
raw_value = values.get(field.name, field.default)
if field.field_type == 'text':
if raw_value is None:
raw_value = ''
if not isinstance(raw_value, str):
raise ValueError(f"'{section_name}.{field.name}' must be a string.")
normalized_value = raw_value.strip()
if field.required and not normalized_value:
raise ValueError(f"'{section_name}.{field.name}' is required.")
normalized[field.name] = normalized_value
continue
if field.field_type == 'select':
if raw_value is None:
raw_value = field.default
if not isinstance(raw_value, str):
raise ValueError(f"'{section_name}.{field.name}' must be a string.")
valid_values = {option.value for option in field.options}
if raw_value not in valid_values:
raise ValueError(f"'{section_name}.{field.name}' must be one of the allowed options.")
normalized[field.name] = raw_value
continue
if field.field_type == 'checkbox':
normalized[field.name] = _coerce_bool(raw_value, f'{section_name}.{field.name}')
continue
if field.field_type == 'number':
if not isinstance(raw_value, (int, float)) or isinstance(raw_value, bool):
raise ValueError(f"'{section_name}.{field.name}' must be numeric.")
normalized[field.name] = raw_value
continue
raise ValueError(f"Unsupported schema field type '{field.field_type}'.")
return normalized
def normalize_plugin_common_settings(payload: Any, *, plugins: dict[str, ScreenPlugin]) -> dict[str, Any]:
schemas = collect_common_settings_schemas(plugins)
normalized: dict[str, Any] = {}
if payload is None:
payload = {}
if not isinstance(payload, dict):
raise ValueError("'pluginCommonSettings' must be a JSON object.")
for namespace, schema in schemas.items():
normalized[namespace] = normalize_schema_values(
payload.get(namespace),
schema,
section_name=f'pluginCommonSettings.{namespace}',
)
return normalized
def load_plugin_common_settings(config_path: Path | None, *, plugins: dict[str, ScreenPlugin]) -> dict[str, Any]:
payload = load_config_payload(config_path)
if not payload:
return normalize_plugin_common_settings(None, plugins=plugins)
return normalize_plugin_common_settings(payload.get('pluginCommonSettings'), plugins=plugins)
def generate_screen_id() -> str:
return secrets.token_hex(8)
def build_manual_screens_from_messages(
messages: Any | None,
*,
cols: int,
rows: int,
) -> list[dict[str, Any]]:
if messages is None:
messages = [message.copy() for message in DEFAULT_MESSAGES]
normalized_messages = normalize_default_messages(messages, cols, rows)
return [
{
'id': f'manual-{index + 1}',
'slug': f'screen-{index + 1}',
'type': 'manual',
'name': '',
'enabled': True,
'lines': trim_message_lines(message),
}
for index, message in enumerate(normalized_messages)
]
def load_screens_payload(screens_path: Path | None) -> dict[str, list[dict[str, Any]]]:
if screens_path is None or not screens_path.exists():
return {}
with screens_path.open('r', encoding='utf-8') as screens_file:
payload = json.load(screens_file)
if isinstance(payload, dict) and isinstance(payload.get('boards'), list):
board_payloads: dict[str, list[dict[str, Any]]] = {}
for index, raw_board in enumerate(payload['boards'], start=1):
if not isinstance(raw_board, dict):
raise ValueError(f'Screen board {index} must be a JSON object.')
slug = _coerce_slug(raw_board.get('slug'), f'boards[{index}].slug')
raw_screens = raw_board.get('screens')
if not isinstance(raw_screens, list):
raise ValueError(f"'boards[{index}].screens' must be an array.")
board_payloads[slug] = raw_screens
return board_payloads
if isinstance(payload, dict) and isinstance(payload.get('screens'), list):
return {DEFAULT_BOARD_SLUG: payload['screens']}
raise ValueError("Screens file must contain either 'boards' or 'screens'.")
def serialize_screen_for_storage(screen: dict[str, Any]) -> dict[str, Any]:
payload = {
'id': screen['id'],
'slug': screen['slug'],
'type': screen['type'],
'name': screen.get('name', ''),
'enabled': screen.get('enabled', True),
}
if screen['type'] == 'manual':
payload['lines'] = trim_message_lines(screen['lines'])
return payload
payload.update(
{
'pluginId': screen['pluginId'],
'refreshIntervalSeconds': screen['refreshIntervalSeconds'],
'settings': screen['settings'],
'design': screen['design'],
'pluginState': screen.get('pluginState', {}),
'cachedLines': trim_message_lines(screen.get('cachedLines', [])),
'lastRefreshedAt': screen.get('lastRefreshedAt'),
'lastError': screen.get('lastError'),
}
)
return payload
def save_screens(screens_path: Path | None, boards: dict[str, BoardState]) -> None:
if screens_path is None:
return
screens_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
'boards': [
{
'slug': board.config.slug,
'screens': [serialize_screen_for_storage(screen) for screen in board.screens],
}
for board in boards.values()
]
}
with screens_path.open('w', encoding='utf-8') as screens_file:
json.dump(payload, screens_file, indent=2)
screens_file.write('\n')
def normalize_screens_payload(
payload: Any,
*,
config: DisplayConfig,
plugins: dict[str, ScreenPlugin],
existing_screens: dict[str, dict[str, Any]],
) -> list[dict[str, Any]]:
raw_screens = payload.get('screens') if isinstance(payload, dict) else payload
if not isinstance(raw_screens, list) or len(raw_screens) == 0:
raise ValueError("'screens' must be a non-empty array.")
normalized_screens: list[dict[str, Any]] = []
seen_ids: set[str] = set()
seen_slugs: set[str] = set()
for index, raw_screen in enumerate(raw_screens, start=1):
if not isinstance(raw_screen, dict):
raise ValueError(f'Screen {index} must be a JSON object.')
screen_id = raw_screen.get('id') if isinstance(raw_screen.get('id'), str) else generate_screen_id()
if screen_id in seen_ids:
raise ValueError(f"Duplicate screen id '{screen_id}' is not allowed.")
seen_ids.add(screen_id)
previous_screen = existing_screens.get(screen_id, {})
raw_slug = raw_screen.get('slug', previous_screen.get('slug'))
if raw_slug is None:
suggested_slug = _suggest_slug(
raw_screen.get('name')
or previous_screen.get('name')
or raw_screen.get('pluginId')
or screen_id,
f'screen-{index}',
)
screen_slug = _make_unique_slug(suggested_slug, seen_slugs)
else:
screen_slug = _coerce_slug(raw_slug, f'screens[{index}].slug')
if screen_slug in seen_slugs:
raise ValueError(f"Duplicate screen slug '{screen_slug}' is not allowed.")
seen_slugs.add(screen_slug)
screen_type = raw_screen.get('type')
name = _coerce_optional_string(raw_screen.get('name'), f'screens[{index}].name')
enabled = _coerce_bool(raw_screen.get('enabled', True), f'screens[{index}].enabled')
if screen_type == 'manual':
normalized_screens.append(
{
'id': screen_id,
'slug': screen_slug,
'type': 'manual',
'name': name,
'enabled': enabled,
'lines': normalize_message_lines(
raw_screen.get('lines'),
cols=config.cols,
rows=config.rows,
field_name=f'screens[{index}].lines',
),
}
)
continue
if screen_type == 'plugin':
plugin_id = raw_screen.get('pluginId')
if not isinstance(plugin_id, str) or plugin_id not in plugins:
raise ValueError(f"Screen {index} references an unknown plugin.")
plugin = plugins[plugin_id]
refresh_interval_seconds = _coerce_int(
raw_screen.get('refreshIntervalSeconds', plugin.manifest.default_refresh_interval_seconds),
f'screens[{index}].refreshIntervalSeconds',
1,
86400,
)
previous_cached_lines = previous_screen.get('cachedLines', [])
cached_lines = normalize_message_lines(
previous_cached_lines,
cols=config.cols,
rows=config.rows,
field_name=f'screens[{index}].cachedLines',
allow_empty=True,
)
normalized_screens.append(
{
'id': screen_id,
'slug': screen_slug,
'type': 'plugin',
'name': name,
'enabled': enabled,
'pluginId': plugin_id,
'refreshIntervalSeconds': refresh_interval_seconds,
'settings': normalize_schema_values(
raw_screen.get('settings'),
plugin.manifest.settings_schema,
section_name=f'screens[{index}].settings',
),
'design': normalize_schema_values(
raw_screen.get('design'),
plugin.manifest.design_schema,
section_name=f'screens[{index}].design',
),
'pluginState': previous_screen.get('pluginState', {}),
'cachedLines': cached_lines,
'lastRefreshedAt': previous_screen.get('lastRefreshedAt'),
'lastError': previous_screen.get('lastError'),
}
)
continue
raise ValueError(f"Screen {index} must have type 'manual' or 'plugin'.")
return normalized_screens
def reconcile_screens_for_config_change(
screens: list[dict[str, Any]],
*,
cols: int,
rows: int,
plugins: dict[str, ScreenPlugin],
) -> list[dict[str, Any]]:
reconciled: list[dict[str, Any]] = []
for screen in screens:
if screen['type'] == 'manual':
reconciled.append(
{
**screen,
'lines': normalize_message_lines(
screen['lines'],
cols=cols,
rows=rows,
field_name=f"screen '{screen['slug']}'",
),
}
)
continue
plugin = plugins[screen['pluginId']]
reconciled.append(
{
**screen,
'settings': normalize_schema_values(
screen.get('settings'),
plugin.manifest.settings_schema,
section_name=f"screen '{screen['slug']}'.settings",
),
'design': normalize_schema_values(
screen.get('design'),
plugin.manifest.design_schema,
section_name=f"screen '{screen['slug']}'.design",
),
'pluginState': {},
'cachedLines': [],
'lastRefreshedAt': None,
'lastError': None,
}
)
return reconciled
def resolve_screen_lines(
screen: dict[str, Any],
config: DisplayConfig,
plugins: dict[str, ScreenPlugin],
) -> list[str]:
if screen['type'] == 'manual':
return pad_lines(screen['lines'], config.rows)
plugin = plugins[screen['pluginId']]
cached_lines = screen.get('cachedLines') or []
if cached_lines:
return center_lines(cached_lines, config.rows)
placeholder_lines = plugin.placeholder_lines(
settings=screen['settings'],
design=screen['design'],
context=PluginContext(cols=config.cols, rows=config.rows),
error=screen.get('lastError'),
)
return center_lines(
normalize_message_lines(
placeholder_lines,
cols=config.cols,
rows=config.rows,
field_name=f"screen '{screen['slug']}' placeholder",
),
config.rows,
)
def resolve_default_messages(
screens: list[dict[str, Any]],
config: DisplayConfig,
plugins: dict[str, ScreenPlugin],
) -> list[list[str]]:
messages = [
resolve_screen_lines(screen, config, plugins)
for screen in screens
if screen.get('enabled', True)
]
return messages or normalize_default_messages([['NO SCREENS']], config.cols, config.rows)
def sync_board_display_messages(board: BoardState, plugins: dict[str, ScreenPlugin]) -> None:
board.config.default_messages = resolve_default_messages(board.screens, board.config, plugins)
def sync_all_display_messages(app: web.Application) -> None:
for board in app[BOARD_REGISTRY_KEY].boards.values():
sync_board_display_messages(board, app[PLUGINS_KEY])
def build_default_board_state(
config: DisplayConfig,
*,
plugins: dict[str, ScreenPlugin],
) -> BoardState:
screens = build_manual_screens_from_messages(DEFAULT_MESSAGES, cols=config.cols, rows=config.rows)
board = BoardState(
config=config,
screens=screens,
message_state=MessageState(lines=[''] * config.rows),
)
sync_board_display_messages(board, plugins)
return board
def _are_only_default_manual_screens(raw_screens: list[dict[str, Any]]) -> bool:
"""Check if saved screens are all auto-generated manual screens from DEFAULT_MESSAGES."""
return all(
isinstance(s, dict)
and s.get('type') == 'manual'
and str(s.get('id', '')).startswith('manual-')
for s in raw_screens
)
def build_registry(
*,
board_configs: list[DisplayConfig],
default_board_slug: str,
common_settings: dict[str, Any],
screens_by_board: dict[str, list[dict[str, Any]]],
plugins: dict[str, ScreenPlugin],
) -> BoardRegistry:
registry = BoardRegistry(default_board_slug=default_board_slug, common_settings=common_settings)
for config in board_configs:
raw_screens = screens_by_board.get(config.slug)
# Always rebuild
9DF1
default manual screens from config.json so that
# message edits take effect on restart without needing to nuke state.
# Only preserve persisted screens when the admin has customized them
# (added plugins, renamed screens, etc.).
if raw_screens is None or _are_only_default_manual_screens(raw_screens):
board = build_default_board_state(config, plugins=plugins)
else:
normalized_screens = normalize_screens_payload(
raw_screens,
config=config,
plugins=plugins,
existing_screens={},
)
board = BoardState(
config=config,
screens=normalized_screens,
message_state=MessageState(lines=[''] * config.rows),
)
sync_board_display_messages(board, plugins)
registry.boards[config.slug] = board
if registry.default_board_slug not in registry.boards:
registry.default_board_slug = next(iter(registry.boards))
return registry
def apply_runtime_display_config(config: DisplayConfig) -> dict[str, Any]:
return config.serialize()
def build_admin_config_response(board: BoardState, *, default_board_slug: str, has_admin_password: bool) -> dict[str, Any]:
payload = board.config.serialize_settings()
payload['isDefault'] = board.config.slug == default_board_slug
payload['hasAdminPassword'] = has_admin_password
return payload
def serialize_screen_for_admin(
screen: dict[str, Any],
config: DisplayConfig,
plugins: dict[str, ScreenPlugin],
) -> dict[str, Any]:
payload = {
'id': screen['id'],
'slug': screen['slug'],
'type': screen['type'],
'name': screen.get('name', ''),
'enabled': screen.get('enabled', True),
'previewLines': resolve_screen_lines(screen, config, plugins),
}
if screen['type'] == 'manual':
payload['lines'] = screen['lines']
return payload
plugin = plugins[screen['pluginId']]
payload.update(
{
'pluginId': screen['pluginId'],
'pluginName': plugin.manifest.name,
'refreshIntervalSeconds': screen['refreshIntervalSeconds'],
'settings': screen['settings'],
'design': screen['design'],
'pluginState': screen.get('pluginState', {}),
'lastRefreshedAt': screen.get('lastRefreshedAt'),
'lastError': screen.get('lastError'),
}
)
return payload
def build_admin_screens_response(app: web.Application, board: BoardState) -> dict[str, Any]:
plugins = app[PLUGINS_KEY]
return {
'boardSlug': board.config.slug,
'pluginCommonSettings': app[BOARD_REGISTRY_KEY].common_settings,
'screens': [
serialize_screen_for_admin(screen, board.config, plugins)
for screen in board.screens
],
'plugins': [plugin.manifest.serialize() for plugin in plugins.values()],
}
def build_admin_boards_response(registry: BoardRegistry) -> dict[str, Any]:
return {
'defaultBoardSlug': registry.default_board_slug,
'boards': [
{
'slug': board.config.slug,
'name': board.config.name,
'isDefault': board.config.slug == registry.default_board_slug,
'cols': board.config.cols,
'rows': board.config.rows,
'messageDurationSeconds': board.config.message_duration_seconds,
'apiMessageDurationSeconds': board.config.api_message_duration_seconds,
'screenCount': len(board.screens),
}
for board in registry.boards.values()
],
}
def build_message_event(state: MessageState) -> dict[str, Any]:
return {'type': 'message_state', 'payload': state.serialize()}
def build_config_event(config: DisplayConfig) -> dict[str, Any]: