forked from Screenly/Anthias
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
543 lines (422 loc) · 15.8 KB
/
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
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#!/usr/bin/env python
# -*- coding: utf8 -*-
## Some legacy parts of this project are Copyright 2012, Wireload Inc
## Viktor Petersson, [email protected]
__author__ = "James Kirsop"
__version__ = "0.1.5"
__email__ = "[email protected]"
from datetime import datetime, timedelta, time
from functools import wraps
from hurry.filesize import size
from os import path, makedirs, getloadavg, statvfs, mkdir, getenv
from re import split as re_split
from sh import git
from subprocess import check_output
from uptime import uptime
import json
import os
import traceback
import uuid
from sh import sh, sudo
from functools import reduce
from bottle import route, run, request, error, static_file, response
from bottle import HTTPResponse
from bottlehaml import haml_template
import db
import queries
import assets_helper
import schedules_helper
import shutdown_helper
from utils import json_dump
from utils import get_node_ip
from utils import validate_url
from utils import url_fails
from utils import get_video_duration
from settings import settings, DEFAULTS
import string
from classes import AvailableDays
import operator
################################
# Utilities
################################
def make_json_response(obj):
response.content_type = "application/json"
return json_dump(obj)
def api_error(error):
response.content_type = "application/json"
response.status = 500
return json_dump({'error': error})
def is_up_to_date():
"""
Determine if there is any update available.
Used in conjunction with check_update() in viewer.py.
"""
# Always return true for the moment, until updating is better supported - August 2015
return True
sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')
# Until this has been created by viewer.py, let's just assume we're up to date.
if not os.path.exists(sha_file):
return True
try:
with open(sha_file, 'r') as f:
latest_sha = f.read().strip()
except:
latest_sha = None
if latest_sha:
try:
check_sha = git('branch', '--contains', latest_sha)
return 'master' in check_sha
except:
return False
# If we weren't able to verify with remote side,
# we'll set up_to_date to true in order to hide
# the 'update available' message
else:
return True
def template(template_name, **context):
"""Screenly template response generator. Shares the
same function signature as Bottle's template() method
but also injects some global context."""
# Add global contexts
context['up_to_date'] = is_up_to_date()
context['default_duration'] = settings['default_duration']
return haml_template(template_name, **context)
################################
# Model
################################
################################
# API
################################
def prepare_asset(request):
data = request.POST or request.FORM or {}
if 'model' in data:
data = json.loads(data['model'])
def get(key):
val = data.get(key, '')
return val.strip() if isinstance(val, str) else val
if all([get('name'),
get('uri') or (request.files.file_upload != ""),
get('mimetype')]):
asset = {
'name': get('name'),
'mimetype': get('mimetype'),
'asset_id': get('asset_id'),
'is_enabled': get('is_enabled'),
'nocache': get('nocache'),
}
uri = get('uri') or False
if not asset['asset_id']:
asset['asset_id'] = uuid.uuid4().hex
try:
file_upload = request.files.file_upload
filename = file_upload.filename
except AttributeError:
file_upload = None
filename = None
if filename and 'web' in asset['mimetype']:
raise Exception("Invalid combination. Can't upload a web resource.")
if uri and filename:
raise Exception("Invalid combination. Can't select both URI and a file.")
if uri and not uri.startswith('/'):
if not validate_url(uri):
raise Exception("Invalid URL. Failed to add asset.")
else:
asset['uri'] = uri
else:
asset['uri'] = uri
if filename:
asset['uri'] = path.join(settings['assetdir'], asset['asset_id'])
with open(asset['uri'], 'w') as f:
while True:
chunk = file_upload.file.read(1024)
if not chunk:
break
f.write(chunk)
if "video" in asset['mimetype']:
video_duration = get_video_duration(asset['uri'])
if video_duration:
asset['duration'] = int(video_duration.total_seconds())
else:
asset['duration'] = 'N/A'
else:
# Crashes if it's not an int. We want that.
asset['duration'] = int(get('duration'))
if not asset['asset_id']:
raise Exception
if not asset['uri']:
raise Exception
return asset
else:
raise Exception("Not enough information provided. Please specify 'name', 'uri', and 'mimetype'.")
def prepare_schedule(request):
data = request.POST or request.FORM or {}
if 'model' in data:
data = json.loads(data['model'])
def get(key):
val = data.get(key, '')
return val.strip() if isinstance(val, str) else val
if all([get('name')]):
if get('pattern_days'):
pattern_days = [ int(x) for x in get('pattern_days') ]
pattern_days = reduce(operator.or_, pattern_days)
else:
pattern_days = None
schedule = {
'asset_id' : get('asset_id'),
'name': get('name'),
'duration': get('duration'),
'repeat': get('repeat'),
'priority': get('priority'),
'pattern_type': get('pattern_type'),
'pattern_days': pattern_days,
}
if get('start_date'):
schedule['start_date'] = datetime.strptime(get('start_date').split(".")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d")
else:
schedule['start_date'] = ""
if get('start_time'):
schedule['start_time'] = datetime.strptime(get('start_time').split(".")[0], "%I:%M %p")
else:
schedule['start_time'] = ""
if get('end_date'):
schedule['end_date'] = datetime.strptime(get('end_date').split(".")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d")
else:
schedule['end_date'] = ""
if get('end_time'):
schedule['end_time'] = datetime.strptime(get('end_time').split(".")[0], "%I:%M %p")
else:
schedule['end_time'] = ""
else:
raise Exception("Please provide a name")
return schedule
def prepare_shutdown(request):
data = request.POST or request.FORM or {}
if 'model' in data:
data = json.loads(data['model'])
print(data)
def get(key):
val = data.get(key, '')
return val.strip() if isinstance(val, str) else val
if all([get('day'),get('time')]):
shutdown = {
'day': int(get('day')),
'time': time(*(tuple(int(x) for x in get('time').split(':')))),
}
# shutdown['time'] = datetime.strptime(get('time'), "%H:%M")
# print(
# tuple(int(x) for x in get('time').split(':'))
# )
# shutdown['time'] = time(*(tuple(int(x) for x in get('time').split(':'))))
# print(shutdown['time'])
# print(shutdown)
else:
raise Exception("Please provide both Day and Time values.")
return shutdown
@route('/api/assets', method="GET")
def api_assets():
assets = assets_helper.read(db_conn)
return make_json_response(assets)
# api view decorator. handles errors
def api(view):
@wraps(view)
def api_view(*args, **kwargs):
try:
return make_json_response(view(*args, **kwargs))
except HTTPResponse:
raise
except Exception as e:
traceback.print_exc()
return api_error(str(e))
return api_view
@route('/api/assets', method="POST")
@api
def add_asset():
asset = prepare_asset(request)
if url_fails(asset['uri']):
raise Exception("Could not retrieve file. Check the asset URL.")
return assets_helper.create(db_conn, asset)
@route('/api/assets/:asset_id', method="GET")
@api
def edit_asset(asset_id):
return assets_helper.read(db_conn, asset_id)
@route('/api/assets/:asset_id', method=["PUT", "POST"])
@api
def edit_asset(asset_id):
return assets_helper.update(db_conn, asset_id, prepare_asset(request))
@route('/api/assets/:asset_id', method="DELETE")
@api
def remove_asset(asset_id):
asset = assets_helper.read(db_conn, asset_id)
try:
if asset['uri'].startswith(settings['assetdir']):
os.remove(asset['uri'])
except OSError:
pass
assets_helper.delete(db_conn, asset_id)
response.status = 204 # return an OK with no content
@route('/api/assets/order', method="POST")
@api
def playlist_order():
"Receive a list of asset_ids in the order they should be in the playlist"
for play_order, asset_id in enumerate(request.POST.get('ids', '').split(',')):
assets_helper.update(db_conn, asset_id, {'asset_id': asset_id, 'play_order': play_order})
################################
# Schedule Routes
@route('/api/schedules/:asset_id', method="GET")
def api_schedules(asset_id):
schedules = schedules_helper.read(db_conn, asset_id)
for schedule in schedules:
tList = []
if(isinstance(schedule['pattern_days'],(int,float))):
for name, member in list(AvailableDays.__members__.items()):
if schedule['pattern_days'] & member.value:
tList.append(member.value)
schedule['pattern_days'] = tList
return make_json_response(schedules)
@route('/api/schedules/:asset_id', method="POST")
@api
def add_schedule(asset_id):
return schedules_helper.create(db_conn, prepare_schedule(request))
@route('/api/schedules/:asset_id/:schedule_id', method=["POST", "PUT"])
@api
def edit_schedule(asset_id, schedule_id):
return schedules_helper.update(db_conn, schedule_id, prepare_schedule(request))
@route('/api/schedules/:asset_id/:schedule_id', method="DELETE")
@api
def remove_asset(asset_id, schedule_id):
schedules_helper.delete(db_conn, schedule_id)
response.status = 204 # return an OK with no content
################################
# Shutdown Routes
@route('/api/shutdowns', method="GET")
def api_shutdowns():
assets = shutdown_helper.read(db_conn)
assets.sort(key=lambda x: (x['day'], x['time']))
return make_json_response(assets)
@route('/api/shutdowns', method="POST")
@api
def add_shutdown():
return shutdown_helper.create(db_conn, prepare_shutdown(request))
@route('/api/shutdowns/:shutdown_id', method="DELETE")
@api
def remove_shutdown(shutdown_id):
shutdown_helper.delete(db_conn, shutdown_id)
response.status = 204 # return an OK with no content
################################
# Views
################################
@route('/')
def viewIndex():
return template('index')
@route('/asset/<asset_id>/schedule')
def viewSchedule(asset_id):
return template('schedule', asset_id=asset_id)
@route('/settings', method=["GET", "POST"])
def settings_page():
context = {'flash': None}
if request.method == "POST":
for field, default in list(DEFAULTS['viewer'].items()):
value = request.POST.get(field, default)
if isinstance(default, bool):
value = value == 'on'
settings[field] = value
try:
settings.save()
context['flash'] = {'class': "success", 'message': "Settings were successfully saved."}
except IOError as e:
context['flash'] = {'class': "error", 'message': e}
else:
settings.load()
for field, default in list(DEFAULTS['viewer'].items()):
context[field] = settings[field]
return template('settings', **context)
@route('/system_info')
def system_info():
viewer_log_file = '/tmp/screenly_viewer.log'
if path.exists(viewer_log_file):
viewlog = check_output(['tail', '-n', '20', viewer_log_file]).decode('ascii').split("\n")
else:
viewlog = ["(no viewer log present -- is only the screenly server running?)\n"]
# Get load average from last 15 minutes and round to two digits.
loadavg = round(getloadavg()[2], 2)
try:
run_tvservice = check_output(['tvservice', '-s']).decode('ascii')
display_info = re_split('\||,', run_tvservice.strip('state: 0xa'))
except:
display_info = False
# Calculate disk space
slash = statvfs("/")
free_space = size(slash.f_bavail * slash.f_frsize)
# Get uptime
uptime_in_seconds = uptime()
system_uptime = timedelta(seconds=uptime_in_seconds)
return template('system_info', viewlog=viewlog, loadavg=loadavg, free_space=free_space, uptime=system_uptime, display_info=display_info)
@route('/shutdown', method=["GET","POST"])
def shutdown():
if request.method == "POST":
if request.forms.get('shutnow') == "1":
sudo("shutdown", "-h", "-t now")
return template('shutdown', message='The Pi is shutting down. It will take a minute or two for this to complete.')
return template('shutdown')
@route('/splash_page')
def splash_page():
my_ip = get_node_ip()
if my_ip:
ip_lookup = True
url = "http://{}:{}".format(my_ip, settings.get_listen_port())
else:
ip_lookup = False
url = "Unable to look up your installation's IP address."
system_time = '%s %s' % (datetime.now().astimezone().strftime('%c'), str(datetime.now().astimezone().tzinfo))
return template('splash_page',
ip_lookup=ip_lookup,
url=url,
system_time = system_time
)
@error(403)
def mistake403(code):
return 'The parameter you passed has the wrong format!'
@error(404)
def mistake404(code):
return 'Sorry, this page does not exist!'
################################
# Static
################################
@route('/static/:path#.+#', name='static')
def static(path):
return static_file(path, root='static')
if __name__ == "__main__":
# Make sure the asset folder exist. If not, create it
if not path.isdir(settings['assetdir']):
mkdir(settings['assetdir'])
# Create config dir if it doesn't exist
if not path.isdir(settings.get_configdir()):
makedirs(settings.get_configdir())
with db.conn(settings['database']) as conn:
global db_conn
db_conn = conn
with db.cursor(db_conn) as c:
c.execute(queries.exists_table)
if c.fetchone() is None:
c.execute(assets_helper.create_assets_table)
c.execute(queries.exists_table_schedule)
if c.fetchone() is None:
c.execute(schedules_helper.create_schedules_table)
c.execute(queries.exists_table_shutdown)
if c.fetchone() is None:
c.execute(shutdown_helper.create_shutdown_table)
run(host=settings.get_listen_ip(),
port=settings.get_listen_port(),
reloader=True)