added shows, show-schedules, show-preview, show-history-feed, item-history-feed endpoints to the HTTP api to be used via NewscoopAirtimePlugin

This commit is contained in:
Mark Lewis 2014-11-17 21:53:31 +01:00 committed by Albert Santoni
parent 05c9e21e48
commit 44b4faf6d9
4 changed files with 307 additions and 48 deletions

View File

@ -5,8 +5,16 @@ class ApiController extends Zend_Controller_Action
public function init() public function init()
{ {
$ignoreAuth = array("live-info", "live-info-v2", "week-info", $ignoreAuth = array("live-info",
"station-metadata", "station-logo"); "live-info-v2",
"week-info",
"station-metadata",
"station-logo",
"show-history-feed",
"item-history-feed",
"shows",
"show-schedules"
);
$params = $this->getRequest()->getParams(); $params = $this->getRequest()->getParams();
if (!in_array($params['action'], $ignoreAuth)) { if (!in_array($params['action'], $ignoreAuth)) {
@ -47,6 +55,7 @@ class ApiController extends Zend_Controller_Action
->addActionContext('update-stream-setting-table' , 'json') ->addActionContext('update-stream-setting-table' , 'json')
->addActionContext('update-replay-gain-value' , 'json') ->addActionContext('update-replay-gain-value' , 'json')
->addActionContext('update-cue-values-by-silan' , 'json') ->addActionContext('update-cue-values-by-silan' , 'json')
->addActionContext('show-preview' , 'json')
->initContext(); ->initContext();
} }
@ -274,10 +283,10 @@ class ApiController extends Zend_Controller_Action
$utcTimeEnd = $end->format("Y-m-d H:i:s"); $utcTimeEnd = $end->format("Y-m-d H:i:s");
$result = array( $result = array(
"env" => APPLICATION_ENV, "env" => APPLICATION_ENV,
"schedulerTime" => $utcTimeNow, "schedulerTime" => $utcTimeNow,
"currentShow" => Application_Model_Show::getCurrentShow($utcTimeNow), "currentShow" => Application_Model_Show::getCurrentShow($utcTimeNow),
"nextShow" => Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd) "nextShow" => Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd)
); );
} else { } else {
$result = Application_Model_Schedule::GetPlayOrderRangeOld($limit); $result = Application_Model_Schedule::GetPlayOrderRangeOld($limit);
@ -484,9 +493,9 @@ class ApiController extends Zend_Controller_Action
$shows, $shows,
array("starts", "ends", "start_timestamp","end_timestamp"), array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone $timezone
); );
$result[$dow[$i]] = $shows; $result[$dow[$i]] = $shows;
} }
// XSS exploit prevention // XSS exploit prevention
@ -1320,4 +1329,194 @@ class ApiController extends Zend_Controller_Action
Application_Model_StreamSetting::SetListenerStatError($k, $v); Application_Model_StreamSetting::SetListenerStatError($k, $v);
} }
} }
/**
* display played items for a given time range and show instance_id
*
* @return json array
*/
public function itemHistoryFeedAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam("instance_id", null);
list($startsDT, $endsDT) = $this->getStartEnd($request);
$historyService = new Application_Service_HistoryService();
$results = $historyService->getPlayedItemData($startsDT, $endsDT, $params, $instance);
$this->_helper->json->sendJson($results['history']);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
/**
* display show schedules for a given time range and show instance_id
*
* @return json array
*/
public function showHistoryFeedAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$userId = $request->getParam("user_id", null);
list($startsDT, $endsDT) = $this->getStartEnd($request);
$historyService = new Application_Service_HistoryService();
$shows = $historyService->getShowList($startsDT, $endsDT, $userId);
$this->_helper->json->sendJson($shows);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
/**
* display show info (without schedule) for given show_id
*
* @return json array
*/
public function showsAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$showId = $request->getParam("show_id", null);
if (empty($showId)) {
$shows = Application_Model_Show::getDistinctShows();
} else {
$show = new Application_Model_Show($showId);
$shows = $show->getShowInfo();
}
$this->_helper->json->sendJson($shows);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
/**
* display show schedule for given show_id
*
* @return json array
*/
public function showSchedulesAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$showId = $request->getParam("show_id", null);
list($startsDT, $endsDT) = $this->getStartEnd($request);
$shows = Application_Model_Show::getShows($startsDT, $endsDT, FALSE, $showId);
$this->_helper->json->sendJson($shows);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function showPreviewAction()
{
$baseUrl = Application_Common_OsPath::getBaseDir();
$prefTimezone = Application_Model_Preference::GetTimezone();
$instanceId = $this->_getParam('instance_id');
$apiKey = $this->_getParam('api_key');
if (!isset($instanceId)) {
return;
}
$showInstance = new Application_Model_ShowInstance($instanceId);
$result = array();
$position = 0;
foreach ($showInstance->getShowListContent($prefTimezone) as $track) {
$elementMap = array(
'title' => isset($track['track_title']) ? $track['track_title'] : "",
'artist' => isset($track['creator']) ? $track['creator'] : "",
'position' => $position,
'id' => ++$position,
'mime' => isset($track['mime'])?$track['mime']:"",
'starts' => isset($track['starts']) ? $track['starts'] : "",
'length' => isset($track['length']) ? $track['length'] : "",
'file_id' => ($track['type'] == 0) ? $track['item_id'] : $track['filepath']
);
$result[] = $elementMap;
}
$this->_helper->json($result);
}
/**
* sets start and end vars from given params, or defauls to
* yesterday - today using server timezone
*/
private function getStartEnd($request)
{
$prefTimezone = Application_Model_Preference::GetTimezone();
$utcTimezone = new DateTimeZone("UTC");
$utcNow = new DateTime("now", $utcTimezone);
$start = $request->getParam("start");
$end = $request->getParam("end");
$timezone = $request->getParam("timezone");
if (empty($timezone)) {
$userTimezone = new DateTimeZone($prefTimezone);
} else {
$userTimezone = new DateTimeZone($timezone);
}
if (empty($start) || empty($end)) {
$startsDT = clone $utcNow;
$startsDT->sub(new DateInterval("P1D"));
$endsDT = clone $utcNow;
}
else {
try {
$startsDT = new DateTime($start, $userTimezone);
$startsDT->setTimezone($utcTimezone);
$endsDT = new DateTime($end, $userTimezone);
$endsDT->setTimezone($utcTimezone);
if ($startsDT > $endsDT) {
throw new Exception("start greater than end");
}
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
$startsDT = clone $utcNow;
$startsDT->sub(new DateInterval("P1D"));
$endsDT = clone $utcNow;
}
}
return array($startsDT, $endsDT);
}
} }

