CC-2097: Show-recorder: Use RabbitMQ, api_client, and the structure of pypofetch
using api client now
This commit is contained in:
parent
9546d9670e
commit
c727c338af
10 changed files with 334 additions and 274 deletions
|
@ -6,8 +6,10 @@ class ApiController extends Zend_Controller_Action
|
|||
public function init()
|
||||
{
|
||||
/* Initialize action controller here */
|
||||
$ajaxContext = $this->_helper->getHelper('AjaxContext');
|
||||
$ajaxContext->addActionContext('version', 'json')
|
||||
$context = $this->_helper->getHelper('contextSwitch');
|
||||
$context->addActionContext('version', 'json')
|
||||
->addActionContext('recorded-shows', 'json')
|
||||
->addActionContext('upload-recorded', 'json')
|
||||
->initContext();
|
||||
}
|
||||
|
||||
|
@ -150,12 +152,6 @@ class ApiController extends Zend_Controller_Action
|
|||
}
|
||||
}
|
||||
|
||||
public function recordedShowsAction()
|
||||
{
|
||||
$today_timestamp = date("Y-m-d H:i:s");
|
||||
$this->view->shows = Show::getShows($today_timestamp, null, $excludeInstance=NULL, $onlyRecord=TRUE);
|
||||
}
|
||||
|
||||
public function notifyMediaItemStartPlayAction()
|
||||
{
|
||||
global $CC_CONFIG;
|
||||
|
@ -222,5 +218,54 @@ class ApiController extends Zend_Controller_Action
|
|||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
public function recordedShowsAction()
|
||||
{
|
||||
global $CC_CONFIG;
|
||||
|
||||
$api_key = $this->_getParam('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;
|
||||
}
|
||||
|
||||
$today_timestamp = date("Y-m-d H:i:s");
|
||||
$this->view->shows = Show::getShows($today_timestamp, null, $excludeInstance=NULL, $onlyRecord=TRUE);
|
||||
}
|
||||
|
||||
public function uploadRecordedAction()
|
||||
{
|
||||
global $CC_CONFIG;
|
||||
|
||||
// disable the view and the layout
|
||||
$this->view->layout()->disableLayout();
|
||||
$this->_helper->viewRenderer->setNoRender(true);
|
||||
|
||||
$api_key = $this->_getParam('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;
|
||||
}
|
||||
|
||||
$upload_dir = ini_get("upload_tmp_dir");
|
||||
$file = StoredFile::uploadFile($upload_dir);
|
||||
|
||||
if(Application_Model_Preference::GetDoSoundCloudUpload())
|
||||
{
|
||||
$soundcloud = new ATSoundcloud();
|
||||
$soundcloud->uploadTrack($file->getRealFilePath(), $file->getName());
|
||||
}
|
||||
|
||||
$show_instance = $this->_getParam('show_instance');
|
||||
|
||||
$show = new ShowInstance($show_instance);
|
||||
$show->setRecordedFile($file->getId());
|
||||
|
||||
$this->view->id = $file->getId();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -11,143 +11,6 @@ class PluploadController extends Zend_Controller_Action
|
|||
->initContext();
|
||||
}
|
||||
|
||||
public function upload($targetDir)
|
||||
{
|
||||
// HTTP headers for no cache etc
|
||||
header('Content-type: text/plain; charset=UTF-8');
|
||||
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
|
||||
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
|
||||
header("Cache-Control: no-store, no-cache, must-revalidate");
|
||||
header("Cache-Control: post-check=0, pre-check=0", false);
|
||||
header("Pragma: no-cache");
|
||||
|
||||
// Settings
|
||||
//$targetDir = ini_get("upload_tmp_dir"); //. DIRECTORY_SEPARATOR . "plupload";
|
||||
$cleanupTargetDir = false; // Remove old files
|
||||
$maxFileAge = 60 * 60; // Temp file age in seconds
|
||||
|
||||
// 5 minutes execution time
|
||||
@set_time_limit(5 * 60);
|
||||
// usleep(5000);
|
||||
|
||||
// Get parameters
|
||||
$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
|
||||
$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
|
||||
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
|
||||
|
||||
// Clean the fileName for security reasons
|
||||
//$fileName = preg_replace('/[^\w\._]+/', '', $fileName);
|
||||
|
||||
// Create target dir
|
||||
if (!file_exists($targetDir))
|
||||
@mkdir($targetDir);
|
||||
|
||||
// Remove old temp files
|
||||
if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
|
||||
while (($file = readdir($dir)) !== false) {
|
||||
$filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
|
||||
|
||||
// Remove temp files if they are older than the max age
|
||||
if (preg_match('/\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
|
||||
@unlink($filePath);
|
||||
}
|
||||
|
||||
closedir($dir);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
|
||||
|
||||
// Look for the content type header
|
||||
if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
|
||||
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
|
||||
|
||||
if (isset($_SERVER["CONTENT_TYPE"]))
|
||||
$contentType = $_SERVER["CONTENT_TYPE"];
|
||||
|
||||
if (strpos($contentType, "multipart") !== false) {
|
||||
if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
|
||||
// Open temp file
|
||||
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
|
||||
if ($out) {
|
||||
// Read binary input stream and append it to temp file
|
||||
$in = fopen($_FILES['file']['tmp_name'], "rb");
|
||||
|
||||
if ($in) {
|
||||
while ($buff = fread($in, 4096))
|
||||
fwrite($out, $buff);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
|
||||
|
||||
fclose($out);
|
||||
unlink($_FILES['file']['tmp_name']);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
|
||||
} else {
|
||||
// Open temp file
|
||||
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
|
||||
if ($out) {
|
||||
// Read binary input stream and append it to temp file
|
||||
$in = fopen("php://input", "rb");
|
||||
|
||||
if ($in) {
|
||||
while ($buff = fread($in, 4096))
|
||||
fwrite($out, $buff);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
|
||||
|
||||
fclose($out);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
|
||||
}
|
||||
|
||||
$audio_file = $targetDir . DIRECTORY_SEPARATOR . $fileName;
|
||||
|
||||
$md5 = md5_file($audio_file);
|
||||
$duplicate = StoredFile::RecallByMd5($md5);
|
||||
if ($duplicate) {
|
||||
if (PEAR::isError($duplicate)) {
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' . $duplicate->getMessage() .'}}');
|
||||
}
|
||||
else {
|
||||
$duplicateName = $duplicate->getMetadataValue(UI_MDATA_KEY_TITLE);
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "An identical audioclip named ' . $duplicateName . ' already exists in the storage server."}}');
|
||||
}
|
||||
}
|
||||
|
||||
$metadata = Metadata::LoadFromFile($audio_file);
|
||||
|
||||
if (PEAR::isError($metadata)) {
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $metadata->getMessage() + '}}');
|
||||
}
|
||||
|
||||
// #2196 no id tag -> use the original filename
|
||||
if (basename($audio_file) == $metadata[UI_MDATA_KEY_TITLE]) {
|
||||
$metadata[UI_MDATA_KEY_TITLE] = basename($audio_file);
|
||||
$metadata[UI_MDATA_KEY_FILENAME] = basename($audio_file);
|
||||
}
|
||||
|
||||
// setMetadataBatch doesnt like these values
|
||||
unset($metadata['audio']);
|
||||
unset($metadata['playtime_seconds']);
|
||||
|
||||
$values = array(
|
||||
"filename" => basename($audio_file),
|
||||
"filepath" => $audio_file,
|
||||
"filetype" => "audioclip",
|
||||
"mime" => $metadata[UI_MDATA_KEY_FORMAT],
|
||||
"md5" => $md5
|
||||
);
|
||||
$storedFile = StoredFile::Insert($values);
|
||||
|
||||
if (PEAR::isError($storedFile)) {
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}');
|
||||
}
|
||||
|
||||
$storedFile->setMetadataBatch($metadata);
|
||||
|
||||
return $storedFile;
|
||||
}
|
||||
|
||||
public function indexAction()
|
||||
{
|
||||
|
@ -157,26 +20,7 @@ class PluploadController extends Zend_Controller_Action
|
|||
public function uploadAction()
|
||||
{
|
||||
$upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
|
||||
$file = $this->upload($upload_dir);
|
||||
|
||||
die('{"jsonrpc" : "2.0", "id" : '.$file->getId().' }');
|
||||
}
|
||||
|
||||
public function uploadRecordedAction()
|
||||
{
|
||||
$upload_dir = ini_get("upload_tmp_dir");
|
||||
$file = $this->upload($upload_dir);
|
||||
|
||||
if(Application_Model_Preference::GetDoSoundCloudUpload())
|
||||
{
|
||||
$soundcloud = new ATSoundcloud();
|
||||
$soundcloud->uploadTrack($file->getRealFilePath(), $file->getName());
|
||||
}
|
||||
|
||||
$show_instance = $this->_getParam('show_instance');
|
||||
|
||||
$show = new ShowInstance($show_instance);
|
||||
$show->setRecordedFile($file->getId());
|
||||
$file = StoredFile::uploadFile($upload_dir);
|
||||
|
||||
die('{"jsonrpc" : "2.0", "id" : '.$file->getId().' }');
|
||||
}
|
||||
|
|
|
@ -1,28 +0,0 @@
|
|||
<?php
|
||||
|
||||
class RecorderController extends Zend_Controller_Action
|
||||
{
|
||||
|
||||
public function init()
|
||||
{
|
||||
$ajaxContext = $this->_helper->getHelper('contextSwitch');
|
||||
$ajaxContext->addActionContext('get-show-schedule', 'json')
|
||||
->addActionContext('get-uploaded-file', 'json')
|
||||
->initContext();
|
||||
}
|
||||
|
||||
public function indexAction()
|
||||
{
|
||||
// action body
|
||||
}
|
||||
|
||||
public function getShowScheduleAction()
|
||||
{
|
||||
$today_timestamp = date("Y-m-d H:i:s");
|
||||
$this->view->shows = Show::getShows($today_timestamp, null, $excludeInstance=NULL, $onlyRecord=TRUE);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -110,7 +110,7 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
|
|||
{
|
||||
$controller = strtolower($request->getControllerName());
|
||||
|
||||
if ($controller == 'api' || $controller == 'recorder' || $controller == 'plupload' && $request->getActionName() == 'upload-recorded'){
|
||||
if ($controller == 'api'){
|
||||
|
||||
$this->setRoleName("G");
|
||||
}
|
||||
|
|
|
@ -1647,5 +1647,143 @@ class StoredFile {
|
|||
return array("sEcho" => intval($data["sEcho"]), "iTotalDisplayRecords" => $totalDisplayRows, "iTotalRecords" => $totalRows, "aaData" => $results);
|
||||
}
|
||||
|
||||
public static function uploadFile($targetDir) {
|
||||
|
||||
// HTTP headers for no cache etc
|
||||
header('Content-type: text/plain; charset=UTF-8');
|
||||
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
|
||||
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
|
||||
header("Cache-Control: no-store, no-cache, must-revalidate");
|
||||
header("Cache-Control: post-check=0, pre-check=0", false);
|
||||
header("Pragma: no-cache");
|
||||
|
||||
// Settings
|
||||
//$targetDir = ini_get("upload_tmp_dir"); //. DIRECTORY_SEPARATOR . "plupload";
|
||||
$cleanupTargetDir = false; // Remove old files
|
||||
$maxFileAge = 60 * 60; // Temp file age in seconds
|
||||
|
||||
// 5 minutes execution time
|
||||
@set_time_limit(5 * 60);
|
||||
// usleep(5000);
|
||||
|
||||
// Get parameters
|
||||
$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
|
||||
$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
|
||||
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
|
||||
|
||||
// Clean the fileName for security reasons
|
||||
//$fileName = preg_replace('/[^\w\._]+/', '', $fileName);
|
||||
|
||||
// Create target dir
|
||||
if (!file_exists($targetDir))
|
||||
@mkdir($targetDir);
|
||||
|
||||
// Remove old temp files
|
||||
if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
|
||||
while (($file = readdir($dir)) !== false) {
|
||||
$filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
|
||||
|
||||
// Remove temp files if they are older than the max age
|
||||
if (preg_match('/\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
|
||||
@unlink($filePath);
|
||||
}
|
||||
|
||||
closedir($dir);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
|
||||
|
||||
// Look for the content type header
|
||||
if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
|
||||
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
|
||||
|
||||
if (isset($_SERVER["CONTENT_TYPE"]))
|
||||
$contentType = $_SERVER["CONTENT_TYPE"];
|
||||
|
||||
if (strpos($contentType, "multipart") !== false) {
|
||||
if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
|
||||
// Open temp file
|
||||
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
|
||||
if ($out) {
|
||||
// Read binary input stream and append it to temp file
|
||||
$in = fopen($_FILES['file']['tmp_name'], "rb");
|
||||
|
||||
if ($in) {
|
||||
while ($buff = fread($in, 4096))
|
||||
fwrite($out, $buff);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
|
||||
|
||||
fclose($out);
|
||||
unlink($_FILES['file']['tmp_name']);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
|
||||
} else {
|
||||
// Open temp file
|
||||
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
|
||||
if ($out) {
|
||||
// Read binary input stream and append it to temp file
|
||||
$in = fopen("php://input", "rb");
|
||||
|
||||
if ($in) {
|
||||
while ($buff = fread($in, 4096))
|
||||
fwrite($out, $buff);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
|
||||
|
||||
fclose($out);
|
||||
} else
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
|
||||
}
|
||||
|
||||
$audio_file = $targetDir . DIRECTORY_SEPARATOR . $fileName;
|
||||
|
||||
$md5 = md5_file($audio_file);
|
||||
$duplicate = StoredFile::RecallByMd5($md5);
|
||||
if ($duplicate) {
|
||||
if (PEAR::isError($duplicate)) {
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' . $duplicate->getMessage() .'}}');
|
||||
}
|
||||
else {
|
||||
$duplicateName = $duplicate->getMetadataValue(UI_MDATA_KEY_TITLE);
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "An identical audioclip named ' . $duplicateName . ' already exists in the storage server."}}');
|
||||
}
|
||||
}
|
||||
|
||||
$metadata = Metadata::LoadFromFile($audio_file);
|
||||
|
||||
if (PEAR::isError($metadata)) {
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $metadata->getMessage() + '}}');
|
||||
}
|
||||
|
||||
// #2196 no id tag -> use the original filename
|
||||
if (basename($audio_file) == $metadata[UI_MDATA_KEY_TITLE]) {
|
||||
$metadata[UI_MDATA_KEY_TITLE] = basename($audio_file);
|
||||
$metadata[UI_MDATA_KEY_FILENAME] = basename($audio_file);
|
||||
}
|
||||
|
||||
// setMetadataBatch doesnt like these values
|
||||
unset($metadata['audio']);
|
||||
unset($metadata['playtime_seconds']);
|
||||
|
||||
$values = array(
|
||||
"filename" => basename($audio_file),
|
||||
"filepath" => $audio_file,
|
||||
"filetype" => "audioclip",
|
||||
"mime" => $metadata[UI_MDATA_KEY_FORMAT],
|
||||
"md5" => $md5
|
||||
);
|
||||
$storedFile = StoredFile::Insert($values);
|
||||
|
||||
if (PEAR::isError($storedFile)) {
|
||||
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}');
|
||||
}
|
||||
|
||||
$storedFile->setMetadataBatch($metadata);
|
||||
|
||||
return $storedFile;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -13,6 +13,7 @@
|
|||
import sys
|
||||
import time
|
||||
import urllib
|
||||
import urllib2
|
||||
import logging
|
||||
import json
|
||||
import os
|
||||
|
@ -91,6 +92,12 @@ class ApiClientInterface:
|
|||
def get_liquidsoap_data(self, pkey, schedule):
|
||||
pass
|
||||
|
||||
def get_shows_to_record(self):
|
||||
pass
|
||||
|
||||
def upload_recorded_show(self):
|
||||
pass
|
||||
|
||||
# Put here whatever tests you want to run to make sure your API is working
|
||||
def test(self):
|
||||
pass
|
||||
|
@ -225,24 +232,6 @@ class AirTimeApiClient(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
|
||||
# for index in toRemove:
|
||||
# del schedule[index]
|
||||
#except Exception, e:
|
||||
#response["playlists"] = schedule
|
||||
|
||||
return status, response
|
||||
|
||||
|
||||
|
@ -317,6 +306,42 @@ class AirTimeApiClient(ApiClientInterface):
|
|||
data["schedule_id"] = 0
|
||||
return data
|
||||
|
||||
def get_shows_to_record(self):
|
||||
logger = logging.getLogger()
|
||||
response = ''
|
||||
try:
|
||||
url = self.config["base_url"] + self.config["api_base"] + self.config["show_schedule_url"]
|
||||
#logger.debug(url)
|
||||
url = url.replace("%%api_key%%", self.config["api_key"])
|
||||
logger.debug(url)
|
||||
response = urllib.urlopen(url)
|
||||
response = json.loads(response.read())
|
||||
logger.info("shows %s", response)
|
||||
|
||||
except Exception, e:
|
||||
logger.error("Exception: %s", e)
|
||||
|
||||
return response[u'shows']
|
||||
|
||||
def upload_recorded_show(self, data, headers):
|
||||
logger = logging.getLogger()
|
||||
response = ''
|
||||
try:
|
||||
url = self.config["base_url"] + self.config["api_base"] + self.config["upload_file_url"]
|
||||
#logger.debug(url)
|
||||
url = url.replace("%%api_key%%", self.config["api_key"])
|
||||
logger.debug(url)
|
||||
|
||||
request = urllib2.Request(url, data, headers)
|
||||
response = urllib2.urlopen(request).read().strip()
|
||||
|
||||
logger.info("uploaded show result %s", response)
|
||||
|
||||
except Exception, e:
|
||||
logger.error("Exception: %s", e)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
|
||||
################################################################################
|
||||
|
|
|
@ -1,10 +1,8 @@
|
|||
api_client = "airtime"
|
||||
|
||||
# Hostname
|
||||
base_url = 'http://localhost/'
|
||||
|
||||
show_schedule_url = 'Recorder/get-show-schedule/format/json'
|
||||
|
||||
upload_file_url = 'Plupload/upload-recorded/format/json'
|
||||
|
||||
# base path to store recordered shows at
|
||||
base_recorded_files = '/home/pypo/Music/'
|
||||
|
||||
|
@ -16,3 +14,9 @@ api_base = 'api/'
|
|||
|
||||
# URL to get the version number of the server API
|
||||
version_url = 'version/api_key/%%api_key%%'
|
||||
|
||||
# URL to get the schedule of shows set to record
|
||||
show_schedule_url = 'recorded-shows/format/json/api_key/%%api_key%%'
|
||||
|
||||
# URL to upload the recorded show's file to Airtime
|
||||
upload_file_url = 'upload-recorded/format/json/api_key/%%api_key%%'
|
||||
|
|
|
@ -4,9 +4,12 @@ export HOME="/home/pypo/"
|
|||
# Location of pypo_cli.py Python script
|
||||
recorder_path="/opt/recorder/bin/"
|
||||
recorder_script="testrecordscript.py"
|
||||
|
||||
api_client_path="/opt/pypo/"
|
||||
|
||||
echo "*** Daemontools: starting daemon"
|
||||
cd ${recorder_path}
|
||||
exec 2>&1
|
||||
# Note the -u when calling python! we need it to get unbuffered binary stdout and stderr
|
||||
exec sudo python -u ${recorder_path}${recorder_script} -f
|
||||
sudo PYTHONPATH=${api_client_path} -u ${recorder_user} python -u ${recorder_path}${recorder_script} -f
|
||||
# EOF
|
||||
|
|
22
python_apps/show-recorder/logging.cfg
Normal file
22
python_apps/show-recorder/logging.cfg
Normal file
|
@ -0,0 +1,22 @@
|
|||
[loggers]
|
||||
keys=root
|
||||
|
||||
[handlers]
|
||||
keys=consoleHandler
|
||||
|
||||
[formatters]
|
||||
keys=simpleFormatter
|
||||
|
||||
[logger_root]
|
||||
level=DEBUG
|
||||
handlers=consoleHandler
|
||||
|
||||
[handler_consoleHandler]
|
||||
class=StreamHandler
|
||||
level=DEBUG
|
||||
formatter=simpleFormatter
|
||||
args=(sys.stdout,)
|
||||
|
||||
[formatter_simpleFormatter]
|
||||
format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s
|
||||
datefmt=
|
|
@ -1,6 +1,7 @@
|
|||
#!/usr/local/bin/python
|
||||
import urllib
|
||||
import logging
|
||||
import logging.config
|
||||
import json
|
||||
import time
|
||||
import datetime
|
||||
|
@ -15,6 +16,15 @@ import urllib2
|
|||
from subprocess import call
|
||||
from threading import Thread
|
||||
|
||||
# For RabbitMQ
|
||||
from kombu.connection import BrokerConnection
|
||||
from kombu.messaging import Exchange, Queue, Consumer, Producer
|
||||
|
||||
from api_clients import api_client
|
||||
|
||||
# configure logging
|
||||
logging.config.fileConfig("logging.cfg")
|
||||
|
||||
# loading config file
|
||||
try:
|
||||
config = ConfigObj('config.cfg')
|
||||
|
@ -22,12 +32,19 @@ except Exception, e:
|
|||
print 'Error loading config file: ', e
|
||||
sys.exit()
|
||||
|
||||
shows_to_record = {}
|
||||
def getDateTimeObj(time):
|
||||
|
||||
class Recorder(Thread):
|
||||
timeinfo = time.split(" ")
|
||||
date = timeinfo[0].split("-")
|
||||
time = timeinfo[1].split(":")
|
||||
|
||||
return datetime.datetime(int(date[0]), int(date[1]), int(date[2]), int(time[0]), int(time[1]), int(time[2]))
|
||||
|
||||
class ShowRecorder(Thread):
|
||||
|
||||
def __init__ (self, show_instance, filelength, filename, filetype):
|
||||
Thread.__init__(self)
|
||||
self.api_client = api_client.api_client_factory(config)
|
||||
self.filelength = filelength
|
||||
self.filename = filename
|
||||
self.filetype = filetype
|
||||
|
@ -55,83 +72,73 @@ class Recorder(Thread):
|
|||
# datagen is a generator object that yields the encoded parameters
|
||||
datagen, headers = multipart_encode({"file": open(filepath, "rb"), 'name': filename, 'show_instance': self.show_instance})
|
||||
|
||||
url = config["base_url"] + config["upload_file_url"]
|
||||
|
||||
req = urllib2.Request(url, datagen, headers)
|
||||
response = urllib2.urlopen(req).read().strip()
|
||||
print response
|
||||
self.api_client.upload_recorded_show(datagen, headers)
|
||||
|
||||
def run(self):
|
||||
filepath = self.record_show()
|
||||
self.upload_file(filepath)
|
||||
|
||||
|
||||
def getDateTimeObj(time):
|
||||
class Record():
|
||||
|
||||
timeinfo = time.split(" ")
|
||||
date = timeinfo[0].split("-")
|
||||
time = timeinfo[1].split(":")
|
||||
def __init__(self):
|
||||
self.api_client = api_client.api_client_factory(config)
|
||||
self.shows_to_record = {}
|
||||
|
||||
return datetime.datetime(int(date[0]), int(date[1]), int(date[2]), int(time[0]), int(time[1]), int(time[2]))
|
||||
def process_shows(self, shows):
|
||||
|
||||
def process_shows(shows):
|
||||
|
||||
global shows_to_record
|
||||
shows_to_record = {}
|
||||
self.shows_to_record = {}
|
||||
|
||||
for show in shows:
|
||||
show_starts = getDateTimeObj(show[u'starts'])
|
||||
show_end = getDateTimeObj(show[u'ends'])
|
||||
time_delta = show_end - show_starts
|
||||
|
||||
shows_to_record[show[u'starts']] = [time_delta, show[u'instance_id']]
|
||||
self.shows_to_record[show[u'starts']] = [time_delta, show[u'instance_id']]
|
||||
|
||||
|
||||
def check_record():
|
||||
def check_record(self):
|
||||
|
||||
tnow = datetime.datetime.now()
|
||||
sorted_show_keys = sorted(shows_to_record.keys())
|
||||
sorted_show_keys = sorted(self.shows_to_record.keys())
|
||||
print sorted_show_keys
|
||||
start_time = sorted_show_keys[0]
|
||||
next_show = getDateTimeObj(start_time)
|
||||
|
||||
print next_show
|
||||
print tnow
|
||||
delta = next_show - tnow
|
||||
print delta
|
||||
|
||||
if delta <= datetime.timedelta(seconds=60):
|
||||
delta = next_show - tnow
|
||||
min_delta = datetime.timedelta(seconds=60)
|
||||
|
||||
if delta <= min_delta:
|
||||
print "sleeping %s seconds until show" % (delta.seconds)
|
||||
time.sleep(delta.seconds)
|
||||
|
||||
show_length = shows_to_record[start_time][0]
|
||||
show_instance = shows_to_record[start_time][1]
|
||||
show = Recorder(show_instance, show_length.seconds, start_time, filetype="mp3")
|
||||
show_length = self.shows_to_record[start_time][0]
|
||||
show_instance = self.shows_to_record[start_time][1]
|
||||
show = ShowRecorder(show_instance, show_length.seconds, start_time, filetype="mp3")
|
||||
show.start()
|
||||
|
||||
#remove show from shows to record.
|
||||
del shows_to_record[start_time]
|
||||
del self.shows_to_record[start_time]
|
||||
|
||||
|
||||
def get_shows():
|
||||
def get_shows(self):
|
||||
|
||||
url = config["base_url"] + config["show_schedule_url"]
|
||||
response = urllib.urlopen(url)
|
||||
data = response.read()
|
||||
|
||||
response_json = json.loads(data)
|
||||
shows = response_json[u'shows']
|
||||
print shows
|
||||
shows = self.api_client.get_shows_to_record()
|
||||
|
||||
if len(shows):
|
||||
process_shows(shows)
|
||||
check_record()
|
||||
self.process_shows(shows)
|
||||
self.check_record()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
recorder = Record()
|
||||
|
||||
while True:
|
||||
get_shows()
|
||||
recorder.get_shows()
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue