forked from UniversityRadioYork/BAPSicle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_server.py
569 lines (435 loc) · 16.1 KB
/
web_server.py
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
from sanic import Sanic
from sanic.exceptions import NotFound, abort
from sanic.response import html, file, redirect
from sanic.response import json as resp_json
from sanic_cors import CORS
from syncer import sync
import asyncio
from jinja2 import Environment, FileSystemLoader
from jinja2.utils import select_autoescape
from urllib.parse import unquote
from setproctitle import setproctitle
from typing import Any, Optional, List
from multiprocessing.queues import Queue
from queue import Empty
from time import sleep
import json
import os
from helpers.os_environment import (
isLinux,
resolve_external_file_path,
resolve_local_file_path,
)
from helpers.logging_manager import LoggingManager
from helpers.device_manager import DeviceManager
from helpers.state_manager import StateManager
from helpers.the_terminator import Terminator
from helpers.normalisation import get_normalised_filename_if_available
from helpers.myradio_api import MyRadioAPI
from helpers.alert_manager import AlertManager
import package
from baps_types.happytime import happytime
env = Environment(
loader=FileSystemLoader("%s/ui-templates/" % os.path.dirname(__file__)),
autoescape=select_autoescape(),
)
LOG_FILEPATH = resolve_external_file_path("logs")
LOG_FILENAME = LOG_FILEPATH + "/WebServer.log"
# From Sanic's default, but set to log to file.
os.makedirs(LOG_FILEPATH, exist_ok=True)
LOGGING_CONFIG = dict(
version=1,
disable_existing_loggers=False,
loggers={
"sanic.root": {"level": "INFO", "handlers": ["file"]},
"sanic.error": {
"level": "INFO",
"handlers": ["error_file"],
"propagate": True,
"qualname": "sanic.error",
},
"sanic.access": {
"level": "INFO",
"handlers": ["access_file"],
"propagate": True,
"qualname": "sanic.access",
},
},
handlers={
"file": {
"class": "logging.FileHandler",
"formatter": "generic",
"filename": LOG_FILENAME,
},
"error_file": {
"class": "logging.FileHandler",
"formatter": "generic",
"filename": LOG_FILENAME,
},
"access_file": {
"class": "logging.FileHandler",
"formatter": "access",
"filename": LOG_FILENAME,
},
},
formatters={
"generic": {
"format": "%(asctime)s | [%(process)d] [%(levelname)s] %(message)s",
"class": "logging.Formatter",
},
"access": {
"format": "%(asctime)s | (%(name)s)[%(levelname)s][%(host)s]: "
+ "%(request)s %(message)s %(status)d %(byte)d",
"class": "logging.Formatter",
},
},
)
app = Sanic("BAPSicle Web Server", log_config=LOGGING_CONFIG)
def render_template(file, data, status=200):
template = env.get_template(file)
html_content = template.render(data=data)
return html(html_content, status=status)
def _filter_happytime(date):
return happytime(date)
env.filters["happytime"] = _filter_happytime
logger: LoggingManager
server_state: StateManager
api: MyRadioAPI
alerts: AlertManager
player_to_q: List[Queue] = []
player_from_q: List[Queue] = []
# General UI Endpoints
@app.exception(NotFound)
def page_not_found(request, e: Any):
data = {"ui_page": "404", "ui_title": "404", "code": 404, "title": "Page Not Found",
"message": "Looks like you fell off the tip of the iceberg."}
return render_template("error.html", data=data, status=404)
# Future use.
def error_page(code=500, ui_title="500", title="Something went very wrong!",
message="Looks like the server fell over. Try viewing the WebServer logs for more details."):
data = {"ui_page": ui_title, "ui_title": ui_title, "code": code, "title": title, "message": message}
return render_template("error.html", data=data, status=500)
@app.route("/")
def ui_index(request):
config = server_state.get()
data = {
"ui_page": "index",
"ui_title": "",
"alert_count": len(alerts.alerts_current),
"server_version": config["server_version"],
"server_build": config["server_build"],
"server_name": config["server_name"],
"server_beta": config["server_beta"],
"server_branch": config["server_branch"],
}
return render_template("index.html", data=data)
@app.route("/status")
def ui_status(request):
channel_states = []
for i in range(server_state.get()["num_channels"]):
channel_states.append(status(i))
data = {"channels": channel_states,
"ui_page": "status", "ui_title": "Status"}
return render_template("status.html", data=data)
@app.route("/alerts")
def ui_alerts(request):
data = {
"alerts_current": alerts.alerts_current,
"alerts_previous": alerts.alerts_previous,
"ui_page": "alerts",
"ui_title": "Alerts"
}
return render_template("alerts.html", data=data)
@app.route("/config/player")
def ui_config_player(request):
channel_states = []
for i in range(server_state.get()["num_channels"]):
channel_states.append(status(i))
outputs = None
if isLinux():
outputs = DeviceManager.getAudioDevices()
else:
outputs = DeviceManager.getAudioOutputs()
data = {
"channels": channel_states,
"outputs": outputs,
"sdl_direct": isLinux(),
"ui_page": "config",
"ui_title": "Player Config",
}
return render_template("config_player.html", data=data)
@app.route("/config/server")
def ui_config_server(request):
data = {
"ui_page": "server",
"ui_title": "Server Config",
"state": server_state.get(),
"ser_ports": DeviceManager.getSerialPorts(),
"tracklist_modes": ["off", "on", "delayed", "fader-live"],
"normalisation_modes": ["off", "on"],
}
return render_template("config_server.html", data=data)
@app.route("/config/server/update", methods=["POST"])
def ui_config_server_update(request):
# TODO Validation!
server_state.update("server_name", request.form.get("name"))
server_state.update("host", request.form.get("host"))
server_state.update("port", int(request.form.get("port")))
server_state.update("num_channels", int(request.form.get("channels")))
server_state.update("ws_port", int(request.form.get("ws_port")))
serial_port = request.form.get("serial_port")
server_state.update("serial_port", None if serial_port ==
"None" else serial_port)
# Because we're not showing the api key once it's set.
if "myradio_api_key" in request.form and request.form.get("myradio_api_key") != "":
server_state.update("myradio_api_key",
request.form.get("myradio_api_key"))
server_state.update("myradio_base_url",
request.form.get("myradio_base_url"))
server_state.update("myradio_api_url", request.form.get("myradio_api_url"))
server_state.update(
"myradio_api_tracklist_source", request.form.get(
"myradio_api_tracklist_source")
)
server_state.update("tracklist_mode", request.form.get("tracklist_mode"))
server_state.update("normalisation_mode", request.form.get("normalisation_mode"))
return redirect("/restart")
@app.route("/logs")
def ui_logs_list(request):
files = os.listdir(resolve_external_file_path("/logs"))
log_files = []
for file_name in files:
if file_name.endswith(".log"):
log_files.append(file_name.rstrip(".log"))
log_files.sort()
data = {"ui_page": "logs", "ui_title": "Logs", "logs": log_files}
return render_template("loglist.html", data=data)
@app.route("/logs/<path:path>")
def ui_logs_render(request, path):
page = request.args.get("page")
if not page:
return redirect(f"/logs/{path}?page=1")
page = int(page)
assert page >= 1
try:
log_file = open(resolve_external_file_path("/logs/{}.log").format(path))
except FileNotFoundError:
abort(404)
return
data = {
"logs": log_file.read().splitlines()[
-300 * page:(-300 * (page - 1) if page > 1 else None)
][::-1],
"ui_page": "logs",
"ui_title": "Logs - {}".format(path),
"page": page,
}
log_file.close()
return render_template("log.html", data=data)
# Player Audio Control Endpoints
# Just useful for messing arround without presenter / websockets.
@app.route("/player/<channel:int>/<command>")
def player_simple(request, channel: int, command: str):
simple_endpoints = ["play", "pause", "unpause", "stop", "unload", "clear"]
if command in simple_endpoints:
player_to_q[channel].put("UI:" + command.upper())
return redirect("/status")
abort(404)
@app.route("/player/<channel:int>/seek/<pos:number>")
def player_seek(request, channel: int, pos: float):
player_to_q[channel].put("UI:SEEK:" + str(pos))
return redirect("/status")
@app.route("/player/<channel:int>/load/<channel_weight:int>")
def player_load(request, channel: int, channel_weight: int):
player_to_q[channel].put("UI:LOAD:" + str(channel_weight))
return redirect("/status")
@app.route("/player/<channel:int>/remove/<channel_weight:int>")
def player_remove(request, channel: int, channel_weight: int):
player_to_q[channel].put("UI:REMOVE:" + str(channel_weight))
return redirect("/status")
@app.route("/player/<channel:int>/output/<name:string>")
def player_output(request, channel: int, name: Optional[str]):
player_to_q[channel].put("UI:OUTPUT:" + unquote(str(name)))
return redirect("/config/player")
@app.route("/player/<channel:int>/autoadvance/<state:int>")
def player_autoadvance(request, channel: int, state: int):
player_to_q[channel].put("UI:AUTOADVANCE:" + str(state))
return redirect("/status")
@app.route("/player/<channel:int>/repeat/<state:string>")
def player_repeat(request, channel: int, state: str):
player_to_q[channel].put("UI:REPEAT:" + state.upper())
return redirect("/status")
@app.route("/player/<channel:int>/playonload/<state:int>")
def player_playonload(request, channel: int, state: int):
player_to_q[channel].put("UI:PLAYONLOAD:" + str(state))
return redirect("/status")
@app.route("/player/<channel:int>/status")
def player_status_json(request, channel: int):
return resp_json(status(channel))
@app.route("/player/all/stop")
def player_all_stop(request):
for channel in player_to_q:
channel.put("UI:STOP")
return redirect("/status")
# Show Plan Functions
@app.route("/plan/load/<timeslotid:int>")
def plan_load(request, timeslotid: int):
for channel in player_to_q:
channel.put("UI:GETPLAN:" + str(timeslotid))
return redirect("/status")
@app.route("/plan/clear")
def plan_clear(request):
for channel in player_to_q:
channel.put("UI:CLEAR")
return redirect("/status")
# API Proxy Endpoints
@app.route("/plan/list")
async def api_list_showplans(request):
return resp_json(await api.get_showplans())
@app.route("/library/search/track")
async def api_search_library(request):
return resp_json(
await api.get_track_search(
request.args.get("title"), request.args.get("artist")
)
)
@app.route("/library/playlists/<type:string>")
async def api_get_playlists(request, type: str):
if type not in ["music", "aux"]:
abort(401)
if type == "music":
return resp_json(await api.get_playlist_music())
else:
return resp_json(await api.get_playlist_aux())
@app.route("/library/playlist/<type:string>/<library_id:string>")
async def api_get_playlist(request, type: str, library_id: str):
if type not in ["music", "aux"]:
abort(401)
if type == "music":
return resp_json(await api.get_playlist_music_items(library_id))
else:
return resp_json(await api.get_playlist_aux_items(library_id))
# JSON Outputs
@app.route("/status-json")
def json_status(request):
channel_states = []
for i in range(server_state.get()["num_channels"]):
channel_states.append(status(i))
return resp_json({"server": server_state.get(), "channels": channel_states})
# Get audio for UI to generate waveforms.
@app.route("/audiofile/<type:string>/<id:int>")
async def audio_file(request, type: str, id: int):
if type not in ["managed", "track"]:
abort(404)
filename = resolve_external_file_path(
"music-tmp/{}-{}.mp3".format(type, id))
# Swap with a normalised version if it's ready, else returns original.
filename = get_normalised_filename_if_available(filename)
# Send file or 404
try:
response = await file(filename)
except FileNotFoundError:
abort(404)
return
return response
# Static Files
app.static(
"/favicon.ico", resolve_local_file_path("ui-static/favicon.ico"), name="ui-favicon"
)
app.static("/static", resolve_local_file_path("ui-static"), name="ui-static")
dist_directory = resolve_local_file_path("presenter-build")
app.static("/presenter", dist_directory)
app.static(
"/presenter/",
resolve_local_file_path("presenter-build/index.html"),
strict_slashes=True,
name="presenter-index",
)
# Helper Functions
def status(channel: int):
while not player_from_q[channel].empty():
# Just waste any previous status responses.
player_from_q[channel].get()
player_to_q[channel].put("UI:STATUS")
retries = 0
while retries < 40:
try:
response = player_from_q[channel].get_nowait()
if response.startswith("UI:STATUS:"):
response = response.split(":", 2)[2]
# TODO: Handle OKAY / FAIL
response = response[response.index(":") + 1:]
try:
response = json.loads(response)
except Exception as e:
raise e
return response
except Empty:
pass
retries += 1
sleep(0.02)
# WebServer Start / Stop Functions
@app.route("/quit")
def quit(request):
server_state.update("running_state", "quitting")
data = {
"ui_page": "message",
"ui_title": "Quitting BAPSicle",
"title": "See you later!",
"ui_menu": False,
"message": "BAPSicle is going back into winter hibernation, see you again soon!",
}
return render_template("message.html", data)
@app.route("/restart")
def restart(request):
if request.args.get("confirm", '') != "true":
for i in range(server_state.get()["num_channels"]):
state = status(i)
if state["playing"]:
return render_template("restart-confirm.html", data=None)
server_state.update("running_state", "restarting")
data = {
"ui_page": "message",
"ui_title": "Restarting BAPSicle",
"title": "Please Wait...",
"ui_menu": False,
"message": "Just putting BAPSicle back in the freezer for a moment!",
"redirect_to": "/",
"redirect_wait_ms": 10000,
}
return render_template("message.html", data)
# Don't use reloader, it causes Nested Processes!
def WebServer(player_to: List[Queue], player_from: List[Queue], state: StateManager):
global player_to_q, player_from_q, server_state, api, app, alerts
player_to_q = player_to
player_from_q = player_from
server_state = state
logger = LoggingManager("WebServer")
api = MyRadioAPI(logger, state)
alerts = AlertManager()
process_title = "Web Server"
setproctitle(process_title)
CORS(app, supports_credentials=True) # Allow ALL CORS!!!
terminate = Terminator()
while not terminate.terminate:
try:
sync(
app.run(
host=server_state.get()["host"],
port=server_state.get()["port"],
auto_reload=False,
debug=not package.BETA,
access_log=not package.BETA,
)
)
except Exception:
break
try:
loop = asyncio.get_event_loop()
if loop:
loop.close()
if app:
app.stop()
del app
except Exception:
pass