Merge branch 'master' of dev.sourcefabric.org:campcaster

This commit is contained in:
Daniel James 2010-11-30 11:54:39 +00:00
commit 2f11263b4c
26 changed files with 1438 additions and 855 deletions

6
3rd_party/pypo/AUTHORS vendored Normal file
View file

@ -0,0 +1,6 @@
This tool was born out of a collaboration between Open Broadcast
and Sourcefabric. The authors of the code are:
Jonas Ohrstrom <jonas@digris.ch>
Paul Baranowski <paul.baranowski@sourcefabric.org>

View file

@ -1,6 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# This file holds the implementations for all the API clients.
#
# If you want to develop a new client, here are some suggestions:
# Get the fetch methods working first, then the push, then the liquidsoap notifier.
# You will probably want to create a script on your server side to automatically
# schedule a playlist one minute from the current time.
###############################################################################
import sys
import time
import urllib
@ -22,49 +31,82 @@ def api_client_factory(config):
class ApiClientInterface:
# This is optional.
# Implementation: optional
#
# Called from: beginning of all scripts
#
# Should exit the program if this version of pypo is not compatible with
# 3rd party software.
def check_version(self):
nil
pass
# Required.
# Implementation: Required
#
# Called from: fetch loop
#
# This is the main method you need to implement when creating a new API client.
# start and end are for testing purposes.
# start and end are strings in the format YYYY-DD-MM-hh-mm-ss
def get_schedule(self, start=None, end=None):
return 0, []
# Required.
# Implementation: Required
#
# Called from: fetch loop
#
# This downloads the media from the server.
def get_media(self, src, dst):
nil
pass
# This is optional.
# You dont actually have to implement this function for the liquidsoap playout to work.
def update_scheduled_item(self, item_id, value):
nil
# Implementation: optional
#
# Called from: push loop
#
# Tell server that the scheduled *playlist* has started.
def notify_scheduled_item_start_playing(self, pkey, schedule):
pass
# This is optional.
# Implementation: optional
# You dont actually have to implement this function for the liquidsoap playout to work.
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
nil
#
# Called from: pypo_notify.py
#
# This is a callback from liquidsoap, we use this to notify about the
# currently playing *song*. We get passed a JSON string which we handed to
# liquidsoap in get_liquidsoap_data().
def notify_media_item_start_playing(self, data, media_id):
pass
# Implementation: optional
# You dont actually have to implement this function for the liquidsoap playout to work.
def generate_range_dp(self):
nil
pass
# Implementation: optional
#
# Called from: push loop
#
# Return a dict of extra info you want to pass to liquidsoap
# You will be able to use this data in update_start_playing
def get_liquidsoap_data(self, pkey, schedule):
pass
# Put here whatever tests you want to run to make sure your API is working
def test(self):
nil
pass
#def get_media_type(self, playlist):
# nil
################################################################################
# Campcaster API Client
################################################################################
class CampcasterApiClient(ApiClientInterface):
def __init__(self, config):
self.config = config
#self.api_auth = api_auth
def __get_campcaster_version(self):
logger = logging.getLogger()
@ -109,7 +151,6 @@ class CampcasterApiClient(ApiClientInterface):
def test(self):
logger = logging.getLogger()
status, items = self.get_schedule('2010-01-01-00-00-00', '2011-01-01-00-00-00')
#print items
schedule = items["playlists"]
logger.debug("Number of playlists found: %s", str(len(schedule)))
count = 1
@ -117,12 +158,10 @@ class CampcasterApiClient(ApiClientInterface):
logger.debug("Playlist #%s",str(count))
count+=1
#logger.info("found playlist at %s", pkey)
#print pkey
playlist = schedule[pkey]
for item in playlist["medias"]:
filename = urlparse(item["uri"])
filename = filename.query[5:]
#print filename
self.get_media(item["uri"], filename)
@ -142,6 +181,7 @@ class CampcasterApiClient(ApiClientInterface):
print 'pypo is compatible with this version of Campcaster.'
print
def get_schedule(self, start=None, end=None):
logger = logging.getLogger()
@ -183,26 +223,26 @@ class CampcasterApiClient(ApiClientInterface):
except Exception, e:
print e
schedule = response["playlists"]
scheduleKeys = sorted(schedule.iterkeys())
# Remove all playlists that have passed current time
try:
tnow = time.localtime(time.time())
str_tnow_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tnow[0], tnow[1], tnow[2], tnow[3], tnow[4], tnow[5])
toRemove = []
for pkey in scheduleKeys:
if (str_tnow_s > schedule[pkey]['end']):
toRemove.append(pkey)
else:
break
#logger.debug("Remove keys: %s", toRemove)
for index in toRemove:
del schedule[index]
#logger.debug("Schedule dict: %s", schedule)
except Exception, e:
logger.debug("'Ignore Past Playlists' feature not supported by API: %s", e)
response["playlists"] = schedule
#schedule = response["playlists"]
#scheduleKeys = sorted(schedule.iterkeys())
#
## Remove all playlists that have passed current time
#try:
# tnow = time.localtime(time.time())
# str_tnow_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tnow[0], tnow[1], tnow[2], tnow[3], tnow[4], tnow[5])
# toRemove = []
# for pkey in scheduleKeys:
# if (str_tnow_s > schedule[pkey]['end']):
# toRemove.append(pkey)
# else:
# break
# #logger.debug("Remove keys: %s", toRemove)
# for index in toRemove:
# del schedule[index]
# #logger.debug("Schedule dict: %s", schedule)
#except Exception, e:
# logger.debug("'Ignore Past Playlists' feature not supported by API: %s", e)
#response["playlists"] = schedule
return status, response
@ -220,51 +260,58 @@ class CampcasterApiClient(ApiClientInterface):
logger.error("%s", e)
def update_scheduled_item(self, item_id, value):
pass
#logger = logging.getLogger()
#
#url = self.config["base_url"] + self.config["api_base"] + self.config["update_item_url"]
#
#try:
# response = urllib.urlopen(url, self.api_auth)
# response = json.read(response.read())
# logger.info("API-Status %s", response['status'])
# logger.info("API-Message %s", response['message'])
#
#except Exception, e:
# print e
# api_status = False
# logger.critical("Unable to connect - %s", e)
#
#return response
"""
Tell server that the scheduled *playlist* has started.
"""
def notify_scheduled_item_start_playing(self, pkey, schedule):
logger = logging.getLogger()
playlist = schedule[pkey]
schedule_id = playlist["schedule_id"]
url = self.config["base_url"] + self.config["api_base"] + self.config["update_item_url"]
url = url.replace("%%schedule_id%%", str(schedule_id))
url += "&api_key=" + self.config["api_key"]
logger.debug(url)
try:
response = urllib.urlopen(url)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
logger.critical("Unable to connect - %s", e)
return response
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
pass
#logger = logging.getLogger()
#
#url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
#url = url.replace("%%playlist_type%%", str(playlist_type))
#url = url.replace("%%export_source%%", str(export_source))
#url = url.replace("%%media_id%%", str(media_id))
#url = url.replace("%%playlist_id%%", str(playlist_id))
#url = url.replace("%%transmission_id%%", str(transmission_id))
#print url
#
#try:
# response = urllib.urlopen(url)
# response = json.read(response.read())
# logger.info("API-Status %s", response['status'])
# logger.info("API-Message %s", response['message'])
# logger.info("TXT %s", response['str_dls'])
#
#except Exception, e:
# print e
# api_status = False
# logger.critical("Unable to connect - %s", e)
#
#return response
"""
This is a callback from liquidsoap, we use this to notify about the
currently playing *song*. We get passed a JSON string which we handed to
liquidsoap in get_liquidsoap_data().
"""
def notify_media_item_start_playing(self, data, media_id):
logger = logging.getLogger()
response = ''
if (data[0] != '{'):
return response
try:
data = json.read(data)
logger.debug(str(data))
schedule_id = data["schedule_id"]
url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
url = url.replace("%%media_id%%", str(media_id))
url = url.replace("%%schedule_id%%", str(schedule_id))
url += "&api_key=" + self.config["api_key"]
logger.debug(url)
response = urllib.urlopen(url)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
logger.critical("Exception: %s", e)
return response
def generate_range_dp(self):
@ -287,6 +334,17 @@ class CampcasterApiClient(ApiClientInterface):
#
#return response
def get_liquidsoap_data(self, pkey, schedule):
logger = logging.getLogger()
playlist = schedule[pkey]
data = dict()
try:
data["schedule_id"] = playlist['id']
except Exception, e:
data["schedule_id"] = 0
data = json.write(data)
return data
################################################################################
@ -327,7 +385,7 @@ class ObpApiClient():
def get_obp_version(self):
logger = logging.getLogger("ObpApiClient.get_obp_version")
logger = logging.getLogger()
# lookup OBP version
url = self.config["base_url"] + self.config["api_base"]+ self.config["version_url"]
@ -369,7 +427,7 @@ class ObpApiClient():
def get_schedule(self, start=None, end=None):
logger = logging.getLogger("CampcasterApiClient.get_schedule")
logger = logging.getLogger()
"""
calculate start/end time range (format: YYYY-DD-MM-hh-mm-ss,YYYY-DD-MM-hh-mm-ss)
@ -421,13 +479,15 @@ class ObpApiClient():
logger.error("%s", e)
def update_scheduled_item(self, item_id, value):
logger = logging.getLogger("ObpApiClient.update_scheduled_item")
# lookup OBP version
"""
Tell server that the scheduled *playlist* has started.
"""
def notify_scheduled_item_start_playing(self, pkey, schedule):
#def update_scheduled_item(self, item_id, value):
logger = logging.getLogger()
url = self.config["base_url"] + self.config["api_base"] + self.config["update_item_url"]
url = url.replace("%%item_id%%", str(item_id))
url = url.replace("%%played%%", str(value))
url = url.replace("%%item_id%%", str(schedule[pkey]["id"]))
url = url.replace("%%played%%", "1")
try:
response = urllib.urlopen(url, self.api_auth)
@ -442,9 +502,18 @@ class ObpApiClient():
return response
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
logger = logging.getLogger("ApiClient.update_scheduled_item")
"""
This is a callback from liquidsoap, we use this to notify about the
currently playing *song*. We get passed a JSON string which we handed to
liquidsoap in get_liquidsoap_data().
"""
def notify_media_item_start_playing(self, data, media_id):
# def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
logger = logging.getLogger()
playlist_type = data["playlist_type"]
export_source = data["export_source"]
playlist_id = data["playlist_id"]
transmission_id = data["transmission_id"]
url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
url = url.replace("%%playlist_type%%", str(playlist_type))
@ -470,7 +539,7 @@ class ObpApiClient():
def generate_range_dp(self):
logger = logging.getLogger("ObpApiClient.generate_range_dp")
logger = logging.getLogger()
url = self.config["base_url"] + self.config["api_base"] + self.config["generate_range_url"]
@ -486,5 +555,20 @@ class ObpApiClient():
api_status = False
logger.critical("Unable to handle the OBP API request - %s", e)
return response
def get_liquidsoap_data(self, pkey, schedule):
playlist = schedule[pkey]
data = dict()
data["ptype"] = playlist['subtype']
try:
data["user_id"] = playlist['user_id']
data["playlist_id"] = playlist['id']
data["transmission_id"] = playlist['schedule_id']
except Exception, e:
data["playlist_id"] = 0
data["user_id"] = 0
data["transmission_id"] = 0
data = json.write(data)
return data

View file

@ -1,136 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
import urllib
import logging
from util import json
import os
class CampcasterApiClient():
def __init__(self, config):
self.config = config
#self.api_auth = api_auth
def check_version(self):
version = self.get_campcaster_version()
if (version == 0):
print 'Unable to get Campcaster version number.'
print
sys.exit()
elif (version[0:4] != "1.6."):
print 'Campcaster version: ' + str(version)
print 'pypo not compatible with this version of Campcaster'
print
sys.exit()
else:
print 'Campcaster version: ' + str(version)
print 'pypo is compatible with this version of OBP'
print
def get_campcaster_version(self):
logger = logging.getLogger("ApiClient.get_campcaster_version")
url = self.config["base_url"] + self.config["api_base"] + self.config["version_url"]
url = url.replace("%%api_key%%", self.config["api_key"])
try:
logger.debug("Trying to contact %s", url)
response = urllib.urlopen(url)
data = response.read()
response_json = json.read(data)
version = response_json['version']
logger.debug("Campcaster Version %s detected", version)
except Exception, e:
try:
if e[1] == 401:
print '#####################################'
print '# YOUR API KEY SEEMS TO BE INVALID:'
print '# ' + self.config["api_key"]
print '#####################################'
sys.exit()
except Exception, e:
pass
try:
if e[1] == 404:
print '#####################################'
print '# Unable to contact the OBP-API'
print '# ' + url
print '#####################################'
sys.exit()
except Exception, e:
pass
version = 0
logger.error("Unable to detect Campcaster Version - %s", e)
return version
def update_scheduled_item(self, item_id, value):
logger = logging.getLogger("ApiClient.update_scheduled_item")
url = self.api_url + 'schedule/schedule.php?item_id=' + str(item_id) + '&played=' + str(value)
try:
response = urllib.urlopen(url, self.api_auth)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
print e
api_status = False
logger.critical("Unable to connect - %s", e)
return response
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
logger = logging.getLogger("ApiClient.update_scheduled_item")
url = self.api_url + 'schedule/update_start_playing.php' \
+ '?playlist_type=' + str(playlist_type) \
+ '&export_source=' + str(export_source) \
+ '&export_source=' + str(export_source) \
+ '&media_id=' + str(media_id) \
+ '&playlist_id=' + str(playlist_id) \
+ '&transmission_id=' + str(transmission_id)
print url
try:
response = urllib.urlopen(url, self.api_auth)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
logger.info("TXT %s", response['str_dls'])
except Exception, e:
print e
api_status = False
logger.critical("Unable to connect - %s", e)
return response
def generate_range_dp(self):
logger = logging.getLogger("ApiClient.generate_range_dp")
url = self.api_url + 'schedule/generate_range_dp.php'
try:
response = urllib.urlopen(url, self.api_auth)
response = json.read(response.read())
logger.debug("Trying to contact %s", url)
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
print e
api_status = False
logger.critical("Unable to handle the request - %s", e)
return response

View file

@ -1,165 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
import sys
import time
import urllib
import logging
from util import json
import os
OBP_MIN_VERSION = 2010100101 # required obp version
class ObpApiClient():
def __init__(self, config):
self.config = config
#self.api_url = api_url
#self.api_auth = api_auth
def check_version(self):
obp_version = self.get_obp_version()
if obp_version == 0:
print '#################################################'
print 'Unable to get OBP version. Is OBP up and running?'
print '#################################################'
print
sys.exit()
elif obp_version < OBP_MIN_VERSION:
print 'OBP version: ' + str(obp_version)
print 'OBP min-version: ' + str(OBP_MIN_VERSION)
print 'pypo not compatible with this version of OBP'
print
sys.exit()
else:
print 'OBP API: ' + str(API_BASE)
print 'OBP version: ' + str(obp_version)
print 'OBP min-version: ' + str(OBP_MIN_VERSION)
print 'pypo is compatible with this version of OBP'
print
def get_obp_version(self):
logger = logging.getLogger("ApiClient.get_obp_version")
# lookup OBP version
url = self.api_url + 'api/pypo/status/json'
try:
logger.debug("Trying to contact %s", url)
response = urllib.urlopen(url, self.api_auth)
response_json = json.read(response.read())
obp_version = int(response_json['version'])
logger.debug("OBP Version %s detected", obp_version)
except Exception, e:
try:
if e[1] == 401:
print '#####################################'
print '# YOUR API KEY SEEMS TO BE INVALID'
print '# ' + self.api_auth
print '#####################################'
sys.exit()
except Exception, e:
pass
try:
if e[1] == 404:
print '#####################################'
print '# Unable to contact the OBP-API'
print '# ' + url
print '#####################################'
sys.exit()
except Exception, e:
pass
obp_version = 0
logger.error("Unable to detect OBP Version - %s", e)
return obp_version
def update_scheduled_item(self, item_id, value):
logger = logging.getLogger("ApiClient.update_shedueled_item")
# lookup OBP version
url = self.api_url + 'api/pypo/update_scheduled_item/' + str(item_id) + '?played=' + str(value)
try:
response = urllib.urlopen(url, self.api_auth)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
print e
api_status = False
logger.critical("Unable to connect to the OBP API - %s", e)
return response
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
logger = logging.getLogger("ApiClient.update_shedueled_item")
url = self.api_url + 'api/pypo/update_start_playing/' \
+ '?playlist_type=' + str(playlist_type) \
+ '&export_source=' + str(export_source) \
+ '&export_source=' + str(export_source) \
+ '&media_id=' + str(media_id) \
+ '&playlist_id=' + str(playlist_id) \
+ '&transmission_id=' + str(transmission_id)
print url
try:
response = urllib.urlopen(url, self.api_auth)
response = json.read(response.read())
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
logger.info("TXT %s", response['str_dls'])
except Exception, e:
print e
api_status = False
logger.critical("Unable to connect to the OBP API - %s", e)
return response
def generate_range_dp(self):
logger = logging.getLogger("ApiClient.generate_range_dp")
url = self.api_url + 'api/pypo/generate_range_dp/'
try:
response = urllib.urlopen(url, self.api_auth)
response = json.read(response.read())
logger.debug("Trying to contact %s", url)
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
print e
api_status = False
logger.critical("Unable to handle the OBP API request - %s", e)
return response

View file

@ -14,67 +14,12 @@ api_client = "campcaster"
# _include_ trailing slash !! #
############################################
cache_dir = '/opt/pypo/cache/'
schedule_dir = '/opt/pypo/cache/schedule'
file_dir = '/opt/pypo/files/'
tmp_dir = '/opt/pypo/tmp/'
############################################
# API path & co #
############################################
# Value needed to access the API
api_key = 'AAA'
# Hostname
base_url = 'http://localhost/'
################################################################################
# Generic Config - if you are creating a new API client, define these values #
################################################################################
# Path to the base of the API
#api_base = ''
# URL to get the version number of the API
#version_url = ''
# Schedule export path.
# %%from%% - starting date/time in the form YYYY-MM-DD-hh-mm
# %%to%% - starting date/time in the form YYYY-MM-DD-hh-mm
#export_url = ''
# Update whether an item has been played.
# %%item_id%%
# %%played%%
#update_item_url = ''
# Update whether an item is currently playing.
#update_start_playing_url = ''
# ???
#generate_range_url = ''
#####################
# Campcaster Config #
#####################
api_base = 'campcaster/'
version_url = 'api/api_version.php?api_key=%%api_key%%'
export_url = 'api/schedule.php?from=%%from%%&to=%%to%%&api_key=%%api_key%%'
update_item_url = 'api/schedule.php?item_id=%%item_id%%&played=%%played%%'
update_start_playing_url = 'api/update_start_playing.php?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
generate_range_url = 'api/generate_range_dp.php'
##############
# OBP config #
##############
#base_url = 'http://localhost/'
#api_base = ''
#version_url = 'api/pypo/status/json'
#update_item_url = 'api/pypo/update_shedueled_item/$$item_id%%?played=%%played%%'
#update_start_playing_url = 'api/pypo/update_start_playing/?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
#generate_range_url = 'api/pypo/generate_range_dp/'
############################################
# Liquidsoap settings #
############################################
@ -87,10 +32,90 @@ ls_port = '1234'
prepare_ahead = 24 #in hours
cache_for = 24 #how long to hold the cache, in hours
poll_interval = 10 # in seconds
# Poll interval in seconds.
#
# This is how often the poll script downloads new schedules and files from the
# server.
#
# For production use, this number depends on whether you plan on making any
# last-minute changes to your schedule. This number should be set to half of
# the time you expect to "lock-in" your schedule. So if your schedule is set
# 24 hours in advance, this can be set to poll every 12 hours.
#
poll_interval = 10 # in seconds.
# Push interval in seconds.
#
# This is how often the push script checks whether it has something new to
# push to liquidsoap.
#
# It's hard to imagine a situation where this should be more than 1 second.
#
push_interval = 1 # in seconds
# 'pre' or 'otf'. 'pre' cues while playlist preparation
# while 'otf' (on the fly) cues while loading into ls
# (needs the post_processor patch)
cue_style = 'pre'
################################################################################
# Uncomment *one of the sets* of values from the API clients below, and comment
# out all the others.
################################################################################
#####################
# Campcaster Config #
#####################
# Value needed to access the API
api_key = 'AAA'
# Path to the base of the API
api_base = 'campcaster/'
# URL to get the version number of the server API
version_url = 'api/api_version.php?api_key=%%api_key%%'
# Schedule export path.
# %%from%% - starting date/time in the form YYYY-MM-DD-hh-mm
# %%to%% - starting date/time in the form YYYY-MM-DD-hh-mm
export_url = 'api/schedule.php?from=%%from%%&to=%%to%%&api_key=%%api_key%%'
# Update whether a schedule group has begun playing.
update_item_url = 'api/notify_schedule_group_play.php?schedule_id=%%schedule_id%%'
# Update whether an audio clip is currently playing.
update_start_playing_url = 'api/notify_media_item_start_play.php?media_id=%%media_id%%&schedule_id=%%schedule_id%%'
# ???
generate_range_url = 'api/generate_range_dp.php'
##############
# OBP config #
##############
# Value needed to access the API
#api_key = 'AAA'
#base_url = 'http://localhost/'
# Path to the base of the API
#api_base = ''
# URL to get the version number of the server API
#version_url = 'api/pypo/status/json'
# Schedule export path.
# %%from%% - starting date/time in the form YYYY-MM-DD-hh-mm
# %%to%% - starting date/time in the form YYYY-MM-DD-hh-mm
# Update whether an item has been played.
#update_item_url = 'api/pypo/update_shedueled_item/$$item_id%%?played=%%played%%'
# Update whether an item is currently playing.
#update_start_playing_url = 'api/pypo/mod/medialibrary/?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
# ???
#generate_range_url = 'api/pypo/generate_range_dp/'

View file

@ -1,8 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
"""
Python part of radio playout (pypo)

