Merge branch 'devel' of dev.sourcefabric.org:airtime into devel

This commit is contained in:
James 2011-08-18 13:54:17 -04:00
commit 38256de606
22 changed files with 199 additions and 184 deletions

View file

@ -176,7 +176,7 @@ class ScheduleController extends Zend_Controller_Action
public function makeContextMenuAction() public function makeContextMenuAction()
{ {
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$today_timestamp = date("Y-m-d H:i:s"); $epochNow = time();
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new User($userInfo->id); $user = new User($userInfo->id);
@ -184,7 +184,10 @@ class ScheduleController extends Zend_Controller_Action
$params = '/format/json/id/#id#'; $params = '/format/json/id/#id#';
if (strtotime($today_timestamp) < strtotime($show->getShowStart())) { $showStartDateHelper = DateHelper::ConvertToLocalDateTime($show->getShowStart());
$showEndDateHelper = DateHelper::ConvertToLocalDateTime($show->getShowEnd());
if ($epochNow < $showStartDateHelper->getTimestamp()) {
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId()) && !$show->isRecorded() && !$show->isRebroadcast()) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId()) && !$show->isRecorded() && !$show->isRebroadcast()) {
@ -202,7 +205,7 @@ class ScheduleController extends Zend_Controller_Action
'callback' => 'window["buildContentDialog"]'), 'title' => 'Show Content'); 'callback' => 'window["buildContentDialog"]'), 'title' => 'Show Content');
} }
if (strtotime($show->getShowEnd()) <= strtotime($today_timestamp) if ($showEndDateHelper->getTimestamp() <= $epochNow
&& is_null($show->getSoundCloudFileId()) && is_null($show->getSoundCloudFileId())
&& $show->isRecorded() && $show->isRecorded()
&& Application_Model_Preference::GetDoSoundCloudUpload()) { && Application_Model_Preference::GetDoSoundCloudUpload()) {
@ -212,15 +215,15 @@ class ScheduleController extends Zend_Controller_Action
} }
if (strtotime($show->getShowStart()) <= strtotime($today_timestamp) && if ($showStartDateHelper->getTimestamp() <= $epochNow &&
strtotime($today_timestamp) < strtotime($show->getShowEnd()) && $epochNow < $showEndDateHelper->getTimestamp() &&
$user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$menu[] = array('action' => array('type' => 'fn', $menu[] = array('action' => array('type' => 'fn',
'callback' => "window['confirmCancelShow']($id)"), 'callback' => "window['confirmCancelShow']($id)"),
'title' => 'Cancel Current Show'); 'title' => 'Cancel Current Show');
} }
if (strtotime($today_timestamp) < strtotime($show->getShowStart())) { if ($epochNow < $showStartDateHelper->getTimestamp()) {
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
@ -426,10 +429,16 @@ class ScheduleController extends Zend_Controller_Action
'add_show_genre' => $show->getGenre(), 'add_show_genre' => $show->getGenre(),
'add_show_description' => $show->getDescription())); 'add_show_description' => $show->getDescription()));
$formWhen->populate(array('add_show_start_date' => $show->getStartDate(), $startsDateTime = new DateTime($showInstance->getShowStart(), new DateTimeZone("UTC"));
'add_show_start_time' => DateHelper::removeSecondsFromTime($show->getStartTime()), $endsDateTime = new DateTime($showInstance->getShowEnd(), new DateTimeZone("UTC"));
'add_show_end_date_no_repeat' => $show->getEndDate(),
'add_show_end_time' => DateHelper::removeSecondsFromTime($show->getEndTime()), $startsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
$endsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
$formWhen->populate(array('add_show_start_date' => $startsDateTime->format("Y-m-d"),
'add_show_start_time' => $startsDateTime->format("H:i"),
'add_show_end_date_no_repeat' => $endsDateTime->format("Y-m-d"),
'add_show_end_time' => $endsDateTime->format("H:i"),
'add_show_duration' => $show->getDuration(true), 'add_show_duration' => $show->getDuration(true),
'add_show_repeats' => $show->isRepeating() ? 1 : 0)); 'add_show_repeats' => $show->isRepeating() ? 1 : 0));
@ -443,13 +452,13 @@ class ScheduleController extends Zend_Controller_Action
array_push($days, $showDay->getDbDay()); array_push($days, $showDay->getDbDay());
} }
$displayedEndDate = new DateTime($show->getRepeatingEndDate()); $displayedEndDate = new DateTime($show->getRepeatingEndDate(), new DateTimeZone("UTC"));
$displayedEndDate->sub(new DateInterval("P1D"));//end dates are stored non-inclusively. $displayedEndDate->sub(new DateInterval("P1D"));//end dates are stored non-inclusively.
$displayedEndDate = $displayedEndDate->format("Y-m-d"); $displayedEndDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
$formRepeats->populate(array('add_show_repeat_type' => $show->getRepeatType(), $formRepeats->populate(array('add_show_repeat_type' => $show->getRepeatType(),
'add_show_day_check' => $days, 'add_show_day_check' => $days,
'add_show_end_date' => $displayedEndDate, 'add_show_end_date' => $displayedEndDate->format("Y-m-d"),
'add_show_no_end' => ($show->getRepeatingEndDate() == ''))); 'add_show_no_end' => ($show->getRepeatingEndDate() == '')));
$formRecord->populate(array('add_show_record' => $show->isRecorded(), $formRecord->populate(array('add_show_record' => $show->isRecorded(),

View file

@ -88,18 +88,16 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
} }
public function checkReliantFields($formData, $startDateModified) { public function checkReliantFields($formData, $startDateModified) {
$valid = true; $valid = true;
$now_timestamp = date("Y-m-d H:i:s"); $start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
$start_timestamp = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
$now_epoch = strtotime($now_timestamp);
$start_epoch = strtotime($start_timestamp);
//DateTime stores $start_time in the current timezone
$nowDateTime = new DateTime();
$showStartDateTime = new DateTime($start_time);
if ((($formData['add_show_id'] != -1) && $startDateModified) || ($formData['add_show_id'] == -1)){ if ((($formData['add_show_id'] != -1) && $startDateModified) || ($formData['add_show_id'] == -1)){
if($start_epoch < $now_epoch) { if($showStartDateTime->getTimestamp() < $nowDateTime->getTimestamp()) {
$this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past')); $this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past'));
$valid = false; $valid = false;
} }
@ -118,6 +116,5 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
return $valid; return $valid;
} }
} }