View File

@ -786,6 +786,34 @@ SQL;
} }
} }
/**
* returns show specific info (not related to isntance)
*/
public function getShowInfo()
{
$info = array();
if ($this->getId() == null) {
return $info;
} else {
$ccShow = CcShowQuery::create()->findPK($this->_showId);
$info['name'] = $ccShow->getDbName();
$info['id'] = $ccShow->getDbId();
$info['url'] = $ccShow->getDbUrl();
$info['genre'] = $ccShow->getDbGenre();
$info['description'] = $ccShow->getDbDescription();
$info['color'] = $ccShow->getDbColor();
$info['background_color'] = $ccShow->getDbBackgroundColor();
$info['custom_username'] = $ccShow->getDbLiveStreamUser();
$info['cb_airtime_auth'] = $ccShow->getDbLiveStreamUsingAirtimeAuth();
$info['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth();
$info['custom_username'] = $ccShow->getDbLiveStreamUser();
$info['custom_password'] = $ccShow->getDbLiveStreamPass();
$info['linked'] = $ccShow->getDbLinked();
$info['is_linkable'] = $ccShow->getDbIsLinkable();
return $info;
}
}
/* Only used for shows that are repeating. Note that this will return /* Only used for shows that are repeating. Note that this will return
* true even for dates that only have a "modified" show instance (does not * true even for dates that only have a "modified" show instance (does not
* check if the "modified_instance" column is set to true). This is intended * check if the "modified_instance" column is set to true). This is intended
@ -862,9 +890,10 @@ SQL;
* In UTC time. * In UTC time.
* @param unknown_type $excludeInstance * @param unknown_type $excludeInstance
* @param boolean $onlyRecord * @param boolean $onlyRecord
* @param int $showId
* @return array * @return array
*/ */
public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE) public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE, $showId=null)
{ {
self::createAndFillShowInstancesPastPopulatedUntilDate($end_timestamp); self::createAndFillShowInstancesPastPopulatedUntilDate($end_timestamp);
@ -895,13 +924,21 @@ SQL;
//only want shows that are starting at the time or later. //only want shows that are starting at the time or later.
$start_string = $start_timestamp->format("Y-m-d H:i:s"); $start_string = $start_timestamp->format("Y-m-d H:i:s");
$end_string = $end_timestamp->format("Y-m-d H:i:s"); $end_string = $end_timestamp->format("Y-m-d H:i:s");
$params = array();
if ($showId) {
$sql .= " AND (si1.show_id = :show_id)";
$params[':show_id'] = $showId;
}
if ($onlyRecord) { if ($onlyRecord) {
$sql .= " AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)"; $sql .= " AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)";
$sql .= " AND (si1.record = 1)"; $sql .= " AND (si1.record = 1)";
return Application_Common_Database::prepareAndExecute( $sql, $params[':start'] = $start_string;
array( ':start' => $start_string, $params[':end'] = $end_string;
':end' => $end_string ), 'all'); return Application_Common_Database::prepareAndExecute( $sql, $params, 'all');
} else { } else {
$sql .= " ". <<<SQL $sql .= " ". <<<SQL
@ -910,15 +947,16 @@ AND ((si1.starts >= :start1::TIMESTAMP AND si1.starts < :end1::TIMESTAMP)
OR (si1.starts <= :start3::TIMESTAMP AND si1.ends >= :end3::TIMESTAMP)) OR (si1.starts <= :start3::TIMESTAMP AND si1.ends >= :end3::TIMESTAMP))
ORDER BY si1.starts ORDER BY si1.starts
SQL; SQL;
return Application_Common_Database::prepareAndExecute( $sql, $params = array_merge($params, array(
array(
'start1' => $start_string, 'start1' => $start_string,
'start2' => $start_string, 'start2' => $start_string,
'start3' => $start_string, 'start3' => $start_string,
'end1' => $end_string, 'end1' => $end_string,
'end2' => $end_string, 'end2' => $end_string,
'end3' => $end_string 'end3' => $end_string
), 'all'); )
);
return Application_Common_Database::prepareAndExecute( $sql, $params, 'all');
} }
} }
@ -1013,10 +1051,10 @@ SQL;
//for putting the now playing icon on the show. //for putting the now playing icon on the show.
if ($now > $startsDT && $now < $endsDT) { if ($now > $startsDT && $now < $endsDT) {
$event["nowPlaying"] = true; $event["nowPlaying"] = true;
} }
else { else {
$event["nowPlaying"] = false; $event["nowPlaying"] = false;
} }
//event colouring //event colouring
@ -1045,9 +1083,9 @@ SQL;
**/ **/
private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled) private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled)
{ {
$utcTimezone = new DatetimeZone("UTC"); $utcTimezone = new DatetimeZone("UTC");
$startDt = new DateTime($p_starts, $utcTimezone); $startDt = new DateTime($p_starts, $utcTimezone);
$endDt = new DateTime($p_ends, $utcTimezone); $endDt = new DateTime($p_ends, $utcTimezone);
$durationSeconds = intval($endDt->format("U")) - intval($startDt->format("U")); $durationSeconds = intval($endDt->format("U")) - intval($startDt->format("U"));
$time_filled = Application_Common_DateHelper::playlistTimeToSeconds($p_time_filled); $time_filled = Application_Common_DateHelper::playlistTimeToSeconds($p_time_filled);
if ($durationSeconds != 0) { //Prevent division by zero if the show duration somehow becomes zero. if ($durationSeconds != 0) { //Prevent division by zero if the show duration somehow becomes zero.
@ -1448,4 +1486,13 @@ SQL;
return array($start, $end); return array($start, $end);
} }
public static function getDistinctShows() {
$sql = <<<SQL
SELECT * FROM cc_show
SQL;
$shows = Application_Common_Database::prepareAndExecute($sql);
return $shows;
}
} }