View file

@ -1,8 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
"""
Python part of radio playout (pypo)
@ -19,7 +17,7 @@ tracks over and over again.
Attention & ToDos
- liquidsoap does not like mono files! So we have to make sure that only files with
2 channels are fed to LS
2 channels are fed to LiquidSoap
(solved: current = audio_to_stereo(current) - maybe not with ultimate performance)
@ -74,14 +72,14 @@ parser = OptionParser(usage=usage)
parser.add_option("-v", "--compat", help="Check compatibility with server API version", default=False, action="store_true", dest="check_compat")
parser.add_option("-t", "--test", help="Do a test to make sure everything is working properly.", default=False, action="store_true", dest="test")
parser.add_option("-f", "--fetch-scheduler", help="Fetch from scheduler - scheduler (loop, interval in config file)", default=False, action="store_true", dest="fetch_scheduler")
parser.add_option("-p", "--push-scheduler", help="Push scheduler to Liquidsoap (loop, interval in config file)", default=False, action="store_true", dest="push_scheduler")
parser.add_option("-f", "--fetch-scheduler", help="Fetch the schedule from server. This is a polling process that runs forever.", default=False, action="store_true", dest="fetch_scheduler")
parser.add_option("-p", "--push-scheduler", help="Push the schedule to Liquidsoap. This is a polling process that runs forever.", default=False, action="store_true", dest="push_scheduler")
parser.add_option("-F", "--fetch-daypart", help="Fetch from daypart - scheduler (loop, interval in config file)", default=False, action="store_true", dest="fetch_daypart")
parser.add_option("-P", "--push-daypart", help="Push daypart to Liquidsoap (loop, interval in config file)", default=False, action="store_true", dest="push_daypart")
parser.add_option("-b", "--cleanup", help="Cleanup", default=False, action="store_true", dest="cleanup")
parser.add_option("-j", "--jingles", help="Get new jingles from obp, comma separated list if jingle-id's as argument", metavar="LIST")
#parser.add_option("-j", "--jingles", help="Get new jingles from server, comma separated list if jingle-id's as argument", metavar="LIST")
parser.add_option("-c", "--check", help="Check the cached schedule and exit", default=False, action="store_true", dest="check")
# parse options
@ -93,32 +91,19 @@ logging.config.fileConfig("logging.cfg")
# loading config file
try:
config = ConfigObj('config.cfg')
CACHE_DIR = config['cache_dir']
FILE_DIR = config['file_dir']
TMP_DIR = config['tmp_dir']
API_BASE = config['api_base']
API_KEY = config['api_key']
POLL_INTERVAL = float(config['poll_interval'])
PUSH_INTERVAL = float(config['push_interval'])
LS_HOST = config['ls_host']
LS_PORT = config['ls_port']
#PREPARE_AHEAD = config['prepare_ahead']
CACHE_FOR = config['cache_for']
CUE_STYLE = config['cue_style']
#print config
except Exception, e:
print 'Error loading config file: ', e
sys.exit()
#TIME = time.localtime(time.time())
TIME = (2010, 6, 26, 15, 33, 23, 2, 322, 0)
class Global:
def __init__(self):
print
def selfcheck(self):
self.api_auth = urllib.urlencode({'api_key': API_KEY})
self.api_client = api_client.api_client_factory(config)
self.api_client.check_version()
@ -128,18 +113,23 @@ class Global:
"""
class Playout:
def __init__(self):
self.file_dir = FILE_DIR
self.tmp_dir = TMP_DIR
self.api_auth = urllib.urlencode({'api_key': API_KEY})
self.api_client = api_client.api_client_factory(config)
self.cue_file = CueFile()
self.silence_file = self.file_dir + 'basic/silence.mp3'
# set initial state
self.silence_file = config["file_dir"] + 'basic/silence.mp3'
self.push_ahead = 15
self.range_updated = False
def test_api(self):
self.api_client.test()
def set_export_source(self, export_source):
self.export_source = export_source
self.cache_dir = config["cache_dir"] + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule.pickle'
self.schedule_tracker_file = self.cache_dir + "schedule_tracker.pickle"
"""
Fetching part of pypo
@ -155,9 +145,7 @@ class Playout:
"""
logger = logging.getLogger()
self.export_source = export_source
self.cache_dir = CACHE_DIR + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule'
self.set_export_source(export_source)
try: os.mkdir(self.cache_dir)
except Exception, e: pass
@ -185,10 +173,10 @@ class Playout:
except Exception, e: logger.error("%s", e)
# prepare the playlists
if CUE_STYLE == 'pre':
try: self.prepare_playlists_cue(self.export_source)
if config["cue_style"] == 'pre':
try: self.prepare_playlists_cue()
except Exception, e: logger.error("%s", e)
elif CUE_STYLE == 'otf':
elif config["cue_style"] == 'otf':
try: self.prepare_playlists(self.export_source)
except Exception, e: logger.error("%s", e)
@ -210,10 +198,10 @@ class Playout:
tnow = time.localtime(time.time())
if(tnow[3] == 16):
if (tnow[3] == 16):
self.range_updated = False
if(tnow[3] == 17 and self.range_updated == False):
if (tnow[3] == 17 and self.range_updated == False):
try:
print self.api_client.generate_range_dp()
logger.info("daypart updated")
@ -248,18 +236,11 @@ class Playout:
playlist folder.
file is eg 2010-06-23-15-00-00/17_cue_10.132-123.321.mp3
"""
def prepare_playlists_cue(self, export_source):
def prepare_playlists_cue(self):
logger = logging.getLogger()
self.export_source = export_source
try:
schedule_file = open(self.schedule_file, "r")
schedule = pickle.load(schedule_file)
schedule_file.close()
except Exception, e:
logger.error("%s", e)
schedule = None
# Load schedule from disk
schedule = self.load_schedule()
# Dont do anything if schedule is empty
if (not schedule):
@ -271,7 +252,6 @@ class Playout:
try:
for pkey in scheduleKeys:
logger.info("found playlist at %s", pkey)
#print pkey
playlist = schedule[pkey]
# create playlist directory
@ -282,18 +262,20 @@ class Playout:
ls_playlist = '';
print '*****************************************'
print 'pkey: ' + str(pkey)
print 'cached at : ' + self.cache_dir + str(pkey)
print 'subtype: ' + str(playlist['subtype'])
print 'played: ' + str(playlist['played'])
print 'schedule id: ' + str(playlist['schedule_id'])
print 'duration: ' + str(playlist['duration'])
print 'source id: ' + str(playlist['x_ident'])
print '*****************************************'
logger.debug('*****************************************')
logger.debug('pkey: ' + str(pkey))
logger.debug('cached at : ' + self.cache_dir + str(pkey))
logger.debug('subtype: ' + str(playlist['subtype']))
logger.debug('played: ' + str(playlist['played']))
logger.debug('schedule id: ' + str(playlist['schedule_id']))
logger.debug('duration: ' + str(playlist['duration']))
logger.debug('source id: ' + str(playlist['x_ident']))
logger.debug('*****************************************')
# Creating an API call like the next two lines would make this more flexible
# mediaType = api_client.get_media_type(playlist)
# if (mediaType == PYPO_MEDIA_SKIP):
#mediaType = api_client.get_media_type(playlist)
#if (mediaType == PYPO_MEDIA_SKIP):
if int(playlist['played']) == 1:
logger.info("playlist %s already played / sent to liquidsoap, so will ignore it", pkey)
@ -401,7 +383,6 @@ class Playout:
if True == os.access(dst, os.R_OK):
# check filesize (avoid zero-byte files)
#print 'waiting: ' + dst
try: fsize = os.path.getsize(dst)
except Exception, e:
logger.error("%s", e)
@ -445,15 +426,11 @@ class Playout:
else:
if os.path.isfile(dst):
logger.debug("file already in cache: %s", dst)
#print 'cached'
else:
logger.debug("try to download and cue %s", media['uri'])
#print '***'
dst_tmp = self.tmp_dir + "".join([random.choice(string.letters) for i in xrange(10)]) + '.mp3'
#print dst_tmp
#print '***'
dst_tmp = config["tmp_dir"] + "".join([random.choice(string.letters) for i in xrange(10)]) + '.mp3'
self.api_client.get_media(media['uri'], dst_tmp)
# cue
@ -509,7 +486,7 @@ class Playout:
logger.debug("try to copy and cue %s", media['uri'])
print '***'
dst_tmp = self.tmp_dir + "".join([random.choice(string.letters) for i in xrange(10)])
dst_tmp = config["tmp_dir"] + "".join([random.choice(string.letters) for i in xrange(10)])
print dst_tmp
print '***'
@ -550,10 +527,8 @@ class Playout:
"""
logger = logging.getLogger()
self.export_source = export_source
self.cache_dir = CACHE_DIR + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule'
offset = 3600 * int(CACHE_FOR)
self.set_export_source(export_source)
offset = 3600 * int(config["cache_for"])
now = time.time()
for r, d, f in os.walk(self.cache_dir):
@ -588,128 +563,109 @@ class Playout:
def push(self, export_source):
logger = logging.getLogger()
self.export_source = export_source
self.cache_dir = CACHE_DIR + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule'
self.set_export_source(export_source)
self.push_ahead = 15
#try:
# dummy = self.schedule
# logger.debug('schedule already loaded')
#except Exception, e:
# self.schedule = self.push_init(self.export_source)
self.schedule = self.load_schedule()
playedItems = self.load_schedule_tracker()
try:
dummy = self.schedule
logger.debug('schedule already loaded')
except Exception, e:
self.schedule = self.push_init(self.export_source)
self.schedule = self.push_init(self.export_source)
"""
I'm quite sure that this could be achieved in a much more elegant way in python...
"""
tcomming = time.localtime(time.time() + self.push_ahead)
tnow = time.localtime(time.time())
str_tnow = "%04d-%02d-%02d-%02d-%02d" % (tnow[0], tnow[1], tnow[2], tnow[3], tnow[4])
str_tnow_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tnow[0], tnow[1], tnow[2], tnow[3], tnow[4], tnow[5])
str_tnow_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tnow[0], tnow[1], tnow[2], tnow[3], tnow[4], tnow[5])
str_tcomming = "%04d-%02d-%02d-%02d-%02d" % (tcomming[0], tcomming[1], tcomming[2], tcomming[3], tcomming[4])
str_tcomming_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tcomming[0], tcomming[1], tcomming[2], tcomming[3], tcomming[4], tcomming[5])
#print '--'
#print str_tnow_s + ' now'
#print str_tcomming_s + ' comming'
playnow = None
if self.schedule == None:
print 'unable to loop schedule - maybe write in progress'
print 'will try in next loop'
logger.warn('Unable to loop schedule - maybe write in progress?')
logger.warn('Will try again in next loop.')
else:
for pkey in self.schedule:
for pkey in self.schedule:
if pkey[0:16] == str_tcomming:
logger.debug('Preparing to push playlist scheduled at: %s', pkey)
playlist = self.schedule[pkey]
if int(playlist['played']) != 1:
#print '!!!!!!!!!!!!!!!!!!!'
#print 'MATCH'
"""
ok we have a match, replace the current playlist and
force liquidsoap to refresh
Add a 'played' state to the list in schedule, so it is not called again
in the next push loop
"""
playedFlag = (pkey in playedItems) and playedItems[pkey].get("played", 0)
logger.debug("PLAYED FLAG: " + str(playedFlag))
if not playedFlag:
# We have a match, replace the current playlist and
# force liquidsoap to refresh.
ptype = playlist['subtype']
try:
user_id = playlist['user_id']
playlist_id = playlist['id']
transmission_id = playlist['schedule_id']
except Exception, e:
playlist_id = 0
user_id = 0
transmission_id = 0
print e
#print 'Playlist id:',
if (self.push_liquidsoap(pkey, ptype, user_id, playlist_id, transmission_id, self.push_ahead) == 1):
if (self.push_liquidsoap(pkey, self.schedule, ptype) == 1):
logger.debug("Pushed to liquidsoap, updating 'played' status.")
self.schedule[pkey]['played'] = 1
"""
Call api to update schedule states and
write changes back to cache file
"""
self.api_client.update_scheduled_item(int(playlist['schedule_id']), 1)
schedule_file = open(self.schedule_file, "w")
pickle.dump(self.schedule, schedule_file)
schedule_file.close()
logger.debug("Wrote schedule to disk")
#else:
# print 'Nothing to do...'
# Marked the current playlist as 'played' in the schedule tracker
# so it is not called again in the next push loop.
# Write changes back to tracker file.
playedItems[pkey] = playlist
playedItems[pkey]['played'] = 1
schedule_tracker = open(self.schedule_tracker_file, "w")
pickle.dump(playedItems, schedule_tracker)
schedule_tracker.close()
logger.debug("Wrote schedule to disk: "+str(playedItems))
# Call API to update schedule states
logger.debug("Doing callback to server to update 'played' status.")
self.api_client.notify_scheduled_item_start_playing(pkey, self.schedule)
def push_init(self, export_source):
def load_schedule(self):
logger = logging.getLogger()
schedule = None
self.export_source = export_source
self.cache_dir = CACHE_DIR + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule'
# load the schedule from cache
logger.debug('loading schedule from cache...')
try:
schedule_file = open(self.schedule_file, "r")
schedule = pickle.load(schedule_file)
schedule_file.close()
except Exception, e:
logger.error('%s', e)
schedule = None
# create the file if it doesnt exist
if (not os.path.exists(self.schedule_file)):
logger.debug('creating file ' + self.schedule_file)
open(self.schedule_file, 'w').close()
else:
# load the schedule from cache
logger.debug('loading schedule file '+self.schedule_file)
try:
schedule_file = open(self.schedule_file, "r")
schedule = pickle.load(schedule_file)
schedule_file.close()
except Exception, e:
logger.error('%s', e)
return schedule
def push_liquidsoap(self, pkey, ptype, user_id, playlist_id, transmission_id, push_ahead):
def load_schedule_tracker(self):
logger = logging.getLogger()
playedItems = dict()
# create the file if it doesnt exist
if (not os.path.exists(self.schedule_tracker_file)):
logger.debug('creating file ' + self.schedule_tracker_file)
schedule_tracker = open(self.schedule_tracker_file, 'w')
pickle.dump(playedItems, schedule_tracker)
schedule_tracker.close()
else:
try:
logger.debug('loading schedule tracker file '+ self.schedule_tracker_file)
schedule_tracker = open(self.schedule_tracker_file, "r")
playedItems = pickle.load(schedule_tracker)
schedule_tracker.close()
except Exception, e:
logger.error('Unable to load schedule tracker file: %s', e)
return playedItems
#self.export_source = export_source
self.push_ahead = push_ahead
self.cache_dir = CACHE_DIR + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule'
def push_liquidsoap(self, pkey, schedule, ptype):
logger = logging.getLogger()
src = self.cache_dir + str(pkey) + '/list.lsp'
logger.debug(src)
try:
if True == os.access(src, os.R_OK):
logger.debug('OK - Can read playlist file')
@ -724,8 +680,7 @@ class Playout:
if (int(ptype) == 6):
tn.write("live_in.start")
tn.write("\n")
if (int(ptype) < 5):
for line in pl_file.readlines():
logger.debug(line.strip())
@ -741,19 +696,11 @@ class Playout:
logger.debug('sending "flip"')
tn = telnetlib.Telnet(LS_HOST, 1234)
"""
Pass some extra information to liquidsoap
"""
logger.debug('user_id: %s', user_id)
logger.debug('playlist_id: %s', playlist_id)
logger.debug('transmission_id: %s', transmission_id)
logger.debug('ptype: %s', ptype)
tn.write("vars.user_id %s\n" % user_id)
tn.write("vars.playlist_id %s\n" % playlist_id)
tn.write("vars.transmission_id %s\n" % transmission_id)
tn.write("vars.playlist_type %s\n" % ptype)
# Get any extra information for liquidsoap (which will be sent back to us)
liquidsoap_data = self.api_client.get_liquidsoap_data(pkey, schedule)
logger.debug("Sending additional data to liquidsoap: "+liquidsoap_data)
tn.write("vars.pypo_data "+liquidsoap_data+"\n")
# if(int(ptype) < 5):
# tn.write(self.export_source + '.flip')
# tn.write("\n")
@ -761,7 +708,7 @@ class Playout:
tn.write(self.export_source + '.flip')
tn.write("\n")
if(int(ptype) == 6):
if (int(ptype) == 6):
tn.write("live.active 1")
tn.write("\n")
else:
@ -772,7 +719,7 @@ class Playout:
tn.write("exit\n")
logger.debug(tn.read_all())
tn.read_all()
status = 1
except Exception, e:
logger.error('%s', e)
@ -857,38 +804,38 @@ class Playout:
"""
Updates the jingles. Give comma separated list of jingle tracks.
NOTE: commented out because it needs to be converted to use the API client. - Paul
"""
def update_jingles(self, options):
print 'jingles'
jingle_list = string.split(options, ',')
print jingle_list
for media_id in jingle_list:
# api path maybe should not be hard-coded
src = API_BASE + 'api/pypo/get_media/' + str(media_id)
print src
# include the hourly jungles for the moment
dst = "%s%s/%s.mp3" % (self.file_dir, 'jingles/hourly', str(media_id))
print dst
try:
print '** urllib auth with: ',
print self.api_auth
opener = urllib.URLopener()
opener.retrieve (src, dst, False, self.api_auth)
logger.info("downloaded %s to %s", src, dst)
except Exception, e:
print e
logger.error("%s", e)
#def update_jingles(self, options):
# print 'jingles'
#
# jingle_list = string.split(options, ',')
# print jingle_list
# for media_id in jingle_list:
# # api path maybe should not be hard-coded
# src = API_BASE + 'api/pypo/get_media/' + str(media_id)
# print src
# # include the hourly jungles for the moment
# dst = "%s%s/%s.mp3" % (config["file_dir"], 'jingles/hourly', str(media_id))
# print dst
#
# try:
# print '** urllib auth with: ',
# print self.api_auth
# opener = urllib.URLopener()
# opener.retrieve (src, dst, False, self.api_auth)
# logger.info("downloaded %s to %s", src, dst)
# except Exception, e:
# print e
# logger.error("%s", e)
def check_schedule(self, export_source):
logger = logging.getLogger()
self.export_source = export_source
self.cache_dir = CACHE_DIR + self.export_source + '/'
self.schedule_file = self.cache_dir + 'schedule'
self.set_export_source(export_source)
try:
schedule_file = open(self.schedule_file, "r")
schedule = pickle.load(schedule_file)
@ -898,11 +845,8 @@ class Playout:
logger.error("%s", e)
schedule = None
#for pkey in schedule:
for pkey in sorted(schedule.iterkeys()):
playlist = schedule[pkey]
print '*****************************************'
print '\033[0;32m%s %s\033[m' % ('scheduled at:', str(pkey))
print 'cached at : ' + self.cache_dir + str(pkey)
@ -911,7 +855,6 @@ class Playout:
print 'schedule id: ' + str(playlist['schedule_id'])
print 'duration: ' + str(playlist['duration'])
print 'source id: ' + str(playlist['x_ident'])
print '-----------------------------------------'
for media in playlist['medias']:
@ -921,7 +864,6 @@ class Playout:
if __name__ == '__main__':
print
print '###########################################'
print '# *** pypo *** #'
@ -997,11 +939,11 @@ while run == True:
time.sleep(PUSH_INTERVAL)
while options.jingles:
try: po.update_jingles(options.jingles)
except Exception, e:
print e
sys.exit()
#while options.jingles:
# try: po.update_jingles(options.jingles)
# except Exception, e:
# print e
# sys.exit()
while options.check:
@ -1011,7 +953,7 @@ while run == True:
sys.exit()
while options.cleanup:
try: po.cleanup()
try: po.cleanup('scheduler')
except Exception, e:
print e
sys.exit()

