blob: 030e4fc8d4afcdba27280bf38df838ab85018cf5 [file] [log] [blame]
#// Copyright (c) 2000-2019 Ericsson Telecom AB //
#// All rights reserved. This program and the accompanying materials are made available under the terms //
#// of the Eclipse Public License v2.0 which accompanies this distribution, and is available at //
#// https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html //
#/////////////////////////////////////////////////////////////////////////////////////////////////////////
import os, json, logging
from Common.DsRestAPI import DsRestAPI
from ScheduledPlaylist import ScheduledPlaylist
from Help import DSHELP
class Playlist:
SOURCE_ID = 'Playlist'
def __init__(self, directory):
self._logger = logging.getLogger(__name__)
self._playlistDir = os.path.join(directory, 'Playlists')
self._dsRestAPI = DsRestAPI(self._getDataHandler, self._setDataHandler)
self._running = {}
def _getDataHandler(self, request, userCredentials):
element = request['element']
params = request['params']
if element == 'help':
help = {'sources': [{'source': self.SOURCE_ID, 'dataElements': DSHELP}]}
return {'node': {'val': json.dumps(help).encode('hex'), 'tp': 5}}
elif element == 'Playlists':
list = []
for dir in os.listdir(self._playlistDir):
if dir in userCredentials['groups']:
for file in os.listdir(os.path.join(self._playlistDir, dir)):
if file.endswith('.json'):
list.append({'node': {'val': os.path.join(dir, file)[:-5], 'tp': 10}})
list.sort(key = lambda element: element['node']['val'])
return {'list': list}
elif len(params) == 1 and params[0]['paramName'] == 'Playlist':
playlist = params[0]['paramValue']
if playlist.split('/')[0] in userCredentials['groups']:
if element == 'Status':
if playlist in self._running:
return self._running[params[0]['paramValue']].getStatus()
else:
return {'node': {'val': '[led:blue]Not running', 'tp': 11}}
elif element == 'Start':
tp = 1
if playlist in self._running and self._running[playlist].isRunning():
tp = -1
return {'node': {'val': '0', 'tp': tp}}
elif element == 'Stop':
tp = -1
if playlist in self._running and self._running[playlist].isRunning():
tp = 1
return {'node': {'val': '0', 'tp': tp}}
elif element == 'Pause':
tp = -1
if playlist in self._running and self._running[playlist].isRunning():
tp = 1
return {'node': {'val': '0', 'tp': tp}}
elif element == 'Edit':
return {'node': {'val': playlist, 'tp': 4}}
elif element == 'Delete':
return {'node': {'val': '0', 'tp': 1}}
elif element == 'Descriptor':
with open(os.path.join(self._playlistDir, playlist) + '.json', 'r') as f:
content = f.read()
return {'node': {'val': content, 'tp': 4}}
else:
return {'node': {'val': '', 'tp': 0}}
def _setDataHandler(self, request, userCredentials):
element = request['element']
params = request['params']
content = request['content']
if len(params) == 1 and params[0]['paramName'] == 'Playlist':
playlist = params[0]['paramValue']
group = playlist.split('/')[0]
if group in userCredentials['groups']:
if element == 'Start':
return self._start(playlist, userCredentials)
elif element == 'Stop':
return self._stop(playlist)
elif element == 'Pause':
return self._pause(playlist)
elif element == 'Descriptor':
groupDir = os.path.join(self._playlistDir, group)
if not os.path.exists(groupDir):
os.makedirs(groupDir)
with open(os.path.join(self._playlistDir, playlist) + '.json', 'w') as f:
f.write(content)
return {'node': {'val': 'saved', 'tp': 4}}
elif element == 'Delete':
fileName = os.path.join(self._playlistDir, playlist) + '.json'
os.unlink(fileName)
return {'node': {'val': '0', 'tp': 1}}
else:
return {'node': {'val': '', 'tp': 0}}
def _createPlaylistExecutor(self, descriptor):
return ScheduledPlaylist(descriptor)
def _start(self, playlist, userCredentials):
if playlist in self._running and self._running[playlist].isRunning():
return {'node': {'val': '0', 'tp': -1}}
try:
descriptor = []
with open(os.path.join(self._playlistDir, playlist) + '.json', 'r') as f:
descriptor = json.load(f)
scheduledPlaylist = self._createPlaylistExecutor(descriptor)
scheduledPlaylist.start(userCredentials)
self._running[playlist] = scheduledPlaylist
except:
self._logger.exception('Failed to start playlist')
return {'node': {'val': '0', 'tp': 1}}
def _stop(self, playlist):
if playlist in self._running and self._running[playlist].isRunning():
self._running[playlist].stop()
return {'node': {'val': '0', 'tp': 1}}
else:
return {'node': {'val': '0', 'tp': -1}}
def _pause(self, playlist):
if playlist in self._running and self._running[playlist].isRunning():
self._running[playlist].pause()
return {'node': {'val': '0', 'tp': 1}}
else:
return {'node': {'val': '0', 'tp': -1}}
def handleMessage(self, method, path, headers, body, userCredentials, response):
response['body'] = json.dumps(self._dsRestAPI.parseRequest(json.loads(body), userCredentials))
response['headers']['Content-Type'] = 'application/json'
def getDataSourceHandlers(self):
return {
self.SOURCE_ID: {
'getDataHandler': self._getDataHandler,
'setDataHandler': self._setDataHandler
}
}
def close(self):
for playlist in self._running:
self._stop(playlist)