-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
144 lines (106 loc) · 3.85 KB
/
app.py
File metadata and controls
144 lines (106 loc) · 3.85 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
from contextlib import asynccontextmanager
from threading import Lock
from pathlib import Path
import threading
import time
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from kiosk.renderer.registry import render_path
from kiosk.renderer.base import RenderedView
from kiosk.logger import logger
from kiosk.config import load_config
CONFIG = load_config(Path(__file__).parent / 'config.yaml')
TIMING = CONFIG.timing
ROTATION_DIR = CONFIG.timing.media_directory
STATIC_DIR = Path('static')
PLAYLIST: list[RenderedView] = []
PLAYLIST_VERSION: int = 0
PLAYLIST_LOCK = Lock()
# Prevent unsupported files to be analyzed
SKIP_EXTENSIONS = ['.md']
# --- FastAPI -----------------------------------------------------------------
@asynccontextmanager
async def lifespan(_: FastAPI):
global PLAYLIST, PLAYLIST_VERSION
# --- Startup ---
initial = build_playlist()
with PLAYLIST_LOCK:
PLAYLIST = initial
PLAYLIST_VERSION += 1
logger.info(f'Initial playlist build: {len(PLAYLIST)} items')
interval = max(CONFIG.timing.playlist_scan, 5)
thread = threading.Thread(
target=playlist_watcher,
args=(interval,),
daemon=True
)
thread.start()
yield
# --- Shutdown ---
logger.info(f'Shutting down playlist watcher')
app = FastAPI(lifespan=lifespan, title='Kiosk Rotation Engine')
@app.get('/', response_class=HTMLResponse)
def player():
"""
Fullscreen kiosk player.
Broser is expected to run in kiosk / fullscreen mode.
"""
return (STATIC_DIR / 'player.html').read_text(encoding='utf-8')
@app.get('/playlist')
def playlist():
with PLAYLIST_LOCK:
return {
'version': PLAYLIST_VERSION,
'items': PLAYLIST
}
@app.get('/favicon.ico', include_in_schema=False)
def favicon():
return FileResponse('static/favicon.ico')
# Serve rotation content (html, images, rendered output later)
app.mount('/rotation', StaticFiles(directory=ROTATION_DIR), name='rotation')
# Serve static assets (player.html, CSS, JS)
app.mount('/static', StaticFiles(directory=STATIC_DIR), name='static')
# --- App ---------------------------------------------------------------------
def build_playlist() -> list[RenderedView]:
""" Build the rotation playlist from filesystem content. """
views: list[RenderedView] = []
seen_srcs: set[str] = set()
for path in sorted(ROTATION_DIR.iterdir()):
if not path.is_file() or path.suffix.lower() in SKIP_EXTENSIONS:
continue
try:
result = render_path(path, TIMING)
except Exception as e:
logger.info(f'Skipping {path.name}: {e}')
continue
# Normalize result to a list
if isinstance(result, list):
rendered_items = result
else:
rendered_items = [result]
for view in rendered_items:
# Ignore empty or broken renders
if not view or not view.src:
continue
# Prevent duplicates (important with cached files)
if view.src in seen_srcs:
continue
seen_srcs.add(view.src)
views.append(view)
return views
def playlist_watcher(interval: int) -> None:
""" Watch the rotation playlist for given interval. """
global PLAYLIST, PLAYLIST_VERSION
while True:
try:
new_playlist = build_playlist()
with PLAYLIST_LOCK:
if new_playlist != PLAYLIST:
PLAYLIST = new_playlist
PLAYLIST_VERSION += 1
logger.info(f'Playlist updated, '
f'items in rotation playlist: {len(PLAYLIST)}')
except Exception as e:
logger.error(f'Error updating rotation playlist: {e}')
time.sleep(interval)