View file

@ -1,21 +1,18 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
"""
Python part of radio playout (pypo)
This function acts as a gateway between liquidsoap and the obp-api.
Mainliy used to tell the plattform what pypo/LS does.
Mainliy used to tell the platform what pypo/LS does.
Main case:
- whenever Liquidsoap starts playing a new track, its on_metadata callback calls
a function in liquidsoap (notify(m)) which then calls the python script here
with the currently starting filename as parameter
- this python script takes this parameter, tries to extract the actual
media id from it, and then calls back to obp via api to tell about
media id from it, and then calls back to API to tell it about it.
"""
@ -171,7 +168,6 @@ class Notify:
if __name__ == '__main__':
print
print '#########################################'
print '# *** pypo *** #'

View file

@ -1,21 +1,18 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
"""
Python part of radio playout (pypo)
This function acts as a gateway between liquidsoap and the obp-api.
Mainliy used to tell the plattform what pypo/LS does.
This function acts as a gateway between liquidsoap and the server API.
Mainly used to tell the platform what pypo/liquidsoap does.
Main case:
- whenever LS starts playing a new track, its on_metadata callback calls
a function in ls (notify(m)) which then calls the pythin script here
a function in ls (notify(m)) which then calls the python script here
with the currently starting filename as parameter
- this python script takes this parameter, tries to extract the actual
media id from it, and then calls back to obp via api to tell about
media id from it, and then calls back to the API to tell about it about it.
"""
@ -52,14 +49,14 @@ usage = "%prog [options]" + " - notification gateway"
parser = OptionParser(usage=usage)
# Options
#parser.add_option("-p", "--playing", help="Tell daddy what is playing right now", dest="playing", default=False, metavar=False)
parser.add_option("-p", "--playing", help="Tell daddy what is playing right now", default=False, action="store_true", dest="playing")
parser.add_option("-t", "--playlist-type", help="Tell daddy what is playing right now", metavar="playlist_type")
parser.add_option("-M", "--media-id", help="Tell daddy what is playing right now", metavar="media_id")
parser.add_option("-U", "--user-id", help="Tell daddy what is playing right now", metavar="user_id")
parser.add_option("-P", "--playlist-id", help="Tell daddy what is playing right now", metavar="playlist_id")
parser.add_option("-T", "--transmission-id", help="Tell daddy what is playing right now", metavar="transmission_id")
parser.add_option("-E", "--export-source", help="Tell daddy what is playing right now", metavar="export_source")
parser.add_option("-d", "--data", help="Pass JSON data from liquidsoap into this script.", metavar="data")
#parser.add_option("-p", "--playing", help="Tell server what is playing right now.", default=False, action="store_true", dest="playing")
#parser.add_option("-t", "--playlist-type", help="", metavar="playlist_type")
parser.add_option("-m", "--media-id", help="ID of the file that is currently playing.", metavar="media_id")
#parser.add_option("-U", "--user-id", help="", metavar="user_id")
#parser.add_option("-P", "--playlist-id", help="", metavar="playlist_id")
#parser.add_option("-T", "--transmission-id", help="", metavar="transmission_id")
#parser.add_option("-E", "--export-source", help="", metavar="export_source")
# parse options
(options, args) = parser.parse_args()
@ -70,10 +67,6 @@ logging.config.fileConfig("logging.cfg")
# loading config file
try:
config = ConfigObj('config.cfg')
TMP_DIR = config['tmp_dir']
BASE_URL = config['base_url']
API_BASE = BASE_URL + 'mod/medialibrary/'
API_KEY = config['api_key']
except Exception, e:
print 'error: ', e
@ -85,144 +78,156 @@ class Global:
print
def selfcheck(self):
self.api_auth = urllib.urlencode({'api_key': API_KEY})
self.api_client = api_client.api_client_factory(config)
self.api_client.check_version()
pass
#self.api_client = api_client.api_client_factory(config)
#self.api_client.check_version()
class Notify:
def __init__(self):
self.tmp_dir = TMP_DIR
self.api_auth = urllib.urlencode({'api_key': API_KEY})
self.api_client = api_client.api_client_factory(config)
self.dls_client = DlsClient('127.0.0.128', 50008, 'myusername', 'mypass')
#self.dls_client = DlsClient('127.0.0.128', 50008, 'myusername', 'mypass')
def start_playing(self, options):
logger = logging.getLogger("start_playing")
tnow = time.localtime(time.time())
def notify_media_start_playing(self, data, media_id):
logger = logging.getLogger()
#tnow = time.localtime(time.time())
#print options
print '#################################################'
print '# calling obp to tell about what\'s playing #'
print '#################################################'
if int(options.playlist_type) < 5:
print 'seems to be a playlist'
try:
media_id = int(options.media_id)
except Exception, e:
media_id = 0
response = self.api_client.update_start_playing(options.playlist_type, options.export_source, media_id, options.playlist_id, options.transmission_id)
print response
if int(options.playlist_type) == 6:
print 'seems to be a couchcast'
try:
media_id = int(options.media_id)
except Exception, e:
media_id = 0
response = self.api_client.update_start_playing(options.playlist_type, options.export_source, media_id, options.playlist_id, options.transmission_id)
print response
sys.exit()
logger.debug('#################################################')
logger.debug('# Calling server to update about what\'s playing #')
logger.debug('#################################################')
logger.debug('data = '+ str(data))
#print 'options.data = '+ options.data
#data = json.read(options.data)
response = self.api_client.notify_media_item_start_playing(data, media_id)
logger.debug("Response: "+str(response))
#def start_playing(self, options):
# logger = logging.getLogger("start_playing")
# tnow = time.localtime(time.time())
#
# #print options
#
# logger.debug('#################################################')
# logger.debug('# Calling server to update about what\'s playing #')
# logger.debug('#################################################')
#
# if int(options.playlist_type) < 5:
# logger.debug('seems to be a playlist')
#
# try:
# media_id = int(options.media_id)
# except Exception, e:
# media_id = 0
#
# response = self.api_client.update_start_playing(options.playlist_type, options.export_source, media_id, options.playlist_id, options.transmission_id)
#
# logger.debug(response)
#
# if int(options.playlist_type) == 6:
# logger.debug('seems to be a couchcast')
#
# try:
# media_id = int(options.media_id)
# except Exception, e:
# media_id = 0
#
# response = self.api_client.update_start_playing(options.playlist_type, options.export_source, media_id, options.playlist_id, options.transmission_id)
#
# logger.debug(response)
#
# sys.exit()
def start_playing_legacy(self, options):
logger = logging.getLogger("start_playing")
tnow = time.localtime(time.time())
print '#################################################'
print '# calling obp to tell about what\'s playing #'
print '#################################################'
path = options
print
print path
print
if 'pl_id' in path:
print 'seems to be a playlist'
type = 'playlist'
id = path[5:]
elif 'text' in path:
print 'seems to be a playlist'
type = 'text'
id = path[4:]
print id
else:
print 'seems to be a single track (media)'
type = 'media'
try:
file = path.split("/")[-1:][0]
if file.find('_cue_') > 0:
id = file.split("_cue_")[0]
else:
id = file.split(".")[-2:][0]
except Exception, e:
#print e
id = False
try:
id = id
except Exception, e:
#print e
id = False
print
print type + " id: ",
print id
response = self.api_client.update_start_playing(type, id, self.export_source, path)
print 'DONE'
try:
txt = response['txt']
print '#######################################'
print txt
print '#######################################'
#self.dls_client.set_txt(txt)
except Exception, e:
print e
#def start_playing_legacy(self, options):
# logger = logging.getLogger("start_playing")
# tnow = time.localtime(time.time())
#
# print '#################################################'
# print '# Calling server to update about what\'s playing #'
# print '#################################################'
#
# path = options
#
# print
# print path
# print
#
# if 'pl_id' in path:
# print 'seems to be a playlist'
# type = 'playlist'
# id = path[5:]
#
# elif 'text' in path:
# print 'seems to be a playlist'
# type = 'text'
# id = path[4:]
# print id
#
# else:
# print 'seems to be a single track (media)'
# type = 'media'
# try:
# file = path.split("/")[-1:][0]
# if file.find('_cue_') > 0:
# id = file.split("_cue_")[0]
# else:
# id = file.split(".")[-2:][0]
#
# except Exception, e:
# #print e
# id = False
#
# try:
# id = id
# except Exception, e:
# #print e
# id = False
#
# print
# print type + " id: ",
# print id
#
#
# response = self.api_client.update_start_playing(type, id, self.export_source, path)
#
# print 'DONE'
#
# try:
# txt = response['txt']
# print '#######################################'
# print txt
# print '#######################################'
# #self.dls_client.set_txt(txt)
#
# except Exception, e:
# print e
if __name__ == '__main__':
print
print '#########################################'
print '# *** pypo *** #'
print '# pypo notification gateway #'
print '#########################################'
print
# initialize
g = Global()
g.selfcheck()
n = Notify()
run = True
while run == True:
logger = logging.getLogger("pypo notify")
if options.playing:
try: n.start_playing(options)
except Exception, e:
print e
sys.exit()
sys.exit()
logger = logging.getLogger()
#if options.playing:
# try: n.start_playing(options)
# except Exception, e:
# print e
# sys.exit()
if not options.data:
print "NOTICE: 'data' command-line argument not given."
sys.exit()
if not options.media_id:
print "NOTICE: 'media_id' command-line argument not given."
sys.exit()
try:
g.selfcheck()
n = Notify()
n.notify_media_start_playing(options.data, options.media_id)
except Exception, e:
print e

