forked from Screenly/Anthias
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
executable file
·1884 lines (1591 loc) · 55.9 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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Screenly, Inc"
__copyright__ = "Copyright 2012-2021, Screenly, Inc"
__license__ = "Dual License: GPLv2 and Commercial License"
import json
import pydbus
import psutil
import re
import sh
import shutil
import time
import os
import traceback
import yaml
import uuid
from base64 import b64encode
from celery import Celery
from datetime import datetime, timedelta
from dateutil import parser as date_parser
from functools import wraps
from hurry.filesize import size
from mimetypes import guess_type, guess_extension
from os import getenv, listdir, makedirs, mkdir, path, remove, rename, statvfs, stat, walk
from subprocess import check_output
from urlparse import urlparse
from flask import Flask, escape, make_response, render_template, request, send_from_directory, url_for, jsonify
from flask_cors import CORS
from flask_restful_swagger_2 import Api, Resource, Schema, swagger
from flask_swagger_ui import get_swaggerui_blueprint
from gunicorn.app.base import Application
from werkzeug.wrappers import Request
from lib import assets_helper
from lib import backup_helper
from lib import db
from lib import diagnostics
from lib import queries
from lib import raspberry_pi_helper
from lib.github import is_up_to_date
from lib.auth import authorized
from lib.utils import download_video_from_youtube, json_dump
from lib.utils import generate_perfect_paper_password, is_docker
from lib.utils import get_active_connections, remove_connection
from lib.utils import get_node_ip, get_node_mac_address
from lib.utils import get_video_duration
from lib.utils import is_balena_app, is_demo_node
from lib.utils import string_to_bool
from lib.utils import connect_to_redis
from lib.utils import url_fails
from lib.utils import validate_url
from settings import CONFIGURABLE_SETTINGS, DEFAULTS, LISTEN, PORT, settings, ZmqPublisher, ZmqCollector
HOME = getenv('HOME', '/home/pi')
CELERY_RESULT_BACKEND = getenv('CELERY_RESULT_BACKEND', 'redis://localhost:6379/0')
CELERY_BROKER_URL = getenv('CELERY_BROKER_URL', 'redis://localhost:6379/0')
CELERY_TASK_RESULT_EXPIRES = timedelta(hours=6)
app = Flask(__name__)
app.debug = string_to_bool(os.getenv('DEBUG', 'False'))
CORS(app)
api = Api(app, api_version="v1", title="Screenly OSE API")
r = connect_to_redis()
celery = Celery(
app.name,
backend=CELERY_RESULT_BACKEND,
broker=CELERY_BROKER_URL,
result_expires=CELERY_TASK_RESULT_EXPIRES
)
################################
# Celery tasks
################################
@celery.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
# Calls cleanup() every hour.
sender.add_periodic_task(3600, cleanup.s(), name='cleanup')
sender.add_periodic_task(3600, cleanup_usb_assets.s(), name='cleanup_usb_assets')
sender.add_periodic_task(60*5, get_display_power.s(), name='display_power')
@celery.task
def get_display_power():
r.set('display_power', diagnostics.get_display_power())
r.expire('display_power', 3600)
@celery.task
def cleanup():
sh.find(path.join(HOME, 'screenly_assets'), '-name', '*.tmp', '-delete')
@celery.task
def reboot_screenly():
"""
Background task to reboot Screenly-OSE.
"""
r.publish('hostcmd', 'reboot')
@celery.task
def shutdown_screenly():
"""
Background task to shutdown Screenly-OSE.
"""
r.publish('hostcmd', 'shutdown')
@celery.task
def append_usb_assets(mountpoint):
"""
@TODO. Fix me. This will not work in Docker.
"""
settings.load()
datetime_now = datetime.now()
usb_assets_settings = {
'activate': False,
'copy': False,
'start_date': datetime_now,
'end_date': datetime_now + timedelta(days=7),
'duration': settings['default_duration']
}
for root, _, filenames in walk(mountpoint):
if 'usb_assets_key.yaml' in filenames:
with open("%s/%s" % (root, 'usb_assets_key.yaml'), 'r') as yaml_file:
usb_file_settings = yaml.load(yaml_file).get('screenly')
if usb_file_settings.get('key') == settings['usb_assets_key']:
if usb_file_settings.get('activate'):
usb_assets_settings.update({
'activate': usb_file_settings.get('activate')
})
if usb_file_settings.get('copy'):
usb_assets_settings.update({
'copy': usb_file_settings.get('copy')
})
if usb_file_settings.get('start_date'):
ts = time.mktime(datetime.strptime(usb_file_settings.get('start_date'), "%m/%d/%Y").timetuple())
usb_assets_settings.update({
'start_date': datetime.utcfromtimestamp(ts)
})
if usb_file_settings.get('end_date'):
ts = time.mktime(datetime.strptime(usb_file_settings.get('end_date'), "%m/%d/%Y").timetuple())
usb_assets_settings.update({
'end_date': datetime.utcfromtimestamp(ts)
})
if usb_file_settings.get('duration'):
usb_assets_settings.update({
'duration': usb_file_settings.get('duration')
})
files = ['%s/%s' % (root, y) for root, _, filenames in walk(mountpoint) for y in filenames]
with db.conn(settings['database']) as conn:
for filepath in files:
asset = prepare_usb_asset(filepath, **usb_assets_settings)
if asset:
assets_helper.create(conn, asset)
break
@celery.task
def remove_usb_assets(mountpoint):
"""
@TODO. Fix me. This will not work in Docker.
"""
settings.load()
with db.conn(settings['database']) as conn:
for asset in assets_helper.read(conn):
if asset['uri'].startswith(mountpoint):
assets_helper.delete(conn, asset['asset_id'])
@celery.task
def cleanup_usb_assets(media_dir='/media'):
"""
@TODO. Fix me. This will not work in Docker.
"""
settings.load()
mountpoints = ['%s/%s' % (media_dir, x) for x in listdir(media_dir) if path.isdir('%s/%s' % (media_dir, x))]
with db.conn(settings['database']) as conn:
for asset in assets_helper.read(conn):
if asset['uri'].startswith(media_dir):
location = re.search(r'^(/\w+/\w+[^/])', asset['uri'])
if location:
if location.group() not in mountpoints:
assets_helper.delete(conn, asset['asset_id'])
################################
# Utilities
################################
@api.representation('application/json')
def output_json(data, code, headers=None):
response = make_response(json_dump(data), code)
response.headers.extend(headers or {})
return response
def api_error(error):
return make_response(json_dump({'error': error}), 500)
def template(template_name, **context):
"""Screenly template response generator. Shares the
same function signature as Flask's render_template() method
but also injects some global context."""
# Add global contexts
context['date_format'] = settings['date_format']
context['default_duration'] = settings['default_duration']
context['default_streaming_duration'] = settings['default_streaming_duration']
context['template_settings'] = {
'imports': ['from lib.utils import template_handle_unicode'],
'default_filters': ['template_handle_unicode'],
}
context['up_to_date'] = is_up_to_date()
context['use_24_hour_clock'] = settings['use_24_hour_clock']
return render_template(template_name, context=context)
################################
# Models
################################
class AssetModel(Schema):
type = 'object'
properties = {
'asset_id': {'type': 'string'},
'name': {'type': 'string'},
'uri': {'type': 'string'},
'start_date': {
'type': 'string',
'format': 'date-time'
},
'end_date': {
'type': 'string',
'format': 'date-time'
},
'duration': {'type': 'string'},
'mimetype': {'type': 'string'},
'is_active': {
'type': 'integer',
'format': 'int64',
},
'is_enabled': {
'type': 'integer',
'format': 'int64',
},
'is_processing': {
'type': 'integer',
'format': 'int64',
},
'nocache': {
'type': 'integer',
'format': 'int64',
},
'play_order': {
'type': 'integer',
'format': 'int64',
},
'skip_asset_check': {
'type': 'integer',
'format': 'int64',
}
}
class AssetRequestModel(Schema):
type = 'object'
properties = {
'name': {'type': 'string'},
'uri': {'type': 'string'},
'start_date': {
'type': 'string',
'format': 'date-time'
},
'end_date': {
'type': 'string',
'format': 'date-time'
},
'duration': {'type': 'string'},
'mimetype': {'type': 'string'},
'is_enabled': {
'type': 'integer',
'format': 'int64',
},
'nocache': {
'type': 'integer',
'format': 'int64',
},
'play_order': {
'type': 'integer',
'format': 'int64',
},
'skip_asset_check': {
'type': 'integer',
'format': 'int64',
}
}
required = ['name', 'uri', 'mimetype', 'is_enabled', 'start_date', 'end_date']
class AssetContentModel(Schema):
type = 'object'
properties = {
'type': {'type': 'string'},
'url': {'type': 'string'},
'filename': {'type': 'string'},
'mimetype': {'type': 'string'},
'content': {
'type': 'string',
'format': 'byte'
},
}
required = ['type', 'filename']
class AssetPropertiesModel(Schema):
type = 'object'
properties = {
'name': {'type': 'string'},
'start_date': {
'type': 'string',
'format': 'date-time'
},
'end_date': {
'type': 'string',
'format': 'date-time'
},
'duration': {'type': 'string'},
'is_active': {
'type': 'integer',
'format': 'int64',
},
'is_enabled': {
'type': 'integer',
'format': 'int64',
},
'nocache': {
'type': 'integer',
'format': 'int64',
},
'play_order': {
'type': 'integer',
'format': 'int64',
},
'skip_asset_check': {
'type': 'integer',
'format': 'int64',
}
}
################################
# API
################################
def prepare_asset(request, unique_name=False):
req = Request(request.environ)
data = None
# For backward compatibility
try:
data = json.loads(req.data)
except ValueError:
data = json.loads(req.form['model'])
except TypeError:
data = json.loads(req.form['model'])
def get(key):
val = data.get(key, '')
if isinstance(val, unicode):
return val.strip()
elif isinstance(val, basestring):
return val.strip().decode('utf-8')
else:
return val
if not all([get('name'), get('uri'), get('mimetype')]):
raise Exception("Not enough information provided. Please specify 'name', 'uri', and 'mimetype'.")
name = escape(get('name'))
if unique_name:
with db.conn(settings['database']) as conn:
names = assets_helper.get_names_of_assets(conn)
if name in names:
i = 1
while True:
new_name = '%s-%i' % (name, i)
if new_name in names:
i += 1
else:
name = new_name
break
asset = {
'name': name,
'mimetype': get('mimetype'),
'asset_id': get('asset_id'),
'is_enabled': get('is_enabled'),
'is_processing': get('is_processing'),
'nocache': get('nocache'),
}
uri = escape(get('uri').encode('utf-8'))
if uri.startswith('/'):
if not path.isfile(uri):
raise Exception("Invalid file path. Failed to add asset.")
else:
if not validate_url(uri):
raise Exception("Invalid URL. Failed to add asset.")
if not asset['asset_id']:
asset['asset_id'] = uuid.uuid4().hex
if uri.startswith('/'):
rename(uri, path.join(settings['assetdir'], asset['asset_id']))
uri = path.join(settings['assetdir'], asset['asset_id'])
if 'youtube_asset' in asset['mimetype']:
uri, asset['name'], asset['duration'] = download_video_from_youtube(uri, asset['asset_id'])
asset['mimetype'] = 'video'
asset['is_processing'] = 1
asset['uri'] = uri
if "video" in asset['mimetype']:
if get('duration') == 'N/A' or int(get('duration')) == 0:
asset['duration'] = int(get_video_duration(uri).total_seconds())
else:
# Crashes if it's not an int. We want that.
asset['duration'] = int(get('duration'))
asset['skip_asset_check'] = int(get('skip_asset_check')) if int(get('skip_asset_check')) else 0
# parse date via python-dateutil and remove timezone info
if get('start_date'):
asset['start_date'] = date_parser.parse(get('start_date')).replace(tzinfo=None)
else:
asset['start_date'] = ""
if get('end_date'):
asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)
else:
asset['end_date'] = ""
return asset
def prepare_asset_v1_2(request_environ, asset_id=None, unique_name=False):
data = json.loads(request_environ.data)
def get(key):
val = data.get(key, '')
if isinstance(val, unicode):
return val.strip()
elif isinstance(val, basestring):
return val.strip().decode('utf-8')
else:
return val
if not all([get('name'),
get('uri'),
get('mimetype'),
str(get('is_enabled')),
get('start_date'),
get('end_date')]):
raise Exception(
"Not enough information provided. Please specify 'name', 'uri', 'mimetype', 'is_enabled', 'start_date' and 'end_date'.")
ampfix = "&"
name = escape(get('name').replace(ampfix, '&'))
if unique_name:
with db.conn(settings['database']) as conn:
names = assets_helper.get_names_of_assets(conn)
if name in names:
i = 1
while True:
new_name = '%s-%i' % (name, i)
if new_name in names:
i += 1
else:
name = new_name
break
asset = {
'name': name,
'mimetype': get('mimetype'),
'is_enabled': get('is_enabled'),
'nocache': get('nocache')
}
uri = (get('uri')).replace(ampfix, '&').replace('<', '<').replace('>', '>').replace('\'', ''').replace('\"', '"')
if uri.startswith('/'):
if not path.isfile(uri):
raise Exception("Invalid file path. Failed to add asset.")
else:
if not validate_url(uri):
raise Exception("Invalid URL. Failed to add asset.")
if not asset_id:
asset['asset_id'] = uuid.uuid4().hex
if not asset_id and uri.startswith('/'):
new_uri = "{}{}".format(path.join(settings['assetdir'], asset['asset_id']), get('ext'))
rename(uri, new_uri)
uri = new_uri
if 'youtube_asset' in asset['mimetype']:
uri, asset['name'], asset['duration'] = download_video_from_youtube(uri, asset['asset_id'])
asset['mimetype'] = 'video'
asset['is_processing'] = 1
asset['uri'] = uri
if "video" in asset['mimetype']:
if get('duration') == 'N/A' or int(get('duration')) == 0:
asset['duration'] = int(get_video_duration(uri).total_seconds())
elif get('duration'):
# Crashes if it's not an int. We want that.
asset['duration'] = int(get('duration'))
else:
asset['duration'] = 10
asset['play_order'] = get('play_order') if get('play_order') else 0
asset['skip_asset_check'] = int(get('skip_asset_check')) if int(get('skip_asset_check')) else 0
# parse date via python-dateutil and remove timezone info
asset['start_date'] = date_parser.parse(get('start_date')).replace(tzinfo=None)
asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)
return asset
def prepare_usb_asset(filepath, **kwargs):
filetype = guess_type(filepath)[0]
if not filetype:
return
filetype = filetype.split('/')[0]
if filetype not in ['image', 'video']:
return
asset_id = uuid.uuid4().hex
asset_name = path.basename(filepath)
duration = int(get_video_duration(filepath).total_seconds()) if "video" == filetype else int(kwargs['duration'])
if kwargs['copy']:
shutil.copy(filepath, path.join(settings['assetdir'], asset_id))
filepath = path.join(settings['assetdir'], asset_id)
return {
'asset_id': asset_id,
'duration': duration,
'end_date': kwargs['end_date'],
'is_active': 1,
'is_enabled': kwargs['activate'],
'is_processing': 0,
'mimetype': filetype,
'name': asset_name,
'nocache': 0,
'play_order': 0,
'skip_asset_check': 0,
'start_date': kwargs['start_date'],
'uri': filepath,
}
def prepare_default_asset(**kwargs):
if kwargs['mimetype'] not in ['image', 'video', 'webpage']:
return
asset_id = 'default_{}'.format(uuid.uuid4().hex)
duration = int(get_video_duration(kwargs['uri']).total_seconds()) if "video" == kwargs['mimetype'] else kwargs['duration']
return {
'asset_id': asset_id,
'duration': duration,
'end_date': kwargs['end_date'],
'is_active': 1,
'is_enabled': True,
'is_processing': 0,
'mimetype': kwargs['mimetype'],
'name': kwargs['name'],
'nocache': 0,
'play_order': 0,
'skip_asset_check': 0,
'start_date': kwargs['start_date'],
'uri': kwargs['uri']
}
def add_default_assets():
settings.load()
datetime_now = datetime.now()
default_asset_settings = {
'start_date': datetime_now,
'end_date': datetime_now.replace(year=datetime_now.year + 6),
'duration': settings['default_duration']
}
default_assets_yaml = path.join(HOME, '.screenly/default_assets.yml')
with open(default_assets_yaml, 'r') as yaml_file:
default_assets = yaml.safe_load(yaml_file).get('assets')
with db.conn(settings['database']) as conn:
for default_asset in default_assets:
default_asset_settings.update({
'name': default_asset.get('name'),
'uri': default_asset.get('uri'),
'mimetype': default_asset.get('mimetype')
})
asset = prepare_default_asset(**default_asset_settings)
if asset:
assets_helper.create(conn, asset)
def remove_default_assets():
settings.load()
with db.conn(settings['database']) as conn:
for asset in assets_helper.read(conn):
if asset['asset_id'].startswith('default_'):
assets_helper.delete(conn, asset['asset_id'])
def update_asset(asset, data):
for key, value in data.items():
if key in ['asset_id', 'is_processing', 'mimetype', 'uri'] or key not in asset:
continue
if key in ['start_date', 'end_date']:
value = date_parser.parse(value).replace(tzinfo=None)
if key in ['play_order', 'skip_asset_check', 'is_enabled', 'is_active', 'nocache']:
value = int(value)
if key == 'duration':
if "video" not in asset['mimetype']:
continue
value = int(value)
asset.update({key: value})
# api view decorator. handles errors
def api_response(view):
@wraps(view)
def api_view(*args, **kwargs):
try:
return view(*args, **kwargs)
except Exception as e:
traceback.print_exc()
return api_error(unicode(e))
return api_view
class Assets(Resource):
method_decorators = [authorized]
@swagger.doc({
'responses': {
'200': {
'description': 'List of assets',
'schema': {
'type': 'array',
'items': AssetModel
}
}
}
})
def get(self):
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
return assets
@api_response
@swagger.doc({
'parameters': [
{
'name': 'model',
'in': 'formData',
'type': 'string',
'description':
'''
Yes, that is just a string of JSON not JSON itself it will be parsed on the other end.
Content-Type: application/x-www-form-urlencoded
model: "{
"name": "Website",
"mimetype": "webpage",
"uri": "http://example.com",
"is_active": 0,
"start_date": "2017-02-02T00:33:00.000Z",
"end_date": "2017-03-01T00:33:00.000Z",
"duration": "10",
"is_enabled": 0,
"is_processing": 0,
"nocache": 0,
"play_order": 0,
"skip_asset_check": 0
}"
'''
}
],
'responses': {
'201': {
'description': 'Asset created',
'schema': AssetModel
}
}
})
def post(self):
asset = prepare_asset(request)
if url_fails(asset['uri']):
raise Exception("Could not retrieve file. Check the asset URL.")
with db.conn(settings['database']) as conn:
return assets_helper.create(conn, asset), 201
class Asset(Resource):
method_decorators = [api_response, authorized]
@swagger.doc({
'parameters': [
{
'name': 'asset_id',
'type': 'string',
'in': 'path',
'description': 'id of an asset'
}
],
'responses': {
'200': {
'description': 'Asset',
'schema': AssetModel
}
}
})
def get(self, asset_id):
with db.conn(settings['database']) as conn:
return assets_helper.read(conn, asset_id)
@swagger.doc({
'parameters': [
{
'name': 'asset_id',
'type': 'string',
'in': 'path',
'description': 'id of an asset'
},
{
'name': 'model',
'in': 'formData',
'type': 'string',
'description':
'''
Content-Type: application/x-www-form-urlencoded
model: "{
"asset_id": "793406aa1fd34b85aa82614004c0e63a",
"name": "Website",
"mimetype": "webpage",
"uri": "http://example.com",
"is_active": 0,
"start_date": "2017-02-02T00:33:00.000Z",
"end_date": "2017-03-01T00:33:00.000Z",
"duration": "10",
"is_enabled": 0,
"is_processing": 0,
"nocache": 0,
"play_order": 0,
"skip_asset_check": 0
}"
'''
}
],
'responses': {
'200': {
'description': 'Asset updated',
'schema': AssetModel
}
}
})
def put(self, asset_id):
with db.conn(settings['database']) as conn:
return assets_helper.update(conn, asset_id, prepare_asset(request))
@swagger.doc({
'parameters': [
{
'name': 'asset_id',
'type': 'string',
'in': 'path',
'description': 'id of an asset'
},
],
'responses': {
'204': {
'description': 'Deleted'
}
}
})
def delete(self, asset_id):
with db.conn(settings['database']) as conn:
asset = assets_helper.read(conn, asset_id)
try:
if asset['uri'].startswith(settings['assetdir']):
remove(asset['uri'])
except OSError:
pass
assets_helper.delete(conn, asset_id)
return '', 204 # return an OK with no content
class AssetsV1_1(Resource):
method_decorators = [authorized]
@swagger.doc({
'responses': {
'200': {
'description': 'List of assets',
'schema': {
'type': 'array',
'items': AssetModel
}
}
}
})
def get(self):
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
return assets
@api_response
@swagger.doc({
'parameters': [
{
'in': 'body',
'name': 'model',
'description': 'Adds a asset',
'schema': AssetModel,
'required': True
}
],
'responses': {
'201': {
'description': 'Asset created',
'schema': AssetModel
}
}
})
def post(self):
asset = prepare_asset(request, unique_name=True)
if url_fails(asset['uri']):
raise Exception("Could not retrieve file. Check the asset URL.")
with db.conn(settings['database']) as conn:
return assets_helper.create(conn, asset), 201
class AssetV1_1(Resource):
method_decorators = [api_response, authorized]
@swagger.doc({
'parameters': [
{
'name': 'asset_id',
'type': 'string',
'in': 'path',
'description': 'id of an asset'
}
],
'responses': {
'200': {
'description': 'Asset',
'schema': AssetModel
}
}
})
def get(self, asset_id):
with db.conn(settings['database']) as conn:
return assets_helper.read(conn, asset_id)
@swagger.doc({
'parameters': [
{
'name': 'asset_id',
'type': 'string',
'in': 'path',
'description': 'id of an asset',
'required': True
},
{
'in': 'body',
'name': 'model',
'description': 'Adds an asset',
'schema': AssetModel,
'required': True
}
],
'responses': {
'200': {
'description': 'Asset updated',
'schema': AssetModel
}
}
})
def put(self, asset_id):
with db.conn(settings['database']) as conn:
return assets_helper.update(conn, asset_id, prepare_asset(request))
@swagger.doc({
'parameters': [
{
'name': 'asset_id',
'type': 'string',
'in': 'path',
'description': 'id of an asset',
'required': True
},
],
'responses': {
'204': {
'description': 'Deleted'
}
}
})
def delete(self, asset_id):
with db.conn(settings['database']) as conn:
asset = assets_helper.read(conn, asset_id)
try:
if asset['uri'].startswith(settings['assetdir']):
remove(asset['uri'])
except OSError:
pass
assets_helper.delete(conn, asset_id)
return '', 204 # return an OK with no content
class AssetsV1_2(Resource):
method_decorators = [authorized]
@swagger.doc({
'responses': {
'200': {
'description': 'List of assets',
'schema': {
'type': 'array',
'items': AssetModel
}
}
}
})
def get(self):
with db.conn(settings['database']) as conn:
return assets_helper.read(conn)
@api_response
@swagger.doc({
'parameters': [
{
'in': 'body',
'name': 'model',
'description': 'Adds an asset',
'schema': AssetRequestModel,
'required': True
}
],
'responses': {
'201': {
'description': 'Asset created',
'schema': AssetModel
}
}
})
def post(self):
request_environ = Request(request.environ)