View file

@ -13,9 +13,7 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$this->addElement('text', 'stationName', array( $this->addElement('text', 'stationName', array(
'class' => 'input_text', 'class' => 'input_text',
'label' => 'Station Name', 'label' => 'Station Name',
'required' => true,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'validators' => array('NotEmpty'),
'value' => Application_Model_Preference::GetValue("station_name"), 'value' => Application_Model_Preference::GetValue("station_name"),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'

View file

@ -16,4 +16,9 @@ class Logging {
public static function setLogPath($path){ public static function setLogPath($path){
self::$_path = $path; self::$_path = $path;
} }
public static function log($p_msg){
$logger = self::getLogger();
$logger->info($p_msg);
}
} }

View file

@ -2,11 +2,11 @@
class DateHelper class DateHelper
{ {
private $_timestamp; private $_dateTime;
function __construct() function __construct()
{ {
$this->_timestamp = date("U"); $this->_dateTime = date("U");
} }
/** /**
@ -15,7 +15,19 @@ class DateHelper
*/ */
function getTimestamp() function getTimestamp()
{ {
return date("Y-m-d H:i:s", $this->_timestamp); return date("Y-m-d H:i:s", $this->_dateTime);
}
/**
* Get time of object construction in the format
* YYYY-MM-DD HH:mm:ss
*/
function getUtcTimestamp()
{
$dateTime = new DateTime("@".$this->_dateTime);
$dateTime->setTimezone(new DateTimeZone("UTC"));
return $dateTime->format("Y-m-d H:i:s");
} }
/** /**
@ -24,7 +36,7 @@ class DateHelper
*/ */
function getDate() function getDate()
{ {
return date("Y-m-d", $this->_timestamp); return date("Y-m-d", $this->_dateTime);
} }
/** /**
@ -33,7 +45,7 @@ class DateHelper
*/ */
function getTime() function getTime()
{ {
return date("H:i:s", $this->_timestamp); return date("H:i:s", $this->_dateTime);
} }
/** /**
@ -41,28 +53,30 @@ class DateHelper
*/ */
function setDate($dateString) function setDate($dateString)
{ {
$this->_timestamp = strtotime($dateString); $this->_dateTime = strtotime($dateString);
} }
/** /**
* * Find the epoch timestamp difference from "now" to the beginning of today.
* Enter description here ...
*/ */
function getNowDayStartDiff() function getNowDayStartDiff()
{ {
$dayStartTS = strtotime(date("Y-m-d", $this->_timestamp)); $dayStartTs = ((int)($this->_dateTime/86400))*86400;
return $this->_timestamp - $dayStartTS; return $this->_dateTime - $dayStartTs;
} }
/**
* Find the epoch timestamp difference from "now" to the end of today.
*/
function getNowDayEndDiff() function getNowDayEndDiff()
{ {
$dayEndTS = strtotime(date("Y-m-d", $this->_timestamp+(86400))); $dayEndTs = ((int)(($this->_dateTime+86400)/86400))*86400;
return $dayEndTS - $this->_timestamp; return $dayEndTs - $this->_dateTime;
} }
function getEpochTime() function getEpochTime()
{ {
return $this->_timestamp; return $this->_dateTime;
} }
public static function TimeDiff($time1, $time2) public static function TimeDiff($time1, $time2)
@ -100,31 +114,31 @@ class DateHelper
* format "hh:mm:ss". But when dealing with show times, we * format "hh:mm:ss". But when dealing with show times, we
* do not care about the seconds. * do not care about the seconds.
* *
* @param int $p_timestamp * @param int $p_dateTime
* The value which to format. * The value which to format.
* @return int * @return int
* The timestamp with the new format "hh:mm", or * The timestamp with the new format "hh:mm", or
* the original input parameter, if it does not have * the original input parameter, if it does not have
* the correct format. * the correct format.
*/ */
public static function removeSecondsFromTime($p_timestamp) public static function removeSecondsFromTime($p_dateTime)
{ {
//Format is in hh:mm:ss. We want hh:mm //Format is in hh:mm:ss. We want hh:mm
$timeExplode = explode(":", $p_timestamp); $timeExplode = explode(":", $p_dateTime);
if (count($timeExplode) == 3) if (count($timeExplode) == 3)
return $timeExplode[0].":".$timeExplode[1]; return $timeExplode[0].":".$timeExplode[1];
else else
return $p_timestamp; return $p_dateTime;
} }
public static function getDateFromTimestamp($p_timestamp){ public static function getDateFromTimestamp($p_dateTime){
$explode = explode(" ", $p_timestamp); $explode = explode(" ", $p_dateTime);
return $explode[0]; return $explode[0];
} }
public static function getTimeFromTimestamp($p_timestamp){ public static function getTimeFromTimestamp($p_dateTime){
$explode = explode(" ", $p_timestamp); $explode = explode(" ", $p_dateTime);
return $explode[1]; return $explode[1];
} }
@ -157,5 +171,19 @@ class DateHelper
return $totalSeconds; return $totalSeconds;
} }
public static function ConvertToLocalDateTime($p_dateString){
$dateTime = new DateTime($p_dateString, new DateTimeZone("UTC"));
$dateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $dateTime;
}
public static function ConvertToLocalDateTimeString($p_dateString, $format="Y-m-d H:i:s"){
$dateTime = new DateTime($p_dateString, new DateTimeZone("UTC"));
$dateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $dateTime->format($format);
}
} }

View file

@ -3,21 +3,31 @@
class Application_Model_Nowplaying class Application_Model_Nowplaying
{ {
public static function CreateHeaderRow($p_showName, $p_showStart, $p_showEnd){ private static function CreateHeaderRow($p_showName, $p_showStart, $p_showEnd){
return array("h", "", $p_showStart, $p_showEnd, $p_showName, "", "", "", "", "", ""); return array("h", "", $p_showStart, $p_showEnd, $p_showName, "", "", "", "", "", "");
} }
public static function CreateDatatableRows($p_dbRows){ private static function CreateDatatableRows($p_dbRows){
$dataTablesRows = array(); $dataTablesRows = array();
$date = new DateHelper; $epochNow = time();
$timeNow = $date->getTimestamp();
foreach ($p_dbRows as $dbRow){ foreach ($p_dbRows as $dbRow){
$showStartDateTime = DateHelper::ConvertToLocalDateTime($dbRow['show_starts']);
$showEndDateTime = DateHelper::ConvertToLocalDateTime($dbRow['show_ends']);
$itemStartDateTime = DateHelper::ConvertToLocalDateTime($dbRow['item_starts']);
$itemEndDateTime = DateHelper::ConvertToLocalDateTime($dbRow['item_ends']);
$showStarts = $showStartDateTime->format("Y-m-d H:i:s");
$showEnds = $showEndDateTime->format("Y-m-d H:i:s");
$itemStarts = $itemStartDateTime->format("Y-m-d H:i:s");
$itemEnds = $itemEndDateTime->format("Y-m-d H:i:s");
$status = ($dbRow['show_ends'] < $dbRow['item_ends']) ? "x" : ""; $status = ($dbRow['show_ends'] < $dbRow['item_ends']) ? "x" : "";
$type = "a"; $type = "a";
$type .= ($dbRow['item_ends'] > $timeNow && $dbRow['item_starts'] <= $timeNow) ? "c" : ""; $type .= ($itemEndDateTime->getTimestamp() > $epochNow && $itemStartDateTime->getTimestamp() <= $epochNow) ? "c" : "";
// remove millisecond from the time format // remove millisecond from the time format
$itemStart = explode('.', $dbRow['item_starts']); $itemStart = explode('.', $dbRow['item_starts']);
@ -25,28 +35,28 @@ class Application_Model_Nowplaying
//format duration //format duration
$duration = explode('.', $dbRow['clip_length']); $duration = explode('.', $dbRow['clip_length']);
$formated = Application_Model_Nowplaying::FormatDuration($duration[0]); $formatted = self::FormatDuration($duration[0]);
$dataTablesRows[] = array($type, $dbRow['show_starts'], $itemStart[0], $itemEnd[0], $dataTablesRows[] = array($type, $showStarts, $itemStarts, $itemEnds,
$formated, $dbRow['track_title'], $dbRow['artist_name'], $dbRow['album_title'], $formatted, $dbRow['track_title'], $dbRow['artist_name'], $dbRow['album_title'],
$dbRow['playlist_name'], $dbRow['show_name'], $status); $dbRow['playlist_name'], $dbRow['show_name'], $status);
} }
return $dataTablesRows; return $dataTablesRows;
} }
public static function CreateGapRow($p_gapTime){ private static function CreateGapRow($p_gapTime){
return array("g", "", "", "", $p_gapTime, "", "", "", "", "", ""); return array("g", "", "", "", $p_gapTime, "", "", "", "", "", "");
} }
public static function CreateRecordingRow($p_showInstance){ private static function CreateRecordingRow($p_showInstance){
return array("r", "", "", "", $p_showInstance->getName(), "", "", "", "", "", ""); return array("r", "", "", "", $p_showInstance->getName(), "", "", "", "", "", "");
} }
public static function GetDataGridData($viewType, $dateString){ public static function GetDataGridData($viewType, $dateString){
if ($viewType == "now"){ if ($viewType == "now"){
$date = new DateHelper; $dateTime = new DateTime("now", new DateTimeZone("UTC"));
$timeNow = $date->getTimestamp(); $timeNow = $dateTime->format("Y-m-d H:i:s");
$startCutoff = 60; $startCutoff = 60;
$endCutoff = 86400; //60*60*24 - seconds in a day $endCutoff = 86400; //60*60*24 - seconds in a day
@ -54,7 +64,7 @@ class Application_Model_Nowplaying
$date = new DateHelper; $date = new DateHelper;
$time = $date->getTime(); $time = $date->getTime();
$date->setDate($dateString." ".$time); $date->setDate($dateString." ".$time);
$timeNow = $date->getTimestamp(); $timeNow = $date->getUtcTimestamp();
$startCutoff = $date->getNowDayStartDiff(); $startCutoff = $date->getNowDayStartDiff();
$endCutoff = $date->getNowDayEndDiff(); $endCutoff = $date->getNowDayEndDiff();
@ -71,21 +81,24 @@ class Application_Model_Nowplaying
$showId = $si->getShowId(); $showId = $si->getShowId();
$show = new Show($showId); $show = new Show($showId);
$showStartDateTime = DateHelper::ConvertToLocalDateTime($si->getShowStart());
$showEndDateTime = DateHelper::ConvertToLocalDateTime($si->getShowEnd());
//append show header row //append show header row
$data[] = Application_Model_Nowplaying::CreateHeaderRow($show->getName(), $si->getShowStart(), $si->getShowEnd()); $data[] = self::CreateHeaderRow($show->getName(), $showStartDateTime->format("Y-m-d H:i:s"), $showEndDateTime->format("Y-m-d H:i:s"));
$scheduledItems = $si->getScheduleItemsInRange($timeNow, $startCutoff, $endCutoff); $scheduledItems = $si->getScheduleItemsInRange($timeNow, $startCutoff, $endCutoff);
$dataTablesRows = Application_Model_Nowplaying::CreateDatatableRows($scheduledItems); $dataTablesRows = self::CreateDatatableRows($scheduledItems);
//append show audio item rows //append show audio item rows
$data = array_merge($data, $dataTablesRows); $data = array_merge($data, $dataTablesRows);
//append show gap time row //append show gap time row
$gapTime = Application_Model_Nowplaying::FormatDuration($si->getShowEndGapTime(), true); $gapTime = self::FormatDuration($si->getShowEndGapTime(), true);
if ($si->isRecorded()) if ($si->isRecorded())
$data[] = Application_Model_Nowplaying::CreateRecordingRow($si); $data[] = self::CreateRecordingRow($si);
else if ($gapTime > 0) else if ($gapTime > 0)
$data[] = Application_Model_Nowplaying::CreateGapRow($gapTime); $data[] = self::CreateGapRow($gapTime);
} }
return array("currentShow"=>Show_DAL::GetCurrentShow($timeNow), "rows"=>$data); return array("currentShow"=>Show_DAL::GetCurrentShow($timeNow), "rows"=>$data);
@ -102,7 +115,7 @@ class Application_Model_Nowplaying
* default $time format should be in format of 00:00:00 * default $time format should be in format of 00:00:00
* if $inSecond = true, then $time should be in seconds * if $inSecond = true, then $time should be in seconds
*/ */
public static function FormatDuration($time, $inSecond=false){ private static function FormatDuration($time, $inSecond=false){
if($inSecond == false){ if($inSecond == false){
$duration = explode(':', $time); $duration = explode(':', $time);
}else{ }else{

View file

@ -264,7 +264,6 @@ class Application_Model_Preference
Application_Model_Preference::SetValue("timezone", $timezone); Application_Model_Preference::SetValue("timezone", $timezone);
date_default_timezone_set($timezone); date_default_timezone_set($timezone);
$md = array("timezone" => $timezone); $md = array("timezone" => $timezone);
RabbitMq::SendMessageToPypo("update_timezone", $md);
} }
public static function GetTimezone(){ public static function GetTimezone(){

View file

@ -108,13 +108,12 @@ class RabbitMq
$EXCHANGE = 'airtime-show-recorder'; $EXCHANGE = 'airtime-show-recorder';
$channel->exchange_declare($EXCHANGE, 'direct', false, true); $channel->exchange_declare($EXCHANGE, 'direct', false, true);
$today_timestamp = date("Y-m-d H:i:s"); $now = new DateTime("@".time());
$now = new DateTime($today_timestamp); $end_timestamp = new DateTime("@".time() + 3600*2);
$end_timestamp = $now->add(new DateInterval("PT2H"));
$end_timestamp = $end_timestamp->format("Y-m-d H:i:s");
$temp['event_type'] = $event_type; $temp['event_type'] = $event_type;
if($event_type = "update_schedule"){ if($event_type = "update_schedule"){
$temp['shows'] = Show::getShows($today_timestamp, $end_timestamp, $excludeInstance=NULL, $onlyRecord=TRUE); $temp['shows'] = Show::getShows($now->format("Y-m-d H:i:s"), $end_timestamp->format("Y-m-d H:i:s"), $excludeInstance=NULL, $onlyRecord=TRUE);
} }
$data = json_encode($temp); $data = json_encode($temp);
$msg = new AMQPMessage($data, array('content_type' => 'text/plain')); $msg = new AMQPMessage($data, array('content_type' => 'text/plain'));

View file

@ -364,12 +364,9 @@ class Schedule {
global $CC_CONFIG; global $CC_CONFIG;
$date = new DateHelper; $date = new DateHelper;
$timeNow = $date->getTimestamp(); $timeNow = $date->getUtcTimestamp();
return array("env"=>APPLICATION_ENV, return array("env"=>APPLICATION_ENV,
"schedulerTime"=>gmdate("Y-m-d H:i:s"), "schedulerTime"=>$timeNow,
//"previous"=>Schedule::GetScheduledItemData($timeNow, -1, $prev, "24 hours"),
//"current"=>Schedule::GetScheduledItemData($timeNow, 0),
//"next"=>Schedule::GetScheduledItemData($timeNow, 1, $next, "48 hours"),
"previous"=>Application_Model_Dashboard::GetPreviousItem($timeNow), "previous"=>Application_Model_Dashboard::GetPreviousItem($timeNow),
"current"=>Application_Model_Dashboard::GetCurrentItem($timeNow), "current"=>Application_Model_Dashboard::GetCurrentItem($timeNow),
"next"=>Application_Model_Dashboard::GetNextItem($timeNow), "next"=>Application_Model_Dashboard::GetNextItem($timeNow),
@ -660,13 +657,13 @@ class Schedule {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
if (is_null($p_fromDateTime)) { if (is_null($p_fromDateTime)) {
$t1 = new DateTime(); $t1 = new DateTime("now", new DateTimeZone("UTC"));
$range_start = $t1->format("Y-m-d H:i:s"); $range_start = $t1->format("Y-m-d H:i:s");
} else { } else {
$range_start = Schedule::PypoTimeToAirtimeTime($p_fromDateTime); $range_start = Schedule::PypoTimeToAirtimeTime($p_fromDateTime);
} }
if (is_null($p_fromDateTime)) { if (is_null($p_fromDateTime)) {
$t2 = new DateTime(); $t2 = new DateTime("now", new DateTimeZone("UTC"));
$t2->add(new DateInterval("PT24H")); $t2->add(new DateInterval("PT24H"));
$range_end = $t2->format("Y-m-d H:i:s"); $range_end = $t2->format("Y-m-d H:i:s");
} else { } else {
@ -740,7 +737,6 @@ class Schedule {
$result['stream_metadata'] = array(); $result['stream_metadata'] = array();
$result['stream_metadata']['format'] = Application_Model_Preference::GetStreamLabelFormat(); $result['stream_metadata']['format'] = Application_Model_Preference::GetStreamLabelFormat();
$result['stream_metadata']['station_name'] = Application_Model_Preference::GetStationName(); $result['stream_metadata']['station_name'] = Application_Model_Preference::GetStationName();
$result['server_timezone'] = date('O');
return $result; return $result;
} }

View file

@ -724,27 +724,26 @@ class Show {
*/ */
public static function create($data) public static function create($data)
{ {
$con = Propel::getConnection(CcShowPeer::DATABASE_NAME);
$sql = "SELECT EXTRACT(DOW FROM TIMESTAMP '{$data['add_show_start_date']} {$data['add_show_start_time']}')"; $utcStartDateTime = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time']);
$r = $con->query($sql); $utcStartDateTime->setTimezone(new DateTimeZone('UTC'));
$startDow = $r->fetchColumn(0);
if ($data['add_show_no_end']) { if ($data['add_show_no_end']) {
$endDate = NULL; $endDateTime = NULL;
} }
else if ($data['add_show_repeats']) { else if ($data['add_show_repeats']) {
$sql = "SELECT date '{$data['add_show_end_date']}' + INTERVAL '1 day' "; $endDateTime = new DateTime($data['add_show_end_date']);
$r = $con->query($sql); $endDateTime->setTimezone(new DateTimeZone('UTC'));
$endDate = $r->fetchColumn(0); $endDateTime->add(new DateInterval("P1D"));
} }
else { else {
$sql = "SELECT date '{$data['add_show_start_date']}' + INTERVAL '1 day' "; $endDateTime = new DateTime($data['add_show_start_date']);
$r = $con->query($sql); $endDateTime->setTimezone(new DateTimeZone('UTC'));
$endDate = $r->fetchColumn(0); $endDateTime->add(new DateInterval("P1D"));
} }
//only want the day of the week from the start date. //only want the day of the week from the start date.
$startDow = date("w", $utcStartDateTime->getTimestamp());
if (!$data['add_show_repeats']) { if (!$data['add_show_repeats']) {
$data['add_show_day_check'] = array($startDow); $data['add_show_day_check'] = array($startDow);
} else if ($data['add_show_repeats'] && $data['add_show_day_check'] == "") { } else if ($data['add_show_repeats'] && $data['add_show_day_check'] == "") {
@ -768,12 +767,12 @@ class Show {
$ccShow->save(); $ccShow->save();
$showId = $ccShow->getDbId(); $showId = $ccShow->getDbId();
$show = new Show($showId);
$isRecorded = ($data['add_show_record']) ? 1 : 0; $isRecorded = ($data['add_show_record']) ? 1 : 0;
if ($data['add_show_id'] != -1){ if ($data['add_show_id'] != -1){
$show->deletePossiblyInvalidInstances($data, $endDate, $isRecorded, $repeatType); $show = new Show($showId);
$show->deletePossiblyInvalidInstances($data, $endDateTime->format("Y-m-d"), $isRecorded, $repeatType);
} }
//check if we are adding or updating a show, and if updating //check if we are adding or updating a show, and if updating
@ -785,37 +784,30 @@ class Show {
//don't set day for monthly repeat type, it's invalid. //don't set day for monthly repeat type, it's invalid.
if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2){ if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2){
$showDay = new CcShowDays(); $showDay = new CcShowDays();
$showDay->setDbFirstShow($data['add_show_start_date']); $showDay->setDbFirstShow($utcStartDateTime->format("Y-m-d"));
$showDay->setDbLastShow($endDate); $showDay->setDbLastShow($endDateTime->format("Y-m-d"));
$showDay->setDbStartTime($data['add_show_start_time']); $showDay->setDbStartTime($utcStartDateTime->format("H:i:s"));
$showDay->setDbDuration($data['add_show_duration']); $showDay->setDbDuration($data['add_show_duration']);
$showDay->setDbRepeatType($repeatType); $showDay->setDbRepeatType($repeatType);
$showDay->setDbShowId($showId); $showDay->setDbShowId($showId);
$showDay->setDbRecord($isRecorded); $showDay->setDbRecord($isRecorded);
$showDay->save(); $showDay->save();
} } else {
else {
foreach ($data['add_show_day_check'] as $day) { foreach ($data['add_show_day_check'] as $day) {
if ($startDow !== $day){ if ($startDow !== $day){
if ($startDow > $day) if ($startDow > $day)
$daysAdd = 6 - $startDow + 1 + $day; $daysAdd = 6 - $startDow + 1 + $day;
else else
$daysAdd = $day - $startDow; $daysAdd = $day - $startDow;
$sql = "SELECT date '{$data['add_show_start_date']}' + INTERVAL '{$daysAdd} day' "; $utcStartDateTime->add("P".$daysAdd."d");
$r = $con->query($sql);
$start = $r->fetchColumn(0);
}
else {
$start = $data['add_show_start_date'];
} }
if (strtotime($start) <= strtotime($endDate) || is_null($endDate)) { if (is_null($endDateTime) || strtotime($utcStartDateTime->format("Y-m-d")) <= $endDateTime->getTimestamp()) {
$showDay = new CcShowDays(); $showDay = new CcShowDays();
$showDay->setDbFirstShow($start); $showDay->setDbFirstShow($utcStartDateTime->format("Y-m-d"));
$showDay->setDbLastShow($endDate); $showDay->setDbLastShow($endDateTime->format("Y-m-d"));
$showDay->setDbStartTime($data['add_show_start_time']); $showDay->setDbStartTime($utcStartDateTime->format("H:i:s"));
$showDay->setDbDuration($data['add_show_duration']); $showDay->setDbDuration($data['add_show_duration']);
$showDay->setDbDay($day); $showDay->setDbDay($day);
$showDay->setDbRepeatType($repeatType); $showDay->setDbRepeatType($repeatType);
@ -826,15 +818,11 @@ class Show {
} }
} }
$date = new DateHelper();
$currentTimestamp = $date->getTimestamp();
//check if we are adding or updating a show, and if updating //check if we are adding or updating a show, and if updating
//erase all the show's future show_rebroadcast information first. //erase all the show's future show_rebroadcast information first.
if (($data['add_show_id'] != -1) && $data['add_show_rebroadcast']){ if (($data['add_show_id'] != -1) && $data['add_show_rebroadcast']){
CcShowRebroadcastQuery::create() CcShowRebroadcastQuery::create()
->filterByDbShowId($data['add_show_id']) ->filterByDbShowId($data['add_show_id'])
//->filterByDbStartTime($currentTimestamp, Criteria::GREATER_EQUAL)
->delete(); ->delete();
} }
//adding rows to cc_show_rebroadcast //adding rows to cc_show_rebroadcast
@ -852,6 +840,7 @@ class Show {
else if ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)){ else if ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)){
for ($i=1; $i<=10; $i++) { for ($i=1; $i<=10; $i++) {
if ($data['add_show_rebroadcast_date_absolute_'.$i]) { if ($data['add_show_rebroadcast_date_absolute_'.$i]) {
$con = Propel::getConnection(CcShowPeer::DATABASE_NAME);
$sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' "; $sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' ";
$r = $con->query($sql); $r = $con->query($sql);
$offset_days = $r->fetchColumn(0); $offset_days = $r->fetchColumn(0);
@ -1237,10 +1226,16 @@ class Show {
$event["disableResizing"] = true; $event["disableResizing"] = true;
} }
$startDateTime = new DateTime($show["starts"], new DateTimeZone("UTC"));
$startDateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
$endDateTime = new DateTime($show["ends"], new DateTimeZone("UTC"));
$endDateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
$event["id"] = $show["instance_id"]; $event["id"] = $show["instance_id"];
$event["title"] = $show["name"]; $event["title"] = $show["name"];
$event["start"] = $show["starts"]; $event["start"] = $startDateTime->format("Y-m-d H:i:s");
$event["end"] = $show["ends"]; $event["end"] = $endDateTime->format("Y-m-d H:i:s");
$event["allDay"] = false; $event["allDay"] = false;
$event["description"] = $show["description"]; $event["description"] = $show["description"];
$event["showId"] = $show["show_id"]; $event["showId"] = $show["show_id"];

View file

@ -12,7 +12,9 @@
<?php $i=0; ?> <?php $i=0; ?>
<?php foreach($this->showContent as $row): ?> <?php foreach($this->showContent as $row): ?>
<tr id="au_<?php echo $row["file_id"] ?>" class="<?php if($i&1){echo "even";}else{echo "odd";}?>"> <tr id="au_<?php echo $row["file_id"] ?>" class="<?php if($i&1){echo "even";}else{echo "odd";}?>">
<td><?php echo $row["starts"] ?></td> <td><?php $dt = new DateTime($row["starts"], new DateTimeZone("UTC"));
$dt->setTimezone(new DateTimeZone(date_default_timezone_get()));
echo $dt->format("Y-m-d H:i:s") ?></td>
<td><?php echo $row["track_title"] ?></td> <td><?php echo $row["track_title"] ?></td>
<td><?php echo $row["artist_name"] ?></td> <td><?php echo $row["artist_name"] ?></td>
<td><?php echo $row["album_title"] ?></td> <td><?php echo $row["album_title"] ?></td>

View file

@ -13,6 +13,8 @@ var currentElem;
var serverUpdateInterval = 5000; var serverUpdateInterval = 5000;
var uiUpdateInterval = 200; var uiUpdateInterval = 200;
var timezoneOffset = 0;
//set to "development" if we are developing :). Useful to disable alerts //set to "development" if we are developing :). Useful to disable alerts
//when entering production mode. //when entering production mode.
var APPLICATION_ENV = ""; var APPLICATION_ENV = "";
@ -169,7 +171,7 @@ function updatePlaybar(){
} }
/* Column 2 update */ /* Column 2 update */
$('#time').text(convertDateToHHMMSS(estimatedSchedulePosixTime)); $('#time').text(convertDateToHHMMSS(estimatedSchedulePosixTime + timezoneOffset));
} }
function calcAdditionalData(currentItem){ function calcAdditionalData(currentItem){
@ -209,7 +211,7 @@ function parseItems(obj){
calcAdditionalShowData(obj.nextShow); calcAdditionalShowData(obj.nextShow);
var schedulePosixTime = convertDateToPosixTime(obj.schedulerTime); var schedulePosixTime = convertDateToPosixTime(obj.schedulerTime);
schedulePosixTime += parseInt(obj.timezoneOffset)*1000; timezoneOffset = parseInt(obj.timezoneOffset)*1000;
var date = new Date(); var date = new Date();
localRemoteTimeOffset = date.getTime() - schedulePosixTime; localRemoteTimeOffset = date.getTime() - schedulePosixTime;
} }

View file

@ -26,9 +26,9 @@ echo "----------------------------------------------------"
# Updated package list # Updated package list
sudo apt-get -y install tar gzip curl apache2 php5-pgsql libapache2-mod-php5 \ sudo apt-get -y install tar gzip curl apache2 php5-pgsql libapache2-mod-php5 \
php-pear php5-gd postgresql odbc-postgresql python2.6 lame libsoundtouch-ocaml \ php-pear php5-gd postgresql odbc-postgresql python2.6 lame libsoundtouch-ocaml \
libvorbis-ocaml-dev libmp3lame-dev libtaglib-ocaml libao-ocaml libmad-ocaml \ libmp3lame-dev libtaglib-ocaml libao-ocaml libmad-ocaml ecasound \
libesd0 icecast2 sudo libportaudio2 libsamplerate0 libcamomile-ocaml-dev \ libesd0 icecast2 sudo libportaudio2 libsamplerate0 rabbitmq-server \
ecasound php5-curl mpg123 rabbitmq-server monit python-virtualenv php5-curl mpg123 monit python-virtualenv
if [ "$?" -ne "0" ]; then if [ "$?" -ne "0" ]; then
echo "" echo ""

View file

@ -50,9 +50,9 @@ AirtimeInstall::SetAirtimeVersion(AIRTIME_VERSION);
// set up some keys in DB // set up some keys in DB
AirtimeInstall::SetUniqueId(); AirtimeInstall::SetUniqueId();
AirtimeInstall::SetImportTimestamp(); AirtimeInstall::SetImportTimestamp();
AirtimeInstall::SetDefaultTimezone();
if (AirtimeInstall::$databaseTablesCreated) { if (AirtimeInstall::$databaseTablesCreated) {
AirtimeInstall::SetDefaultTimezone();
$ini = parse_ini_file(__DIR__."/airtime-install.ini"); $ini = parse_ini_file(__DIR__."/airtime-install.ini");

View file

@ -622,7 +622,9 @@ class ObpApiClient():
return obp_version return obp_version
"""
NOTE: The server currently ignores start and end parameters we send to it.
"""
def get_schedule(self, start=None, end=None): def get_schedule(self, start=None, end=None):
logger = logging.getLogger() logger = logging.getLogger()
@ -630,13 +632,12 @@ class ObpApiClient():
calculate start/end time range (format: YYYY-DD-MM-hh-mm-ss,YYYY-DD-MM-hh-mm-ss) calculate start/end time range (format: YYYY-DD-MM-hh-mm-ss,YYYY-DD-MM-hh-mm-ss)
(seconds are ignored, just here for consistency) (seconds are ignored, just here for consistency)
""" """
tnow = time.localtime(time.time())
if (not start): if (not start):
tstart = time.localtime(time.time() - 3600 * int(self.config["cache_for"])) tstart = time.gmtime(time.time() - 3600 * int(self.config["cache_for"]))
start = "%04d-%02d-%02d-%02d-%02d" % (tstart[0], tstart[1], tstart[2], tstart[3], tstart[4]) start = "%04d-%02d-%02d-%02d-%02d" % (tstart[0], tstart[1], tstart[2], tstart[3], tstart[4])
if (not end): if (not end):
tend = time.localtime(time.time() + 3600 * int(self.config["prepare_ahead"])) tend = time.gmtime(time.time() + 3600 * int(self.config["prepare_ahead"]))
end = "%04d-%02d-%02d-%02d-%02d" % (tend[0], tend[1], tend[2], tend[3], tend[4]) end = "%04d-%02d-%02d-%02d-%02d" % (tend[0], tend[1], tend[2], tend[3], tend[4])
range = {} range = {}

View file

@ -1,6 +1,7 @@
import os import os
import sys import sys
import time import time
import calendar
import logging import logging
import logging.config import logging.config
import shutil import shutil
@ -53,12 +54,9 @@ Hopefully there is a better way to do this.
if(command == 'update_schedule'): if(command == 'update_schedule'):
SCHEDULE_PUSH_MSG = m['schedule'] SCHEDULE_PUSH_MSG = m['schedule']
elif (command == 'update_timezone'):
logger.info("Setting timezone to %s", m['timezone'])
os.environ['TZ'] = m['timezone']
time.tzset()
elif (command == 'update_stream_setting'): elif (command == 'update_stream_setting'):
logger.info("Updating stream setting: %s", m['setting']) logger.info("Updating stream setting: %s", m['setting'])
# ACK the message to take it off the queue # ACK the message to take it off the queue
message.ack()""" message.ack()"""
@ -104,10 +102,6 @@ class PypoFetch(Thread):
if(command == 'update_schedule'): if(command == 'update_schedule'):
self.schedule_data = m['schedule'] self.schedule_data = m['schedule']
self.process_schedule(self.schedule_data, "scheduler", False) self.process_schedule(self.schedule_data, "scheduler", False)
elif (command == 'update_timezone'):
logger.info("Setting timezone to %s", m['timezone'])
os.environ['TZ'] = m['timezone']
time.tzset()
elif (command == 'update_stream_setting'): elif (command == 'update_stream_setting'):
logger.info("Updating stream setting...") logger.info("Updating stream setting...")
self.regenerateLiquidsoapConf(m['setting']) self.regenerateLiquidsoapConf(m['setting'])
@ -212,20 +206,6 @@ class PypoFetch(Thread):
self.cache_dir = config["cache_dir"] + self.export_source + '/' self.cache_dir = config["cache_dir"] + self.export_source + '/'
logger.info("Creating cache directory at %s", self.cache_dir) logger.info("Creating cache directory at %s", self.cache_dir)
def check_matching_timezones(self, server_timezone):
logger = logging.getLogger('fetch')
process = Popen(["date", "+%z"], stdout=PIPE)
pypo_timezone = (process.communicate()[0]).strip(' \r\n\t')
if server_timezone != pypo_timezone:
logger.error("ERROR: Airtime server and pypo timezone offsets do not match. Audio playback will not start when expected!!!")
logger.error(" * Server timezone offset: %s", server_timezone)
logger.error(" * Pypo timezone offset: %s", pypo_timezone)
logger.error(" * To fix this, you need to set the 'date.timezone' value in your php.ini file and restart apache.")
logger.error(" * See this page for more info (v1.7): http://wiki.sourcefabric.org/x/BQBF")
logger.error(" * and also the 'FAQ and Support' page underneath it.")
""" """
def get_currently_scheduled(self, playlistsOrMedias, str_tnow_s): def get_currently_scheduled(self, playlistsOrMedias, str_tnow_s):
for key in playlistsOrMedias: for key in playlistsOrMedias:
@ -274,12 +254,6 @@ class PypoFetch(Thread):
logger = logging.getLogger('fetch') logger = logging.getLogger('fetch')
playlists = schedule_data["playlists"] playlists = schedule_data["playlists"]
#if bootstrapping:
#TODO: possible allow prepare_playlists to handle this.
#self.handle_shows_currently_scheduled(playlists)
self.check_matching_timezones(schedule_data["server_timezone"])
# Push stream metadata to liquidsoap # Push stream metadata to liquidsoap
# TODO: THIS LIQUIDSOAP STUFF NEEDS TO BE MOVED TO PYPO-PUSH!!! # TODO: THIS LIQUIDSOAP STUFF NEEDS TO BE MOVED TO PYPO-PUSH!!!
stream_metadata = schedule_data['stream_metadata'] stream_metadata = schedule_data['stream_metadata']
@ -465,7 +439,7 @@ class PypoFetch(Thread):
for r, d, f in os.walk(self.cache_dir): for r, d, f in os.walk(self.cache_dir):
for dir in d: for dir in d:
try: try:
timestamp = time.mktime(time.strptime(dir, "%Y-%m-%d-%H-%M-%S")) timestamp = calendar.timegm(time.strptime(dir, "%Y-%m-%d-%H-%M-%S"))
if (now - timestamp) > offset: if (now - timestamp) > offset:
try: try:
logger.debug('trying to remove %s - timestamp: %s', os.path.join(r, dir), timestamp) logger.debug('trying to remove %s - timestamp: %s', os.path.join(r, dir), timestamp)

View file

@ -85,23 +85,19 @@ class PypoPush(Thread):
playedItems = self.load_schedule_tracker() playedItems = self.load_schedule_tracker()
timenow = time.time() timenow = time.time()
tcoming = time.localtime(timenow + self.push_ahead) tcoming = time.gmtime(timenow + self.push_ahead)
str_tcoming_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tcoming[0], tcoming[1], tcoming[2], tcoming[3], tcoming[4], tcoming[5]) str_tcoming_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tcoming[0], tcoming[1], tcoming[2], tcoming[3], tcoming[4], tcoming[5])
tcoming2 = time.localtime(timenow + self.push_ahead2) tcoming2 = time.gmtime(timenow + self.push_ahead2)
str_tcoming2_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tcoming2[0], tcoming2[1], tcoming2[2], tcoming2[3], tcoming2[4], tcoming2[5]) str_tcoming2_s = "%04d-%02d-%02d-%02d-%02d-%02d" % (tcoming2[0], tcoming2[1], tcoming2[2], tcoming2[3], tcoming2[4], tcoming2[5])
tnow = time.localtime(timenow) tnow = time.gmtime(timenow)
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])
for pkey in schedule: for pkey in schedule:
plstart = schedule[pkey]['start'][0:19] plstart = schedule[pkey]['start'][0:19]
#plstart = pkey[0:19]
#playedFlag = (pkey in playedItems) and playedItems[pkey].get("played", 0) if plstart == str_tcoming_s or (plstart < str_tcoming_s and plstart > str_tcoming2_s):
playedFlag = False
if plstart == str_tcoming_s or (plstart < str_tcoming_s and plstart > str_tcoming2_s and not playedFlag):
logger.debug('Preparing to push playlist scheduled at: %s', pkey) logger.debug('Preparing to push playlist scheduled at: %s', pkey)
playlist = schedule[pkey] playlist = schedule[pkey]
@ -156,7 +152,7 @@ class PypoPush(Thread):
#mktime takes a time_struct and returns a floating point #mktime takes a time_struct and returns a floating point
#gmtime Convert a time expressed in seconds since the epoch to a struct_time in UTC #gmtime Convert a time expressed in seconds since the epoch to a struct_time in UTC
#mktime: expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). #mktime: expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time().
epoch_start = calendar.timegm(time.gmtime(time.mktime(time.strptime(pkey, '%Y-%m-%d-%H-%M-%S')))) epoch_start = calendar.timegm(time.strptime(pkey, '%Y-%m-%d-%H-%M-%S'))
#Return the time as a floating point number expressed in seconds since the epoch, in UTC. #Return the time as a floating point number expressed in seconds since the epoch, in UTC.
epoch_now = time.time() epoch_now = time.time()

View file

@ -42,12 +42,14 @@ except Exception, e:
sys.exit() sys.exit()
def getDateTimeObj(time): def getDateTimeObj(time):
timeinfo = time.split(" ") timeinfo = time.split(" ")
date = timeinfo[0].split("-") date = timeinfo[0].split("-")
time = timeinfo[1].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])) date = map(int, date)
time = map(int, time)
return datetime.datetime(date[0], date[1], date[2], time[0], time[1], time[2], 0, None)
class ShowRecorder(Thread): class ShowRecorder(Thread):
@ -168,7 +170,7 @@ class CommandListener(Thread):
self.logger = logging.getLogger('root') self.logger = logging.getLogger('root')
self.sr = None self.sr = None
self.current_schedule = {} self.current_schedule = {}
self.shows_to_record = [] self.shows_to_record = {}
self.time_till_next_show = 3600 self.time_till_next_show = 3600
self.logger.info("RecorderFetch: init complete") self.logger.info("RecorderFetch: init complete")
@ -213,7 +215,6 @@ class CommandListener(Thread):
time_delta = show_end - show_starts time_delta = show_end - show_starts
self.shows_to_record[show[u'starts']] = [time_delta, show[u'instance_id'], show[u'name']] self.shows_to_record[show[u'starts']] = [time_delta, show[u'instance_id'], show[u'name']]
delta = self.get_time_till_next_show() delta = self.get_time_till_next_show()
# awake at least 5 seconds prior to the show start # awake at least 5 seconds prior to the show start
self.time_till_next_show = delta - 5 self.time_till_next_show = delta - 5
@ -222,7 +223,7 @@ class CommandListener(Thread):
def get_time_till_next_show(self): def get_time_till_next_show(self):
if len(self.shows_to_record) != 0: if len(self.shows_to_record) != 0:
tnow = datetime.datetime.now() tnow = datetime.datetime.utcnow()
sorted_show_keys = sorted(self.shows_to_record.keys()) sorted_show_keys = sorted(self.shows_to_record.keys())
start_time = sorted_show_keys[0] start_time = sorted_show_keys[0]