View File

@ -548,7 +548,7 @@ SQL;
} }
public function getShowListContent() public function getShowListContent($timezone = null)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -599,9 +599,14 @@ SQL;
':instance_id2' => $this->_instanceId ':instance_id2' => $this->_instanceId
)); ));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$userTimezone = Application_Model_Preference::GetUserTimezone(); if (isset($timezone)) {
$displayTimezone = new DateTimeZone($userTimezone); $displayTimezone = new DateTimeZone($timezone);
} else {
$userTimezone = Application_Model_Preference::GetUserTimezone();
$displayTimezone = new DateTimeZone($userTimezone);
}
$utcTimezone = new DateTimeZone("UTC"); $utcTimezone = new DateTimeZone("UTC");
foreach ($results as &$row) { foreach ($results as &$row) {

View File

@ -204,30 +204,34 @@ class Application_Service_HistoryService
//------------------------------------------------------------------------ //------------------------------------------------------------------------
//Using Datatables parameters to sort the data. //Using Datatables parameters to sort the data.
$numOrderColumns = $opts["iSortingCols"]; if (empty($opts["iSortingCols"])) {
$orderBys = array(); $orderBys = array();
} else {
$numOrderColumns = $opts["iSortingCols"];
$orderBys = array();
for ($i = 0; $i < $numOrderColumns; $i++) { for ($i = 0; $i < $numOrderColumns; $i++) {
$colNum = $opts["iSortCol_".$i]; $colNum = $opts["iSortCol_".$i];
$key = $opts["mDataProp_".$colNum]; $key = $opts["mDataProp_".$colNum];
$sortDir = $opts["sSortDir_".$i]; $sortDir = $opts["sSortDir_".$i];
if (in_array($key, $required)) { if (in_array($key, $required)) {
$orderBys[] = "history_range.{$key} {$sortDir}"; $orderBys[] = "history_range.{$key} {$sortDir}";
} }
else if (in_array($key, $filemd_keys)) { else if (in_array($key, $filemd_keys)) {
$orderBys[] = "file_info.{$key} {$sortDir}"; $orderBys[] = "file_info.{$key} {$sortDir}";
} }
else if (in_array($key, $general_keys)) { else if (in_array($key, $general_keys)) {
$orderBys[] = "{$key}_filter.{$key} {$sortDir}"; $orderBys[] = "{$key}_filter.{$key} {$sortDir}";
} }
else { else {
//throw new Exception("Error: $key is not part of the template."); //throw new Exception("Error: $key is not part of the template.");
} }
}
} }
if (count($orderBys) > 0) { if (count($orderBys) > 0) {
@ -241,7 +245,7 @@ class Application_Service_HistoryService
//--------------------------------------------------------------- //---------------------------------------------------------------
//using Datatables parameters to add limits/offsets //using Datatables parameters to add limits/offsets
$displayLength = intval($opts["iDisplayLength"]); $displayLength = empty($opts["iDisplayLength"]) ? -1 : intval($opts["iDisplayLength"]);
//limit the results returned. //limit the results returned.
if ($displayLength !== -1) { if ($displayLength !== -1) {
$mainSqlQuery.= $mainSqlQuery.=
@ -311,7 +315,7 @@ class Application_Service_HistoryService
} }
return array( return array(
"sEcho" => intval($opts["sEcho"]), "sEcho" => empty($opts["sEcho"]) ? null : intval($opts["sEcho"]),
//"iTotalDisplayRecords" => intval($totalDisplayRows), //"iTotalDisplayRecords" => intval($totalDisplayRows),
"iTotalDisplayRecords" => intval($totalRows), "iTotalDisplayRecords" => intval($totalRows),
"iTotalRecords" => intval($totalRows), "iTotalRecords" => intval($totalRows),
@ -445,9 +449,13 @@ class Application_Service_HistoryService
); );
} }
public function getShowList($startDT, $endDT) public function getShowList($startDT, $endDT, $userId = null)
{ {
$user = Application_Model_User::getCurrentUser(); if (empty($userId)) {
$user = Application_Model_User::getCurrentUser();
} else {
$user = new Application_Model_User($userId);
}
$shows = Application_Model_Show::getShows($startDT, $endDT); $shows = Application_Model_Show::getShows($startDT, $endDT);
Logging::info($startDT->format("Y-m-d H:i:s")); Logging::info($startDT->format("Y-m-d H:i:s"));
@ -456,7 +464,7 @@ class Application_Service_HistoryService
Logging::info($shows); Logging::info($shows);
//need to filter the list to only their shows //need to filter the list to only their shows
if ($user->isHost()) { if ((!empty($user)) && ($user->isHost())) {
$showIds = array(); $showIds = array();
@ -1524,4 +1532,4 @@ class Application_Service_HistoryService
throw $e; throw $e;
} }
} }
} }