-
-
Notifications
You must be signed in to change notification settings - Fork 704
Expand file tree
/
Copy path__init__.py
More file actions
381 lines (291 loc) · 9.38 KB
/
__init__.py
File metadata and controls
381 lines (291 loc) · 9.38 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
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import logging
import sys
from builtins import range
from os import getenv, path, environ
import socket
from signal import SIGALRM, SIGUSR1, signal
from time import sleep
import django
import pydbus
import sh
from future import standard_library
from jinja2 import Template
from tenacity import Retrying, stop_after_attempt, wait_fixed
from settings import LISTEN, ZmqConsumer, settings
from viewer.constants import (
BALENA_IP_RETRY_DELAY,
EMPTY_PL_DELAY,
MAX_BALENA_IP_RETRIES,
SERVER_WAIT_TIMEOUT,
SPLASH_DELAY,
SPLASH_PAGE_URL,
STANDBY_SCREEN,
)
from viewer.media_player import MediaPlayerProxy
from viewer.playback import navigate_to_asset, play_loop, skip_asset, stop_loop
from viewer.utils import (
command_not_found,
sigalrm,
sigusr1,
wait_for_server,
watchdog,
)
try:
django.setup()
# Place imports that uses Django in this block.
from lib.utils import (
connect_to_redis,
get_balena_device_info,
get_node_ip,
get_node_mac_address,
is_balena_app,
string_to_bool,
url_fails,
)
from lib import diagnostics
from viewer.scheduling import Scheduler
from viewer.zmq import ZMQ_HOST_PUB_URL, ZmqSubscriber
except Exception:
pass
standard_library.install_aliases()
__author__ = "Screenly, Inc"
__copyright__ = "Copyright 2012-2024, Screenly, Inc"
__license__ = "Dual License: GPLv2 and Commercial License"
current_browser_url = None
browser = None
loop_is_stopped = False
browser_bus = None
r = connect_to_redis()
HOME = None
scheduler = None
def send_current_asset_id_to_server():
consumer = ZmqConsumer()
consumer.send({'current_asset_id': scheduler.current_asset_id})
def show_hotspot_page(data):
global loop_is_stopped
uri = 'http://{0}/hotspot'.format(LISTEN)
decoded = json.loads(data)
base_dir = path.abspath(path.dirname(__file__))
template_path = path.join(base_dir, 'templates/hotspot.html')
with open(template_path) as f:
template = Template(f.read())
context = {
'network': decoded.get('network', None),
'ssid_pswd': decoded.get('ssid_pswd', None),
'address': decoded.get('address', None),
}
with open('/data/hotspot/hotspot.html', 'w') as out_file:
out_file.write(template.render(context=context))
loop_is_stopped = stop_loop(scheduler)
view_webpage(uri)
def setup_wifi(data):
global load_screen_displayed, mq_data
if not load_screen_displayed:
mq_data = data
return
show_hotspot_page(data)
def show_splash(data):
global loop_is_stopped
if is_balena_app():
while True:
try:
ip_address = get_balena_device_info().json()['ip_address']
if ip_address != '':
break
except Exception:
break
else:
r.set('ip_addresses', data)
view_webpage(SPLASH_PAGE_URL)
sleep(SPLASH_DELAY)
loop_is_stopped = play_loop()
commands = {
'next': lambda _: skip_asset(scheduler),
'previous': lambda _: skip_asset(scheduler, back=True),
'asset': lambda id: navigate_to_asset(scheduler, id),
'reload': lambda _: load_settings(),
'stop': lambda _: setattr(
__import__('__main__'), 'loop_is_stopped', stop_loop(scheduler)
),
'play': lambda _: setattr(
__import__('__main__'), 'loop_is_stopped', play_loop()
),
'setup_wifi': lambda data: setup_wifi(data),
'show_splash': lambda data: show_splash(data),
'unknown': lambda _: command_not_found(),
'current_asset_id': lambda _: send_current_asset_id_to_server()
}
def load_browser():
global browser
logging.info('Loading browser...')
# Prepare headers data for WebView via environment variables
try:
anthias_hostname = socket.gethostname()
except Exception:
anthias_hostname = ''
try:
git_branch = diagnostics.get_git_branch()
git_short_hash = diagnostics.get_git_short_hash()
anthias_version = (
f"{git_branch}@{git_short_hash}"
if git_branch and git_short_hash else ''
)
except Exception:
anthias_version = ''
try:
anthias_mac = get_node_mac_address()
except Exception:
anthias_mac = ''
env = dict(environ)
if anthias_hostname:
env['ANTHIAS_HOSTNAME'] = anthias_hostname
if anthias_version:
env['ANTHIAS_VERSION'] = anthias_version
if anthias_mac:
env['ANTHIAS_MAC'] = anthias_mac
browser = sh.Command('ScreenlyWebview')(_bg=True, _err_to_out=True, _env=env)
while (
'Screenly service start' not in browser.process.stdout.decode('utf-8')
):
sleep(1)
def view_webpage(uri):
global current_browser_url
if browser is None or not browser.process.alive:
load_browser()
if current_browser_url is not uri:
browser_bus.loadPage(uri)
current_browser_url = uri
logging.info('Current url is {0}'.format(current_browser_url))
def view_image(uri):
global current_browser_url
if browser is None or not browser.process.alive:
load_browser()
if current_browser_url is not uri:
browser_bus.loadImage(uri)
current_browser_url = uri
logging.info('Current url is {0}'.format(current_browser_url))
if string_to_bool(getenv('WEBVIEW_DEBUG', '0')):
logging.info(browser.process.stdout)
def view_video(uri, duration):
logging.debug('Displaying video %s for %s ', uri, duration)
media_player = MediaPlayerProxy.get_instance()
media_player.set_asset(uri, duration)
media_player.play()
view_image('null')
try:
while media_player.is_playing():
watchdog()
sleep(1)
except sh.ErrorReturnCode_1:
logging.info(
'Resource URI is not correct, remote host is not responding or '
'request was rejected.'
)
media_player.stop()
def load_settings():
"""
Load settings and set the log level.
"""
settings.load()
logging.getLogger().setLevel(
logging.DEBUG if settings['debug_logging'] else logging.INFO
)
def asset_loop(scheduler):
asset = scheduler.get_next_asset()
if asset is None:
logging.info(
'Playlist is empty. Sleeping for %s seconds', EMPTY_PL_DELAY)
view_image(STANDBY_SCREEN)
sleep(EMPTY_PL_DELAY)
elif (
path.isfile(asset['uri']) or
(not url_fails(asset['uri']) or asset['skip_asset_check'])
):
name, mime, uri = asset['name'], asset['mimetype'], asset['uri']
logging.info('Showing asset %s (%s)', name, mime)
logging.debug('Asset URI %s', uri)
watchdog()
if 'image' in mime:
view_image(uri)
elif 'web' in mime:
view_webpage(uri)
elif 'video' or 'streaming' in mime:
view_video(uri, asset['duration'])
else:
logging.error('Unknown MimeType %s', mime)
if 'image' in mime or 'web' in mime:
duration = int(asset['duration'])
logging.info('Sleeping for %s', duration)
sleep(duration)
else:
logging.info('Asset %s at %s is not available, skipping.',
asset['name'], asset['uri'])
sleep(0.5)
def setup():
global HOME, browser_bus
HOME = getenv('HOME')
if not HOME:
logging.error('No HOME variable')
# Alternatively, we can raise an Exception using a custom message,
# or we can create a new class that extends Exception.
sys.exit(1)
signal(SIGUSR1, sigusr1)
signal(SIGALRM, sigalrm)
load_settings()
load_browser()
bus = pydbus.SessionBus()
browser_bus = bus.get('screenly.webview', '/Screenly')
def wait_for_node_ip(seconds):
for _ in range(seconds):
try:
get_node_ip()
break
except Exception:
sleep(1)
def start_loop():
global loop_is_stopped
logging.debug('Entering infinite loop.')
while True:
if loop_is_stopped:
sleep(0.1)
continue
asset_loop(scheduler)
def main():
global scheduler
global load_screen_displayed, mq_data
load_screen_displayed = False
mq_data = None
setup()
subscriber_1 = ZmqSubscriber(r, commands, 'tcp://anthias-server:10001')
subscriber_1.daemon = True
subscriber_1.start()
subscriber_2 = ZmqSubscriber(r, commands, ZMQ_HOST_PUB_URL)
subscriber_2.daemon = True
subscriber_2.start()
# This will prevent white screen from happening before showing the
# splash screen with IP addresses.
view_image(STANDBY_SCREEN)
wait_for_server(SERVER_WAIT_TIMEOUT)
scheduler = Scheduler()
if settings['show_splash']:
if is_balena_app():
for attempt in Retrying(
stop=stop_after_attempt(MAX_BALENA_IP_RETRIES),
wait=wait_fixed(BALENA_IP_RETRY_DELAY),
):
with attempt:
get_balena_device_info()
view_webpage(SPLASH_PAGE_URL)
sleep(SPLASH_DELAY)
# We don't want to show splash page if there are active assets but all of
# them are not available.
view_image(STANDBY_SCREEN)
load_screen_displayed = True
if mq_data is not None:
show_hotspot_page(mq_data)
mq_data = None
sleep(0.5)
start_loop()