View file

@ -1,8 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
"""
cue script that gets called by liquidsoap if a file in the playlist

View file

@ -6,7 +6,11 @@ playlist_id = ref '0'
user_id = ref '0'
transmission_id = ref '0'
playlist_type = ref '0'
pypo_data = ref '0'
def set_pypo_data(s)
pypo_data := s
end
def set_user_id(s)
user_id := s
@ -29,4 +33,5 @@ end
server.register(namespace="vars", "user_id", fun (s) -> begin set_user_id(s) "Done!" end)
server.register(namespace="vars", "playlist_id", fun (s) -> begin set_playlist_id(s) "Done!" end)
server.register(namespace="vars", "transmission_id", fun (s) -> begin set_transmission_id(s) "Done!" end)
server.register(namespace="vars", "playlist_type", fun (s) -> begin set_playlist_type(s) "Done!" end)
server.register(namespace="vars", "playlist_type", fun (s) -> begin set_playlist_type(s) "Done!" end)
server.register(namespace="vars", "pypo_data", fun (s) -> begin set_pypo_data(s) "Done!" end)

View file

@ -4,10 +4,10 @@
def notify(m)
print('user_id: #{!user_id}')
print('playlist_id: #{!playlist_id}')
print('transmission_id: #{!transmission_id}')
print('playlist_type: #{!playlist_type}')
# print('user_id: #{!user_id}')
# print('playlist_id: #{!playlist_id}')
# print('transmission_id: #{!transmission_id}')
# print('playlist_type: #{!playlist_type}')
if !playlist_type=='5' then
print('livesession')
@ -20,8 +20,9 @@ def notify(m)
end
if !playlist_type=='0' or !playlist_type=='1' or !playlist_type=='2' or !playlist_type=='3' or !playlist_type=='4' then
print('playlist')
system("./notify.sh --playing --playlist-type=#{!playlist_type} --media-id=#{m['media_id']} --export-source=#{m['export_source']}")
print('include_notify.liq: notify on playlist')
#system("./notify.sh --playing --playlist-type=#{!playlist_type} --media-id=#{m['media_id']} --export-source=#{m['export_source']}")
system("./notify.sh --data='#{!pypo_data}' --media-id=#{m['media_id']}")
end
end

View file

@ -2,9 +2,6 @@
# liquidsoap config file #
###########################################
# author Jonas Ohrstrom <jonas@digris.ch>
# this file is specific to the obp
# installation. eg it assumes that there are
# two instances of LS running

View file

@ -1,4 +1,4 @@
# author Jonas Ohrstrom <jonas@digris.ch>
# Register the cut protocol
def cue_protocol(arg,delay)
# The extraction program

View file

@ -1,8 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author Jonas Ohrstrom <jonas@digris.ch>
import sys
import shutil
import random

42
CREDITS
View file

@ -1,13 +1,31 @@
=======
CREDITS
=======
The original Campcaster (LiveSupport) concept was drafted by Micz Flor. It was
fully developed by Robert Klajn, Douglas Arellanes, Ákos Maróy, and Sava Tatić.
The user interface has been designed by Charles Truett, based on the initial work
done by a team of his then-fellow Parsons School of Design students Turi McKinley,
Catalin Lazia and Sangita Shah. The team was led by then-head of the school's
Department of Digital Design Colleen Macklin, assisted by Kunal Jain.
Version 1.6.0
-------------
This version marks a major change to the project, completely replacing the
custom audio player with liquidsoap, dropping the custom desktop GUI, and
completely rewriting the web interface.
Paul Baranowski (paul.baranowski@sourcefabric.org)
Role: Project Lead / Software Developer
Highlights:
- Integration and development of liquidsoap scheduler
- Separation of playlists from the scheduler
Naomi Aro (naomi.aro@sourcefabric.org)
Role: Software Developer
Highlights:
- New User Interface
- Conversion to Propel DB backend
Daniel James
Role: Documentor & QA
Version 1.4.0 - "Monrovia"
--------------------------
The great deal of the work on Campcaster 1.4 "Monrovia" was commissioned by the
Open Society Initiative for West Africa (www.osiwa.org), and by West Africa
Democracy Radio (www.wadr.org). We would like to thank Ben Akoh at OSIWA and
@ -18,10 +36,6 @@ generated radio station based in Basel, Switzerland powered by Campcaster. We ar
very grateful for their contributions, and specifically to Thomas Gilgen, Dirk Claes,
Rigzen Latshang and Fabiano Sidler.
Version 1.4.0 - "Monrovia"
--------------------------
Douglas Arellanes (douglas.arellanes@mdlf.org)
- Tester and user feedback
@ -106,8 +120,14 @@ Sava Tatić
Version 1.0
-----------
In alphabetical order:
The original Campcaster (LiveSupport) concept was drafted by Micz Flor. It was
fully developed by Robert Klajn, Douglas Arellanes, Ákos Maróy, and Sava Tatić.
The user interface has been designed by Charles Truett, based on the initial work
done by a team of his then-fellow Parsons School of Design students Turi McKinley,
Catalin Lazia and Sangita Shah. The team was led by then-head of the school's
Department of Digital Design Colleen Macklin, assisted by Kunal Jain.
In alphabetical order:
Douglas Arellanes
Michael Aschauer <mash@re-p.org>
Micz Flor (micz.flor@web.de)

675
LICENSE Normal file
View file

@ -0,0 +1,675 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

27
LICENSE_3RD_PARTY Normal file
View file

@ -0,0 +1,27 @@
This application uses the following 3rd Party software:
* Zend Framework (New BSD license, compatible with GPL)
* Liquidsoap (GPLv2, we only call this as an executable)
* PEAR (Ok to ship with GPLed code, see: http://pear.php.net/manual/en/faq.devs.php, see note [1])
* poc-streamer (mp3cut)
* PHP
[1] PEAR Note (from http://pear.php.net/manual/en/faq.devs.php):
"""
From time to time people raise concerns of using PEAR packages licensed under the PHP license in GPL'ed code. In a discussion about this topic, the creator of PHP, Rasmus Lerdorf, issued the following statement:
It all comes down to semantics of what linking means. The PHP license is pretty much identical to the Apache license and you could indeed make a case for not allowing any GPL'ed software to be "linked to" from Apache either.
See http://www.apache.org/licenses/LICENSE-1.1.
The PHP license was chosen to match the Apache license because Apache and PHP are tied so closely to each other.
This hair splitting over linking, derivation and aggregation has been going on since the beginning of time. My stance is that you can indeed ship PHP licensed PEAR components on the same cd or in the same tarball as GPL'ed code because I see it as an aggregate work. This changes if you take PEAR code, modify it and copy-paste it directly into your own work. Then it moves from aggregate to derived. But the intent of the PEAR components is to be used in aggregate form. The PHP license allows you to use it in derived form as well, of course, but then you should be choosing a license other than the GPL for the derived work.
The FSF has a FAQ on aggregation here: http://www.fsf.org/licensing/licenses/gpl-faq.html#MereAggregation
That text is heavily biased towards compiled software and they talk about executables and memory spaces which don't really apply in this case. If you don't consider using a PEAR component as aggregation then it logically follows that you also cannot have Apache call your code so you will have to stipulate that nobody can use your code from Apache. I think this is an extreme interpretation that pretty much nobody out there shares.
In short, I don't see an issue here. Move along.
"""

View file

@ -1,6 +1,5 @@
<?php
require_once('../conf.php');
require_once('DB.php');
require_once('../backend/StoredFile.php');
$api_key = $_GET['api_key'];
@ -13,13 +12,6 @@ if(!in_array($api_key, $CC_CONFIG["apiKey"]))
PEAR::setErrorHandling(PEAR_ERROR_RETURN);
$CC_DBC = DB::connect($CC_CONFIG['dsn'], TRUE);
if (PEAR::isError($CC_DBC)) {
echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n";
exit(1);
}
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
$filename = $_GET["file"];
$file_id = substr($filename, 0, strpos($filename, "."));
if (ctype_alnum($file_id) && strlen($file_id) == 32) {

View file

@ -0,0 +1,37 @@
<?php
require_once('../conf.php');
require_once('../backend/Schedule.php');
$api_key = $_GET['api_key'];
if(!in_array($api_key, $CC_CONFIG["apiKey"]))
{
header('HTTP/1.0 401 Unauthorized');
print 'You are not allowed to access this resource.';
exit;
}
PEAR::setErrorHandling(PEAR_ERROR_RETURN);
$schedule_group_id = $_GET["schedule_id"];
$media_id = $_GET["media_id"];
$f = StoredFile::RecallByGunid($media_id);
if (is_numeric($schedule_group_id)) {
$sg = new ScheduleGroup($schedule_group_id);
if ($sg->exists()) {
$result = $sg->notifyMediaItemStartPlay($f->getId());
if (!PEAR::isError($result)) {
echo json_encode(array("status"=>1, "message"=>""));
exit;
} else {
echo json_encode(array("status"=>0, "message"=>"DB Error:".$result->getMessage()));
exit;
}
} else {
echo json_encode(array("status"=>0, "message"=>"Schedule group does not exist: ".$schedule_group_id));
exit;
}
} else {
echo json_encode(array("status"=>0, "message" => "Incorrect or non-numeric arguments given."));
}
?>

View file

@ -0,0 +1,35 @@
<?php
require_once('../conf.php');
require_once('../backend/Schedule.php');
$api_key = $_GET['api_key'];
if (!in_array($api_key, $CC_CONFIG["apiKey"]))
{
header('HTTP/1.0 401 Unauthorized');
print 'You are not allowed to access this resource.';
exit;
}
PEAR::setErrorHandling(PEAR_ERROR_RETURN);
$schedule_group_id = $_GET["schedule_id"];
if (is_numeric($schedule_group_id)) {
$sg = new ScheduleGroup($schedule_group_id);
if ($sg->exists()) {
$result = $sg->notifyGroupStartPlay();
if (!PEAR::isError($result)) {
echo json_encode(array("status"=>1, "message"=>""));
exit;
} else {
echo json_encode(array("status"=>0, "message"=>"DB Error:".$result->getMessage()));
exit;
}
} else {
echo json_encode(array("status"=>0, "message"=>"Schedule group does not exist: ".$schedule_group_id));
exit;
}
} else {
echo json_encode(array("status"=>0, "message"=>"Incorrect or non-numeric arguments given."));
exit;
}
?>

View file

@ -1,6 +1,5 @@
<?php
require_once('../conf.php');
require_once('DB.php');
require_once('../backend/Schedule.php');
$api_key = $_GET['api_key'];
@ -13,12 +12,6 @@ if(!in_array($api_key, $CC_CONFIG["apiKey"]))
PEAR::setErrorHandling(PEAR_ERROR_RETURN);
$CC_DBC = DB::connect($CC_CONFIG['dsn'], TRUE);
if (PEAR::isError($CC_DBC)) {
echo "ERROR: ".$CC_DBC->getMessage()." ".$CC_DBC->getUserInfo()."\n";
exit(1);
}
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
$from = $_GET["from"];
$to = $_GET["to"];
echo Schedule::ExportRangeAsJson($from, $to);

View file

@ -10,6 +10,21 @@ class ScheduleGroup {
$this->groupId = $p_groupId;
}
/**
* Return true if the schedule group exists in the DB.
* @return boolean
*/
public function exists() {
global $CC_CONFIG, $CC_DBC;
$sql = "SELECT COUNT(*) FROM ".$CC_CONFIG['scheduleTable']
." WHERE group_id=".$this->groupId;
$result = $CC_DBC->GetOne($sql);
if (PEAR::isError($result)) {
return $result;
}
return $result != "0";
}
/**
* Convert a date to an ID by stripping out all characters
* and padding with zeros.
@ -204,6 +219,22 @@ class ScheduleGroup {
// $sql = "UPDATE ".$CC_CONFIG["scheduleTable"]. " SET id=, starts=,ends="
}
public function notifyGroupStartPlay() {
global $CC_CONFIG, $CC_DBC;
$sql = "UPDATE ".$CC_CONFIG['scheduleTable']
." SET schedule_group_played=TRUE"
." WHERE group_id=".$this->groupId;
return $CC_DBC->query($sql);
}
public function notifyMediaItemStartPlay($p_fileId) {
global $CC_CONFIG, $CC_DBC;
$sql = "UPDATE ".$CC_CONFIG['scheduleTable']
." SET media_item_played=TRUE"
." WHERE group_id=".$this->groupId
." AND file_id=".pg_escape_string($p_fileId);
return $CC_DBC->query($sql);
}
}
class Schedule {
@ -464,7 +495,7 @@ class Schedule {
$playlists[$pkey]['user_id'] = 0;
$playlists[$pkey]['id'] = $dx["playlist_id"];
$playlists[$pkey]['start'] = Schedule::CcTimeToPypoTime($dx["start"]);
$playlists[$pkey]['end'] = Schedule::CcTimeToPypoTime($dx["end"]);
$playlists[$pkey]['end'] = Schedule::CcTimeToPypoTime($dx["end"]);
}
}

View file

@ -244,6 +244,8 @@ CREATE TABLE "cc_schedule"
"fade_out" TIME default '00:00:00',
"cue_in" TIME default '00:00:00',
"cue_out" TIME default '00:00:00',
"schedule_group_played" BOOLEAN default 'f',
"media_item_played" BOOLEAN default 'f',
PRIMARY KEY ("id")
);

View file

@ -182,6 +182,8 @@
<column name="fade_out" phpName="FadeOut" type="TIME" required="false" defaultValue="00:00:00"/>
<column name="cue_in" phpName="CueIn" type="TIME" required="false" defaultValue="00:00:00"/>
<column name="cue_out" phpName="CueOut" type="TIME" required="false" defaultValue="00:00:00"/>
<column name="schedule_group_played" phpName="ScheduleGroupPlayed" type="BOOLEAN" required="false" defaultValue="0"/>
<column name="media_item_played" phpName="MediaItemPlayed" type="BOOLEAN" required="false" defaultValue="0"/>
</table>
<table name="cc_sess" phpName="CcSess">
<column name="sessid" phpName="Sessid" type="CHAR" size="32" primaryKey="true" required="true"/>

View file

@ -31,11 +31,26 @@ $pl = new Playlist();
$pl->create($playlistName);
// Add a media clip
$mediaFile = StoredFile::findByOriginalName("test10001.mp3");
$mediaFile = StoredFile::findByOriginalName("Manolo Camp - Morning Coffee.mp3");
if (is_null($mediaFile)) {
echo "Adding test audio clip to the database.\n";
$v = array("filepath" => __DIR__."/test10001.mp3");
$v = array("filepath" => __DIR__."/../../audio_samples/OpSound/Manolo Camp - Morning Coffee.mp3");
$mediaFile = StoredFile::Insert($v);
if (PEAR::isError($mediaFile)) {
var_dump($mediaFile);
exit();
}
}
$pl->addAudioClip($mediaFile->getId());
$mediaFile = StoredFile::findByOriginalName("Peter Rudenko - Opening.mp3");
if (is_null($mediaFile)) {
echo "Adding test audio clip to the database.\n";
$v = array("filepath" => __DIR__."/../../audio_samples/OpSound/Peter Rudenko - Opening.mp3");
$mediaFile = StoredFile::Insert($v);
if (PEAR::isError($mediaFile)) {
var_dump($mediaFile);
exit();
}
}
$pl->addAudioClip($mediaFile->getId());
echo "done.\n";