-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp_server.py
More file actions
213 lines (178 loc) · 8.81 KB
/
app_server.py
File metadata and controls
213 lines (178 loc) · 8.81 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
import os
import socket
from typing import List, Optional, Any
import tornado
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, StaticFileHandler
from tornado_prometheus import PrometheusMixIn
from controllers import controllers
from controllers.ws_controller import WebSocketController
from digi_server.logger import get_logger, configure_file_logging, configure_db_logging
from digi_server.settings import Settings
from models.cue import CueType
from models.models import db
from models.script import Script
from models.show import Show
from models.session import Session, ShowSession
from models.user import User
from rbac.rbac import RBACController
from utils.database import DigiSQLAlchemy
from utils.env_parser import EnvParser
from digi_server.plugin_manager import PluginManager
from utils.web.route import Route
class DigiScriptServer(PrometheusMixIn, Application):
def __init__(self, debug=False, settings_path=None):
self.http_server: Optional[HTTPServer] = None
self.env_parser: EnvParser = EnvParser.instance() # pylint: disable=no-member
self.digi_settings: Settings = Settings(self, settings_path)
self.app_log_handler = None
self.db_file_handler = None
# Controller imports (needed to trigger the decorator)
controllers.import_all_controllers()
# Plugin imports (needed to trigger decorator)
self.plugin_manager: PluginManager = PluginManager(self)
self.plugin_manager.import_all_plugins()
self.clients: List[WebSocketController] = []
db_path = self.digi_settings.settings.get('db_path').get_value()
get_logger().info(f'Using {db_path} as DB path')
self._db: DigiSQLAlchemy = db
self._db.configure(url=db_path)
self.rbac = RBACController(self)
self._configure_rbac()
self._db.create_all()
# Clear out all sessions since we are starting the app up
with self._db.sessionmaker() as session:
get_logger().debug('Emptying out sessions table!')
session.query(Session).delete()
session.commit()
# Check for presence of admin user, and update settings to match
with self._db.sessionmaker() as session:
any_admin = session.query(User).filter(User.is_admin).first()
has_admin = any_admin is not None
self.digi_settings.settings['has_admin_user'].set_value(has_admin, False)
self.digi_settings._save()
# Check the show we are expecting to be loaded exists
with self._db.sessionmaker() as session:
current_show = self.digi_settings.settings.get('current_show').get_value()
if current_show:
show = session.query(Show).get(current_show)
if not show:
get_logger().warning('Current show from settings not found. Resetting.')
self.digi_settings.settings['current_show'].set_to_default()
self.digi_settings._save()
# If there is a live session in progress, clean up the current client ID
with self._db.sessionmaker() as session:
current_show = self.digi_settings.settings.get('current_show').get_value()
if current_show:
show = session.query(Show).get(current_show)
if show and show.current_session_id:
show_session: ShowSession = session.query(ShowSession).get(show.current_session_id)
if show_session:
show_session.last_client_internal_id = show_session.client_internal_id
show_session.client_internal_id = None
else:
get_logger().warning('Current show session not found. Resetting.')
show.current_session_id = None
session.commit()
static_files_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'..', 'static', 'assets')
get_logger().info(f'Using {static_files_path} as static files path')
handlers = Route.routes()
handlers.append(('/favicon.ico', controllers.StaticController))
handlers.append((r'/assets/(.*)', StaticFileHandler, {'path': static_files_path}))
handlers.append((r'/api/.*', controllers.ApiFallback))
handlers.append((r'/(.*)', controllers.RootController))
super().__init__(
handlers=handlers,
debug=debug,
db=self._db,
websocket_ping_interval=5,
cookie_secret='DigiScriptSuperSecretValue123!',
login_url='/login',
)
def listen(self,
port: int,
address: Optional[str] = None,
*,
family: socket.AddressFamily = socket.AF_UNSPEC,
backlog: int = tornado.netutil._DEFAULT_BACKLOG,
flags: Optional[int] = None,
reuse_port: bool = False,
**kwargs: Any) -> HTTPServer:
self.http_server = super().listen(port, address, family=family, backlog=backlog, flags=flags,
reuse_port=reuse_port, **kwargs)
return self.http_server
async def configure(self):
await self._configure_logging()
async def post_configure(self):
await self.plugin_manager.start_default()
async def shutdown(self):
get_logger().warning('DigiScript shutting down - goodbye!')
await self.plugin_manager.shutdown()
async def _configure_logging(self):
get_logger().info('Reconfiguring logging!')
# Application logging
log_path = await self.digi_settings.get('log_path')
file_size = await self.digi_settings.get('max_log_mb')
backups = await self.digi_settings.get('log_backups')
if log_path:
self.app_log_handler = configure_file_logging(log_path, file_size, backups,
self.app_log_handler)
# Database logging
use_db_logging = await self.digi_settings.get('db_log_enabled')
if use_db_logging:
db_log_path = await self.digi_settings.get('db_log_path')
db_file_size = await self.digi_settings.get('db_max_log_mb')
db_backups = await self.digi_settings.get('db_log_backups')
self.db_file_handler = configure_db_logging(log_path=db_log_path,
max_size_mb=db_file_size,
log_backups=db_backups,
handler=self.db_file_handler)
def _configure_rbac(self):
self.rbac.add_mapping(User, Show, [Show.id, Show.name])
self.rbac.add_mapping(User, CueType, [CueType.id, CueType.prefix])
self.rbac.add_mapping(User, Script, [Script.id])
def regen_logging(self):
if not IOLoop.current():
get_logger().error('Unable to regenerate logging as there is no current IOLoop')
else:
IOLoop.current().add_callback(self._configure_logging)
def validate_has_admin(self):
if not IOLoop.current():
get_logger().error('Unable to validate admin user as there is no current IOLoop')
else:
IOLoop.current().add_callback(self._validate_has_admin)
def show_changed(self):
if not IOLoop.current():
get_logger().error('Unable to initiate show change as there is no current IOLoop')
else:
IOLoop.current().add_callback(self._show_changed)
async def _validate_has_admin(self):
with self.get_db().sessionmaker() as session:
any_admin = session.query(User).filter(User.is_admin).first()
has_admin = any_admin is not None
await self.digi_settings.set('has_admin_user', has_admin)
async def _show_changed(self):
await self.ws_send_to_all('NOOP', 'SHOW_CHANGED', {})
def get_db(self) -> DigiSQLAlchemy:
return self._db
def get_all_ws(self, user_id) -> List[WebSocketController]:
sockets = []
for client in self.clients:
c_user_id = client.get_secure_cookie('digiscript_user_id')
if c_user_id is not None and int(c_user_id) == user_id:
sockets.append(client)
return sockets
def get_ws(self, internal_uuid: str) -> Optional[WebSocketController]:
for client in self.clients:
if client.__getattribute__('internal_id') == internal_uuid:
return client
return None
async def ws_send_to_all(self, ws_op: str, ws_action: str, ws_data: dict):
for client in self.clients:
await client.write_message({
'OP': ws_op,
'DATA': ws_data,
'ACTION': ws_action
})