public static function GetNextItem($p_timeNow) { //get previous show and previous item in the schedule table. //Compare the two and if the last show was recorded and started //after the last item in the schedule table, then return the show's //name. Else return the last item from the schedule. $showInstance = Application_Model_ShowInstance::GetNextShowInstance($p_timeNow); $row = Application_Model_Schedule::GetNextScheduleItem($p_timeNow); if (is_null($showInstance)) { if (count($row) == 0) { return null; } else { return array("name" => $row[0]["artist_name"] . " - " . $row[0]["track_title"], "starts" => $row[0]["starts"], "ends" => $row[0]["ends"]); } } else { if (count($row) == 0) { if ($showInstance->isRecorded()) { //last item is a show instance return array("name" => $showInstance->getName(), "starts" => $showInstance->getShowInstanceStart(), "ends" => $showInstance->getShowInstanceEnd()); } else { return null; } } else { //return the one that starts sooner. if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()) { return array("name" => $row[0]["artist_name"] . " - " . $row[0]["track_title"], "starts" => $row[0]["starts"], "ends" => $row[0]["ends"]); } else { return array("name" => $showInstance->getName(), "starts" => $showInstance->getShowInstanceStart(), "ends" => $showInstance->getShowInstanceEnd()); } } } }
public function dispatchLoopShutdown() { if (Application_Model_RabbitMq::$doPush) { $md = array('schedule' => Application_Model_Schedule::getSchedule()); Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md); if (!isset($_SERVER['AIRTIME_SRV'])) { Application_Model_RabbitMq::SendMessageToShowRecorder("update_recorder_schedule"); } } if (memory_get_peak_usage() > 30 * pow(2, 20)) { Logging::debug("Peak memory usage: " . memory_get_peak_usage() / 1000000 . " MB while accessing URI " . $_SERVER['REQUEST_URI']); Logging::debug("Should try to keep memory footprint under 25 MB"); } }
function testIsScheduleEmptyInRange() { $i = new Application_Model_ScheduleGroup(); $this->groupIdCreated = $i->add('2011-10-10 01:30:23', $this->storedFile->getId()); if (Application_Model_Schedule::isScheduleEmptyInRange('2011-10-10 01:30:23', '00:00:12.555')) { $this->fail("Reporting empty schedule when it isnt."); return; } // echo "groupid: ".$this->groupIdCreated."\n"; $success = $i->remove(); if ($success === false) { $this->fail("Failed to delete schedule group."); return; } if (!Application_Model_Schedule::isScheduleEmptyInRange('2011-10-10 01:30:23', '00:00:12.555')) { $this->fail("Reporting booked schedule when it isnt."); return; } }
public function notifyMediaItemStartPlayAction() { // disable the view and the layout $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $media_id = $this->_getParam("media_id"); Logging::debug("Received notification of new media item start: {$media_id}"); Application_Model_Schedule::UpdateMediaPlayedStatus($media_id); //set a 'last played' timestamp for media item //needed for smart blocks try { $mediaType = Application_Model_Schedule::GetType($media_id); if ($mediaType == 'file') { $file_id = Application_Model_Schedule::GetFileId($media_id); if (!is_null($file_id)) { //we are dealing with a file not a stream $file = Application_Model_StoredFile::Recall($file_id); $now = new DateTime("now", new DateTimeZone("UTC")); $file->setLastPlayedTime($now); } } else { // webstream $stream_id = Application_Model_Schedule::GetStreamId($media_id); if (!is_null($stream_id)) { $webStream = new Application_Model_Webstream($stream_id); $now = new DateTime("now", new DateTimeZone("UTC")); $webStream->setLastPlayed($now); } } } catch (Exception $e) { Logging::info($e); } echo json_encode(array("status" => 1, "message" => "")); }
public function getItems() { $current_id = -1; $display_items = array(); $shows = array(); $showInstance = array(); if ($this->opts["myShows"] === 1) { $shows = $this->getUsersShows(); } elseif ($this->opts["showFilter"] !== 0) { $shows[] = $this->opts["showFilter"]; } elseif ($this->opts["showInstanceFilter"] !== 0) { $showInstance[] = $this->opts["showInstanceFilter"]; } $scheduled_items = Application_Model_Schedule::GetScheduleDetailItems($this->startDT, $this->endDT, $shows, $showInstance); for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) { $item = $scheduled_items[$i]; //don't send back data for filler rows. if (isset($item["playout_status"]) && $item["playout_status"] < 0) { continue; } //make a header row. if ($current_id !== $item["si_id"]) { //make a footer row. if ($current_id !== -1) { // pass in the previous row as it's the last row for // the previous show. $display_items[] = $this->makeFooterRow($scheduled_items[$i - 1]); } $display_items[] = $this->makeHeaderRow($item); $current_id = $item["si_id"]; $this->pos = 1; } //make a normal data row. $row = $this->makeScheduledItemRow($item); //don't display the empty rows. if (isset($row)) { $display_items[] = $row; } if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) { $this->showInstances[] = $current_id; } } //make the last footer if there were any scheduled items. if (count($scheduled_items) > 0) { $display_items[] = $this->makeFooterRow($scheduled_items[count($scheduled_items) - 1]); } return array("schedule" => $display_items, "showInstances" => $this->showInstances); }
public function getCurrentPlaylistAction() { $range = Application_Model_Schedule::GetPlayOrderRange(); $show = Application_Model_Show::getCurrentShow(); /* Convert all UTC times to localtime before sending back to user. */ $range["schedulerTime"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["schedulerTime"]); if (isset($range["previous"])) { $range["previous"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["previous"]["starts"]); $range["previous"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["previous"]["ends"]); } if (isset($range["current"])) { $range["current"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["current"]["starts"]); $range["current"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["current"]["ends"]); } if (isset($range["next"])) { $range["next"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["next"]["starts"]); $range["next"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["next"]["ends"]); } Application_Common_DateHelper::convertTimestamps($range["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp"), "user"); Application_Common_DateHelper::convertTimestamps($range["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp"), "user"); //TODO: Add timezone and timezoneOffset back into the ApiController's results. $range["timezone"] = Application_Common_DateHelper::getUserTimezoneAbbreviation(); $range["timezoneOffset"] = Application_Common_DateHelper::getUserTimezoneOffset(); $source_status = array(); $switch_status = array(); $live_dj = Application_Model_Preference::GetSourceStatus("live_dj"); $master_dj = Application_Model_Preference::GetSourceStatus("master_dj"); $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play"); $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj"); $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj"); //might not be the correct place to implement this but for now let's just do it here $source_status['live_dj_source'] = $live_dj; $source_status['master_dj_source'] = $master_dj; $this->view->source_status = $source_status; $switch_status['live_dj_source'] = $live_dj_switch; $switch_status['master_dj_source'] = $master_dj_switch; $switch_status['scheduled_play'] = $scheduled_play_switch; $this->view->switch_status = $switch_status; $this->view->entries = $range; $this->view->show_name = isset($show[0]) ? $show[0]["name"] : ""; }
public function resizeShow($deltaDay, $deltaMin, $instanceId) { $con = Propel::getConnection(); if ($deltaDay > 0) { return _("Shows can have a max length of 24 hours."); } $utcTimezone = new DateTimeZone("UTC"); $nowDateTime = new DateTime("now", $utcTimezone); //keep track of cc_show_day entries we need to update $showDayIds = array(); /* * If the resized show is an edited instance of a repeating show we * need to treat it as a separate show and not resize the other instances * * Also, if the resized show has edited instances, we need to exclude * those from the resize */ $ccShow = CcShowQuery::create()->findPk($this->_showId); if ($ccShow->isRepeating()) { //convert instance to local timezone $ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); $startsDT = $ccShowInstance->getDbStarts(null); $timezone = $ccShow->getFirstCcShowDay()->getDbTimezone(); $startsDT->setTimezone(new DateTimeZone($timezone)); /* Get cc_show_day for the current instance. If we don't find one * we know it is a repeat interval of one of cc_show_days first * show and we can assume we aren't resizing a modified instance */ $ccShowDay = CcShowDaysQuery::create()->filterByDbFirstShow($startsDT->format("Y-m-d"))->filterByDbStartTime($startsDT->format("H:i:s"))->filterByDbShowId($this->_showId)->findOne(); /* Check if this cc_show_day rule is non-repeating. If it is, then * we know this instance was edited out of the repeating sequence */ if (!$ccShowDay || $ccShowDay->getDbRepeatType() != -1) { $ccShowDays = $ccShow->getRepeatingCcShowDays(); foreach ($ccShowDays as $day) { array_push($showDayIds, $day->getDbId()); } $excludeIds = $ccShow->getEditedRepeatingInstanceIds(); //exlcude edited instances from resize $showInstances = CcShowInstancesQuery::create()->filterByDbShowId($this->_showId)->filterByDbModifiedInstance(false)->filterByDbId($excludeIds, criteria::NOT_IN)->find(); } elseif ($ccShowDay->getDbRepeatType() == -1) { array_push($showDayIds, $ccShowDay->getDbId()); //treat edited instance as separate show for resize $showInstances = CcShowInstancesQuery::create()->filterByDbId($instanceId)->find(); } } else { $ccShowDays = $ccShow->getCcShowDayss(); foreach ($ccShowDays as $day) { array_push($showDayIds, $day->getDbId()); } $showInstances = CcShowInstancesQuery::create()->filterByDbShowId($this->_showId)->find($con); } /* Check two things: 1. If the show being resized and any of its repeats end in the past 2. If the show being resized and any of its repeats overlap with other scheduled shows */ //keep track of instance ids for update show instances start/end times $instanceIds = array(); $displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone()); //check if new show time overlaps with any other shows foreach ($showInstances as $si) { array_push($instanceIds, $si->getDbId()); $startsDateTime = $si->getDbStarts(null); $endsDateTime = $si->getDbEnds(null); /* The user is moving the show on the calendar from the perspective of local time. * incase a show is moved across a time change border offsets should be added to the local * timestamp and then converted back to UTC to avoid show time changes */ $startsDateTime->setTimezone($displayTimezone); $endsDateTime->setTimezone($displayTimezone); //$newStartsDateTime = Application_Model_ShowInstance::addDeltas($startsDateTime, $deltaDay, $deltaMin); $newEndsDateTime = Application_Model_ShowInstance::addDeltas($endsDateTime, $deltaDay, $deltaMin); if ($newEndsDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { return _("End date/time cannot be in the past"); } //convert our new starts/ends to UTC. //$newStartsDateTime->setTimezone($utc); $newEndsDateTime->setTimezone($utcTimezone); $overlapping = Application_Model_Schedule::checkOverlappingShows($startsDateTime, $newEndsDateTime, true, $si->getDbId()); if ($overlapping) { return _("Cannot schedule overlapping shows.\nNote: Resizing a repeating show " . "affects all of its repeats."); } } $hours = $deltaMin / 60; $hours = $hours > 0 ? floor($hours) : ceil($hours); $mins = abs($deltaMin % 60); $sql_gen = "UPDATE cc_show_instances " . "SET ends = (ends + :deltaDay1::INTERVAL + :interval1::INTERVAL) " . "WHERE (id IN (" . implode($instanceIds, ",") . ") " . "AND ends > :current_timestamp1) " . "AND ((ends + :deltaDay2::INTERVAL + :interval2::INTERVAL - starts) <= interval '24:00')"; Application_Common_Database::prepareAndExecute($sql_gen, array(':deltaDay1' => "{$deltaDay} days", ':interval1' => "{$hours}:{$mins}", ':current_timestamp1' => $nowDateTime->format("Y-m-d H:i:s"), ':deltaDay2' => "{$deltaDay} days", ':interval2' => "{$hours}:{$mins}"), "execute"); $sql_gen = "UPDATE cc_show_days " . "SET duration = (CAST(duration AS interval) + :deltaDay3::INTERVAL + :interval3::INTERVAL) " . "WHERE id IN (" . implode($showDayIds, ",") . ") " . "AND ((CAST(duration AS interval) + :deltaDay4::INTERVAL + :interval4::INTERVAL) <= interval '24:00')"; Application_Common_Database::prepareAndExecute($sql_gen, array(':deltaDay3' => "{$deltaDay} days", ':interval3' => "{$hours}:{$mins}", ':deltaDay4' => "{$deltaDay} days", ':interval4' => "{$hours}:{$mins}"), "execute"); $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $con->beginTransaction(); try { //update the status flag in cc_schedule. /* Since we didn't use a propel object when updating * cc_show_instances table we need to clear the instances * so the correct information is retrieved from the db */ CcShowInstancesPeer::clearInstancePool(); $instances = CcShowInstancesQuery::create()->filterByDbEnds($nowDateTime->format("Y-m-d H:i:s"), Criteria::GREATER_THAN)->filterByDbId($instanceIds, Criteria::IN)->find($con); foreach ($instances as $instance) { $instance->updateScheduleStatus($con); } $con->commit(); } catch (Exception $e) { $con->rollback(); Logging::info("Couldn't update schedule status."); Logging::info($e->getMessage()); } Application_Model_RabbitMq::PushSchedule(); }
private static function getRangeStartAndEnd($p_fromDateTime, $p_toDateTime) { $CC_CONFIG = Config::getConfig(); $utcTimeZone = new DateTimeZone('UTC'); /* if $p_fromDateTime and $p_toDateTime function parameters are null, then set range * from "now" to "now + 24 hours". */ if (is_null($p_fromDateTime)) { $t1 = new DateTime("@" . time(), $utcTimeZone); $range_start = $t1->format("Y-m-d H:i:s"); } else { $range_start = Application_Model_Schedule::PypoTimeToAirtimeTime($p_fromDateTime); } if (is_null($p_fromDateTime)) { $t2 = new DateTime("@" . time(), $utcTimeZone); $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"]; if (is_numeric($cache_ahead_hours)) { //make sure we are not dealing with a float $cache_ahead_hours = intval($cache_ahead_hours); } else { $cache_ahead_hours = 1; } $t2->add(new DateInterval("PT" . $cache_ahead_hours . "H")); $range_end = $t2->format("Y-m-d H:i:s"); } else { $range_end = Application_Model_Schedule::PypoTimeToAirtimeTime($p_toDateTime); } return array($range_start, $range_end); }
public static function SetNewLogTime($state, $dateTime) { try { $scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); if ($state == 'L' && $scheduled == 'on') { self::SetEndTime('S', $dateTime); } /* Only insert new state if last log * has ended */ $sql_select = "SELECT max(id) from CC_LIVE_LOG" . " WHERE (state= :state1 and end_time is NULL) or (state= :state2 and end_time is NULL)"; $params = array(":state1" => 'L', ":state2" => 'S'); $id = Application_Common_Database::prepareAndExecute($sql_select, $params, Application_Common_Database::COLUMN); if ($id == null) { $sql_insert = "INSERT INTO CC_LIVE_LOG (state, start_time)" . " VALUES (:state, :start)"; $params = array(':state' => $state, ':start' => $dateTime->format("Y-m-d H:i:s")); Application_Common_Database::prepareAndExecute($sql_insert, $params, Application_Common_Database::EXECUTE); if ($state == "S") { // if scheduled play source is getting broadcasted Application_Model_Schedule::UpdateBrodcastedStatus($dateTime, 1); } } } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); Logging::info("SetNewLogTime - Could not connect to database."); exit; } }
public static function setIsScheduled($p_webstreamId, $p_status) { $webstream = CcWebstreamQuery::create()->findPK($p_webstreamId); $updateIsScheduled = false; if (isset($webstream) && !in_array($p_webstreamId, Application_Model_Schedule::getAllFutureScheduledWebstreams())) { //$webstream->setDbIsScheduled($p_status)->save(); $updateIsScheduled = true; } return $updateIsScheduled; }
public function addShowAction() { $js = $this->_getParam('data'); $data = array(); //need to convert from serialized jQuery array. foreach ($js as $j) { $data[$j["name"]] = $j["value"]; } $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); if ($data['add_show_day_check'] == "") { $data['add_show_day_check'] = null; } $validateStartDate = true; $success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate); if ($success) { $this->view->addNewShow = true; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); Logging::debug("Show creation succeeded"); } else { $this->view->addNewShow = true; $this->view->form = $this->view->render('schedule/add-show-form.phtml'); Logging::debug("Show creation failed"); } }
public function emptyShowContent($instanceId) { try { $ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); $instances = array(); $instanceIds = array(); if ($ccShowInstance->getCcShow()->isLinked()) { foreach ($ccShowInstance->getCcShow()->getCcShowInstancess() as $instance) { $instanceIds[] = $instance->getDbId(); $instances[] = $instance; } } else { $instanceIds[] = $ccShowInstance->getDbId(); $instances[] = $ccShowInstance; } /* Get the file ids of the tracks we are about to delete * from cc_schedule. We need these so we can update the * is_scheduled flag in cc_files */ $ccSchedules = CcScheduleQuery::create()->filterByDbInstanceId($instanceIds, Criteria::IN)->setDistinct(CcSchedulePeer::FILE_ID)->find(); $fileIds = array(); foreach ($ccSchedules as $ccSchedule) { $fileIds[] = $ccSchedule->getDbFileId(); } /* Clear out the schedule */ CcScheduleQuery::create()->filterByDbInstanceId($instanceIds, Criteria::IN)->delete(); /* Now that the schedule has been cleared we need to make * sure we do not update the is_scheduled flag for tracks * that are scheduled in other shows */ $futureScheduledFiles = Application_Model_Schedule::getAllFutureScheduledFiles(); foreach ($fileIds as $k => $v) { if (in_array($v, $futureScheduledFiles)) { unset($fileIds[$k]); } } $selectCriteria = new Criteria(); $selectCriteria->add(CcFilesPeer::ID, $fileIds, Criteria::IN); $updateCriteria = new Criteria(); $updateCriteria->add(CcFilesPeer::IS_SCHEDULED, false); BasePeer::doUpdate($selectCriteria, $updateCriteria, Propel::getConnection()); Application_Model_RabbitMq::PushSchedule(); $con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME); foreach ($instances as $instance) { $instance->updateDbTimeFilled($con); } return true; } catch (Exception $e) { Logging::info($e->getMessage()); return false; } }
public function testExport() { echo Application_Model_Schedule::ExportRangeAsJson("2010-01-01 00:00:00", "2011-01-01 00:00:00"); }
public function removeItems($scheduledItems, $adjustSched = true, $cancelShow = false) { $showInstances = array(); $this->con->beginTransaction(); try { $this->validateRequest($scheduledItems); $scheduledIds = array(); foreach ($scheduledItems as $item) { $scheduledIds[] = $item["id"]; } $removedItems = CcScheduleQuery::create()->findPks($scheduledIds); //check to make sure all items selected are up to date foreach ($removedItems as $removedItem) { $instance = $removedItem->getCcShowInstances($this->con); //check if instance is linked and if so get the schedule items //for all linked instances so we can delete them too if (!$cancelShow && $instance->getCcShow()->isLinked()) { //returns all linked instances if linked $ccShowInstances = $this->getInstances($instance->getDbId()); $instanceIds = array(); foreach ($ccShowInstances as $ccShowInstance) { $instanceIds[] = $ccShowInstance->getDbId(); } /* * Find all the schedule items that are in the same position * as the selected item by the user. * The position of each track is the same across each linked instance */ $itemsToDelete = CcScheduleQuery::create()->filterByDbPosition($removedItem->getDbPosition())->filterByDbInstanceId($instanceIds, Criteria::IN)->find(); foreach ($itemsToDelete as $item) { if (!$removedItems->contains($item)) { $removedItems->append($item); } } } //check to truncate the currently playing item instead of deleting it. if ($removedItem->isCurrentItem($this->epochNow)) { $nEpoch = $this->epochNow; $sEpoch = $removedItem->getDbStarts('U.u'); $length = bcsub($nEpoch, $sEpoch, 6); $cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length); $cueinSec = Application_Common_DateHelper::playlistTimeToSeconds($removedItem->getDbCueIn()); $cueOutSec = bcadd($cueinSec, $length, 6); $cueout = Application_Common_DateHelper::secondsToPlaylistTime($cueOutSec); //Set DbEnds - 1 second because otherwise there can be a timing issue //when sending the new schedule to Pypo where Pypo thinks the track is still //playing. $removedItem->setDbCueOut($cueout)->setDbClipLength($cliplength)->setDbEnds($this->nowDT)->save($this->con); } else { $removedItem->delete($this->con); } // update is_scheduled in cc_files but only if // the file is not scheduled somewhere else $fileId = $removedItem->getDbFileId(); // check if the removed item is scheduled somewhere else $futureScheduledFiles = Application_Model_Schedule::getAllFutureScheduledFiles(); if (!is_null($fileId) && !in_array($fileId, $futureScheduledFiles)) { $db_file = CcFilesQuery::create()->findPk($fileId, $this->con); $db_file->setDbIsScheduled(false)->save($this->con); } } if ($adjustSched === true) { //get the show instances of the shows we must adjust times for. foreach ($removedItems as $item) { $instance = $item->getDBInstanceId(); if (!in_array($instance, $showInstances)) { $showInstances[] = $instance; } } foreach ($showInstances as $instance) { $this->removeGaps($instance); $this->calculateCrossfades($instance); } } //update the status flag in cc_schedule. $instances = CcShowInstancesQuery::create()->filterByPrimaryKeys($showInstances)->find($this->con); foreach ($instances as $instance) { $instance->updateScheduleStatus($this->con); $instance->correctSchedulePositions(); } //update the last scheduled timestamp. CcShowInstancesQuery::create()->filterByPrimaryKeys($showInstances)->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con); $this->con->commit(); Application_Model_RabbitMq::PushSchedule(); } catch (Exception $e) { $this->con->rollback(); throw $e; } }
/** * Calculates the percentage of a show scheduled given the start and end times in date/time format * and the time_filled as the total time the schow is scheduled for in time format. **/ private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled) { $durationSeconds = strtotime($p_ends) - strtotime($p_starts); $time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000; $percent = ceil($time_filled / $durationSeconds * 100); return $percent; }
public static function SetNewLogTime($state, $dateTime) { try { $con = Propel::getConnection(); $scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); if ($state == 'L' && $scheduled == 'on') { self::SetEndTime('S', $dateTime); } /* Only insert new state if last log * has ended */ $sql_select = "SELECT max(id) from CC_LIVE_LOG" . " WHERE (state='L' and end_time is NULL) or (state='S' and end_time is NULL)"; $id = $con->query($sql_select)->fetchColumn(0); if ($id == null) { $sql_insert = "INSERT INTO CC_LIVE_LOG (state, start_time)" . " VALUES ('{$state}', '{$dateTime->format("Y-m-d H:i:s")}')"; $con->exec($sql_insert); if ($state == "S") { // if scheduled play source is getting broadcasted Application_Model_Schedule::UpdateBrodcastedStatus($dateTime, 1); } } } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); Logging::info("SetNewLogTime - Could not connect to database."); exit; } }
public function notifyMediaItemStartPlayAction() { $media_id = $this->_getParam("media_id"); Logging::debug("Received notification of new media item start: {$media_id}"); Application_Model_Schedule::UpdateMediaPlayedStatus($media_id); $historyService = new Application_Service_HistoryService(); $historyService->insertPlayedItem($media_id); //set a 'last played' timestamp for media item //needed for smart blocks try { $mediaType = Application_Model_Schedule::GetType($media_id); if ($mediaType == 'file') { $file_id = Application_Model_Schedule::GetFileId($media_id); if (!is_null($file_id)) { //we are dealing with a file not a stream $file = Application_Model_StoredFile::RecallById($file_id); $now = new DateTime("now", new DateTimeZone("UTC")); $file->setLastPlayedTime($now); } } else { // webstream $stream_id = Application_Model_Schedule::GetStreamId($media_id); if (!is_null($stream_id)) { $webStream = new Application_Model_Webstream($stream_id); $now = new DateTime("now", new DateTimeZone("UTC")); $webStream->setLastPlayed($now); } } } catch (Exception $e) { Logging::info($e); } $this->_helper->json->sendJson(array("status" => 1, "message" => "")); }
$instances = Application_Model_Show::getShows($showTime, $showTime); $instance = array_pop($instances); $show = new Application_Model_ShowInstance($instance["instance_id"]); //echo "Adding playlist to show instance ".$show->getShowInstanceId()."\n"; $show->scheduleShow(array(1)); //echo "done\n"; //$show->scheduleShow(array($playlist->getId())); } $showTime = new DateTime(); $resolution = "hour"; $showNumber = 1; $numberOfDays = 180; $numberOfHours = 0; $endDate = new DateTime(); $endDate->add(new DateInterval("P" . $numberOfDays . "DT" . $numberOfHours . "H")); echo "End date: " . $endDate->format("Y-m-d H:i") . "\n"; while ($showTime < $endDate) { echo $showTime->format("Y-m-d H:i") . " < " . $endDate->format("Y-m-d H:i") . "\n"; if ($resolution == "minute") { createTestShow($showNumber, $showTime, "0:01"); $showTime->add(new DateInterval("PT1M")); } elseif ($resolution == "hour") { createTestShow($showNumber, $showTime); $showTime->add(new DateInterval("PT1H")); } $showNumber = $showNumber + 1; } if (Application_Model_RabbitMq::$doPush) { $md = array('schedule' => Application_Model_Schedule::getSchedule()); Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md); }
public function checkRebroadcastDates($repeatShowStart, $formData, $hours, $minutes, $showEdit = false) { $overlapping = false; for ($i = 1; $i <= 10; $i++) { if (empty($formData["add_show_rebroadcast_date_" . $i])) { break; } $rebroadcastShowStart = clone $repeatShowStart; /* formData is in local time so we need to set the * show start back to local time */ $rebroadcastShowStart->setTimezone(new DateTimeZone($formData["add_show_timezone"])); $rebroadcastWhenDays = explode(" ", $formData["add_show_rebroadcast_date_" . $i]); $rebroadcastWhenTime = explode(":", $formData["add_show_rebroadcast_time_" . $i]); $rebroadcastShowStart->add(new DateInterval("P" . $rebroadcastWhenDays[0] . "D")); $rebroadcastShowStart->setTime($rebroadcastWhenTime[0], $rebroadcastWhenTime[1]); $rebroadcastShowStart->setTimezone(new DateTimeZone('UTC')); $rebroadcastShowEnd = clone $rebroadcastShowStart; $rebroadcastShowEnd->add(new DateInterval("PT" . $hours . "H" . $minutes . "M")); if ($showEdit) { $overlapping = Application_Model_Schedule::checkOverlappingShows($rebroadcastShowStart, $rebroadcastShowEnd, true, null, $formData['add_show_id']); } else { $overlapping = Application_Model_Schedule::checkOverlappingShows($rebroadcastShowStart, $rebroadcastShowEnd); } if ($overlapping) { break; } } return $overlapping; }
private function validateShowMove($deltaDay, $deltaMin) { if (!$this->currentUser->isAdminOrPM()) { throw new Exception(_("Permission denied")); } if ($this->ccShow->isRepeating()) { throw new Exception(_("Can't drag and drop repeating shows")); } $today_timestamp = time(); $startsDateTime = $this->ccShowInstance->getDbStarts(null); $endsDateTime = $this->ccShowInstance->getDbEnds(null); if ($today_timestamp > $startsDateTime->getTimestamp()) { throw new Exception(_("Can't move a past show")); } //the user is moving the show on the calendar from the perspective of local time. //incase a show is moved across a time change border offsets should be added to the localtime //stamp and then converted back to UTC to avoid show time changes! $showTimezone = $this->ccShow->getFirstCcShowDay()->getDbTimezone(); $startsDateTime->setTimezone(new DateTimeZone($showTimezone)); $endsDateTime->setTimezone(new DateTimeZone($showTimezone)); $duration = $startsDateTime->diff($endsDateTime); $newStartsDateTime = self::addDeltas($startsDateTime, $deltaDay, $deltaMin); /* WARNING: Do not separately add a time delta to the start and end times because that does not preserve the duration across a DST time change. For example, 5am - 3 hours = 3am when DST occurs at 2am. BUT, 6am - 3 hours = 3am also! So when a DST change occurs, adding the deltas like this separately does not conserve the duration of a show. Since that's what we want (otherwise we'll get a zero length show), we calculate the show duration FIRST, then we just add that on to the start time to calculate the end time. This is a safer approach. The key lesson here is that in general: duration != end - start ... so be careful! */ //$newEndsDateTime = self::addDeltas($endsDateTime, $deltaDay, $deltaMin); <--- Wrong, don't do it. $newEndsDateTime = clone $newStartsDateTime; $newEndsDateTime = $newEndsDateTime->add($duration); //convert our new starts/ends to UTC. $newStartsDateTime->setTimezone(new DateTimeZone("UTC")); $newEndsDateTime->setTimezone(new DateTimeZone("UTC")); if ($today_timestamp > $newStartsDateTime->getTimestamp()) { throw new Exception(_("Can't move show into past")); } //check if show is overlapping $overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->ccShowInstance->getDbId()); if ($overlapping) { throw new Exception(_("Cannot schedule overlapping shows")); } if ($this->ccShow->isRecorded()) { //rebroadcasts should start at max 1 hour after a recorded show has ended. $minRebroadcastStart = self::addDeltas($newEndsDateTime, 0, 60); //check if we are moving a recorded show less than 1 hour before any of its own rebroadcasts. $rebroadcasts = CcShowInstancesQuery::create()->filterByDbOriginalShow($this->ccShow->getDbId())->filterByDbStarts($minRebroadcastStart->format('Y-m-d H:i:s'), Criteria::LESS_THAN)->find(); if (count($rebroadcasts) > 0) { throw new Exception(_("Can't move a recorded show less than 1 hour before its rebroadcasts.")); } } if ($this->ccShow->isRebroadcast()) { $recordedShow = CcShowInstancesQuery::create()->filterByCcShow($this->ccShowInstance->getDbOriginalShow())->findOne(); if (is_null($recordedShow)) { $this->ccShowInstance->delete(); throw new Exception(_("Show was deleted because recorded show does not exist!")); } $recordEndDateTime = new DateTime($recordedShow->getDbEnds(), new DateTimeZone("UTC")); $newRecordEndDateTime = self::addDeltas($recordEndDateTime, 0, 60); if ($newStartsDateTime->getTimestamp() < $newRecordEndDateTime->getTimestamp()) { throw new Exception(_("Must wait 1 hour to rebroadcast.")); } } return array($newStartsDateTime, $newEndsDateTime); }
public static function GetSystemInfo($returnArray = false, $p_testing = false) { exec('/usr/bin/airtime-check-system --no-color', $output); $output = preg_replace('/\\s+/', ' ', $output); $systemInfoArray = array(); foreach ($output as $key => &$out) { $info = explode('=', $out); if (isset($info[1])) { $key = str_replace(' ', '_', trim($info[0])); $key = strtoupper($key); if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' || $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' || $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' || $key == 'PLAYOUT_ENGINE_CPU_PERC') { if ($key == 'AIRTIME_VERSION') { // remove hash tag on the version string $version = explode('+', $info[1]); $systemInfoArray[$key] = $version[0]; } else { $systemInfoArray[$key] = $info[1]; } } } } $outputArray = array(); $outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing); $outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing); $outputArray['SOUNDCLOUD_ENABLED'] = self::GetUploadToSoundcloudOption(); if ($outputArray['SOUNDCLOUD_ENABLED']) { $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads(); } else { $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL; } $outputArray['STATION_NAME'] = self::GetStationName(); $outputArray['PHONE'] = self::GetPhone(); $outputArray['EMAIL'] = self::GetEmail(); $outputArray['STATION_WEB_SITE'] = self::GetStationWebSite(); $outputArray['STATION_COUNTRY'] = self::GetStationCountry(); $outputArray['STATION_CITY'] = self::GetStationCity(); $outputArray['STATION_DESCRIPTION'] = self::GetStationDescription(); // get web server info if (isset($systemInfoArray["AIRTIME_VERSION_URL"])) { $url = $systemInfoArray["AIRTIME_VERSION_URL"]; $index = strpos($url, '/api/'); $url = substr($url, 0, $index); $headerInfo = get_headers(trim($url), 1); $outputArray['WEB_SERVER'] = $headerInfo['Server'][0]; } $outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount(); $outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount(); $outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount(); $outputArray['NUM_OF_SCHEDULED_PLAYLISTS'] = Application_Model_Schedule::getSchduledPlaylistCount(); $outputArray['NUM_OF_PAST_SHOWS'] = Application_Model_ShowInstance::GetShowInstanceCount(gmdate("Y-m-d H:i:s")); $outputArray['UNIQUE_ID'] = self::GetUniqueId(); $outputArray['SAAS'] = self::GetPlanLevel(); if ($outputArray['SAAS'] != 'disabled') { $outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate(); } else { $outputArray['TRIAL_END_DATE'] = NULL; } $outputArray['INSTALL_METHOD'] = self::GetInstallMethod(); $outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams(); $outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection(); $outputArray = array_merge($systemInfoArray, $outputArray); $outputString = "\n"; foreach ($outputArray as $key => $out) { if ($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')) { continue; } if ($key == "STREAM_INFO") { $outputString .= $key . " :\n"; foreach ($out as $s_info) { foreach ($s_info as $k => $v) { $outputString .= "\t" . strtoupper($k) . " : " . $v . "\n"; } } } elseif ($key == "SOUNDCLOUD_ENABLED") { if ($out) { $outputString .= $key . " : TRUE\n"; } elseif (!$out) { $outputString .= $key . " : FALSE\n"; } } elseif ($key == "SAAS") { if (strcmp($out, 'disabled') != 0) { $outputString .= $key . ' : ' . $out . "\n"; } } else { $outputString .= $key . ' : ' . $out . "\n"; } } if ($returnArray) { $outputArray['PROMOTE'] = self::GetPublicise(); $outputArray['LOGOIMG'] = self::GetStationLogo(); return $outputArray; } else { return $outputString; } }
public static function setIsScheduled($fileId, $status) { $file = self::RecallById($fileId); $updateIsScheduled = false; if (!is_null($fileId) && !in_array($fileId, Application_Model_Schedule::getAllFutureScheduledFiles())) { $file->_file->setDbIsScheduled($status)->save(); $updateIsScheduled = true; } return $updateIsScheduled; }
/** * Delete stored virtual file * * @param boolean $p_deleteFile * */ public function delete($deleteFromPlaylist = false) { $filepath = $this->getFilePath(); // Check if the file is scheduled to be played in the future if (Application_Model_Schedule::IsFileScheduledInTheFuture($this->getId())) { throw new DeleteScheduledFileException(); } $music_dir = Application_Model_MusicDir::getDirByPK($this->_file->getDbDirectory()); $type = $music_dir->getType(); if (file_exists($filepath) && $type == "stor") { $data = array("filepath" => $filepath, "delete" => 1); Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data); } if ($deleteFromPlaylist) { Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId()); } // set file_exists falg to false $this->_file->setDbFileExists(false); $this->_file->save(); }
public function streamSettingAction() { $CC_CONFIG = Config::getConfig(); $request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir(); $this->view->headScript()->appendFile($baseUrl . 'js/airtime/preferences/streamsetting.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); // get current settings $temp = Application_Model_StreamSetting::getStreamSetting(); $setting = array(); foreach ($temp as $t) { $setting[$t['keyname']] = $t['value']; } $name_map = array('ogg' => 'Ogg Vorbis', 'fdkaac' => 'AAC+', 'aac' => 'AAC', 'opus' => 'Opus', 'mp3' => 'MP3'); // get predefined type and bitrate from pref table $temp_types = Application_Model_Preference::GetStreamType(); $stream_types = array(); foreach ($temp_types as $type) { $type = strtolower(trim($type)); if (isset($name_map[$type])) { $name = $name_map[$type]; } else { $name = $type; } $stream_types[$type] = $name; } $temp_bitrate = Application_Model_Preference::GetStreamBitrate(); $max_bitrate = intval(Application_Model_Preference::GetMaxBitrate()); $stream_bitrates = array(); foreach ($temp_bitrate as $type) { if (intval($type) <= $max_bitrate) { $stream_bitrates[trim($type)] = strtoupper(trim($type)) . " kbit/s"; } } $num_of_stream = intval(Application_Model_Preference::GetNumOfStreams()); $form = new Application_Form_StreamSetting(); $form->setSetting($setting); $form->startFrom(); $live_stream_subform = new Application_Form_LiveStreamingPreferences(); $form->addSubForm($live_stream_subform, "live_stream_subform"); for ($i = 1; $i <= $num_of_stream; $i++) { $subform = new Application_Form_StreamSettingSubForm(); $subform->setPrefix($i); $subform->setSetting($setting); $subform->setStreamTypes($stream_types); $subform->setStreamBitrates($stream_bitrates); $subform->startForm(); $form->addSubForm($subform, "s" . $i . "_subform"); } if ($request->isPost()) { $params = $request->getPost(); /* Parse through post data and put in format * $form->isValid() is expecting it in */ $postData = explode('&', $params['data']); $s1_data = array(); $s2_data = array(); $s3_data = array(); $values = array(); foreach ($postData as $k => $v) { $v = explode('=', urldecode($v)); if (strpos($v[0], "s1_data") !== false) { /* In this case $v[0] may be 's1_data[enable]' , for example. * We only want the 'enable' part */ preg_match('/\\[(.*)\\]/', $v[0], $matches); $s1_data[$matches[1]] = $v[1]; } elseif (strpos($v[0], "s2_data") !== false) { preg_match('/\\[(.*)\\]/', $v[0], $matches); $s2_data[$matches[1]] = $v[1]; } elseif (strpos($v[0], "s3_data") !== false) { preg_match('/\\[(.*)\\]/', $v[0], $matches); $s3_data[$matches[1]] = $v[1]; } else { $values[$v[0]] = $v[1]; } } $values["s1_data"] = $s1_data; $values["s2_data"] = $s2_data; $values["s3_data"] = $s3_data; $error = false; if ($form->isValid($values)) { $values['output_sound_device'] = $form->getValue('output_sound_device'); $values['output_sound_device_type'] = $form->getValue('output_sound_device_type'); $values['icecast_vorbis_metadata'] = $form->getValue('icecast_vorbis_metadata'); $values['streamFormat'] = $form->getValue('streamFormat'); Application_Model_StreamSetting::setStreamSetting($values); /* If the admin password values are empty then we should not * set the pseudo password ('xxxxxx') on the front-end */ $s1_set_admin_pass = !empty($values["s1_data"]["admin_pass"]); $s2_set_admin_pass = !empty($values["s2_data"]["admin_pass"]); $s3_set_admin_pass = !empty($values["s3_data"]["admin_pass"]); // this goes into cc_pref table Application_Model_Preference::SetStreamLabelFormat($values['streamFormat']); Application_Model_Preference::SetLiveStreamMasterUsername($values["master_username"]); Application_Model_Preference::SetLiveStreamMasterPassword($values["master_password"]); Application_Model_Preference::SetDefaultTransitionFade($values["transition_fade"]); Application_Model_Preference::SetAutoTransition($values["auto_transition"]); Application_Model_Preference::SetAutoSwitch($values["auto_switch"]); // compare new values with current value $changeRGenabled = Application_Model_Preference::GetEnableReplayGain() != $values["enableReplayGain"]; $changeRGmodifier = Application_Model_Preference::getReplayGainModifier() != $values["replayGainModifier"]; if ($changeRGenabled || $changeRGmodifier) { Application_Model_Preference::SetEnableReplayGain($values["enableReplayGain"]); Application_Model_Preference::setReplayGainModifier($values["replayGainModifier"]); $md = array('schedule' => Application_Model_Schedule::getSchedule()); Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md); //Application_Model_RabbitMq::PushSchedule(); } if (!Application_Model_Preference::GetMasterDjConnectionUrlOverride()) { $master_connection_url = "http://" . $_SERVER['SERVER_NAME'] . ":" . $values["master_harbor_input_port"] . "/" . $values["master_harbor_input_mount_point"]; if (empty($values["master_harbor_input_port"]) || empty($values["master_harbor_input_mount_point"])) { Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A'); } else { Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url); } } else { Application_Model_Preference::SetMasterDJSourceConnectionURL($values["master_dj_connection_url"]); } if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) { $live_connection_url = "http://" . $_SERVER['SERVER_NAME'] . ":" . $values["dj_harbor_input_port"] . "/" . $values["dj_harbor_input_mount_point"]; if (empty($values["dj_harbor_input_port"]) || empty($values["dj_harbor_input_mount_point"])) { Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A'); } else { Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url); } } else { Application_Model_Preference::SetLiveDJSourceConnectionURL($values["live_dj_connection_url"]); } // extra info that goes into cc_stream_setting Application_Model_StreamSetting::setMasterLiveStreamPort($values["master_harbor_input_port"]); Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values["master_harbor_input_mount_point"]); Application_Model_StreamSetting::setDjLiveStreamPort($values["dj_harbor_input_port"]); Application_Model_StreamSetting::setDjLiveStreamMountPoint($values["dj_harbor_input_mount_point"]); Application_Model_StreamSetting::setOffAirMeta($values['offAirMeta']); // store stream update timestamp Application_Model_Preference::SetStreamUpdateTimestamp(); $data = array(); $info = Application_Model_StreamSetting::getStreamSetting(); $data['setting'] = $info; for ($i = 1; $i <= $num_of_stream; $i++) { Application_Model_StreamSetting::setLiquidsoapError($i, "waiting"); } Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data); $live_stream_subform->updateVariables(); $this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf(); $this->view->form = $form; $this->view->num_stream = $num_of_stream; $this->view->statusMsg = "<div class='success'>" . _("Stream Setting Updated.") . "</div>"; $this->_helper->json->sendJson(array("valid" => "true", "html" => $this->view->render('preference/stream-setting.phtml'), "s1_set_admin_pass" => $s1_set_admin_pass, "s2_set_admin_pass" => $s2_set_admin_pass, "s3_set_admin_pass" => $s3_set_admin_pass)); } else { $live_stream_subform->updateVariables(); $this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf(); $this->view->form = $form; $this->view->num_stream = $num_of_stream; $this->_helper->json->sendJson(array("valid" => "false", "html" => $this->view->render('preference/stream-setting.phtml'))); } } $live_stream_subform->updateVariables(); $this->view->num_stream = $num_of_stream; $this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf(); $this->view->form = $form; }
public function moveShow($deltaDay, $deltaMin) { if ($this->getShow()->isRepeating()) { return "Can't drag and drop repeating shows"; } $today_timestamp = time(); $startsDateTime = new DateTime($this->getShowInstanceStart(), new DateTimeZone("UTC")); $endsDateTime = new DateTime($this->getShowInstanceEnd(), new DateTimeZone("UTC")); if ($today_timestamp > $startsDateTime->getTimestamp()) { return "Can't move a past show"; } //the user is moving the show on the calendar from the perspective of local time. //incase a show is moved across a time change border offsets should be added to the localtime //stamp and then converted back to UTC to avoid show time changes! $startsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); $endsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); $newStartsDateTime = self::addDeltas($startsDateTime, $deltaDay, $deltaMin); $newEndsDateTime = self::addDeltas($endsDateTime, $deltaDay, $deltaMin); //convert our new starts/ends to UTC. $newStartsDateTime->setTimezone(new DateTimeZone("UTC")); $newEndsDateTime->setTimezone(new DateTimeZone("UTC")); if ($today_timestamp > $newStartsDateTime->getTimestamp()) { return "Can't move show into past"; } //check if show is overlapping $overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->getShowInstanceId()); if ($overlapping) { return "Cannot schedule overlapping shows"; } if ($this->isRecorded()) { //rebroadcasts should start at max 1 hour after a recorded show has ended. $minRebroadcastStart = self::addDeltas($newEndsDateTime, 0, 60); //check if we are moving a recorded show less than 1 hour before any of its own rebroadcasts. $rebroadcasts = CcShowInstancesQuery::create()->filterByDbOriginalShow($this->_instanceId)->filterByDbStarts($minRebroadcastStart->format('Y-m-d H:i:s'), Criteria::LESS_THAN)->find(); if (count($rebroadcasts) > 0) { return "Can't move a recorded show less than 1 hour before its rebroadcasts."; } } if ($this->isRebroadcast()) { try { $recordedShow = new Application_Model_ShowInstance($this->_showInstance->getDbOriginalShow()); } catch (Exception $e) { $this->_showInstance->delete(); return "Show was deleted because recorded show does not exist!"; } $recordEndDateTime = new DateTime($recordedShow->getShowInstanceEnd(), new DateTimeZone("UTC")); $newRecordEndDateTime = self::addDeltas($recordEndDateTime, 0, 60); if ($newStartsDateTime->getTimestamp() < $newRecordEndDateTime->getTimestamp()) { return "Must wait 1 hour to rebroadcast."; } } $this->setShowStart($newStartsDateTime); $this->setShowEnd($newEndsDateTime); $this->correctScheduleStartTimes(); $show = new Application_Model_Show($this->getShowId()); if (!$show->isRepeating() && is_null($this->isRebroadcast())) { $show->setShowFirstShow($newStartsDateTime); $show->setShowLastShow($newEndsDateTime); } Application_Model_RabbitMq::PushSchedule(); }
public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate = null, $update = false, $instanceId = null) { $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new Application_Model_User($userInfo->id); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isSaas = Application_Model_Preference::GetPlanLevel() != 'disabled'; $record = false; $formWhat = new Application_Form_AddShowWhat(); $formWho = new Application_Form_AddShowWho(); $formWhen = new Application_Form_AddShowWhen(); $formRepeats = new Application_Form_AddShowRepeats(); $formStyle = new Application_Form_AddShowStyle(); $formLive = new Application_Form_AddShowLiveStream(); $formWhat->removeDecorator('DtDdWrapper'); $formWho->removeDecorator('DtDdWrapper'); $formWhen->removeDecorator('DtDdWrapper'); $formRepeats->removeDecorator('DtDdWrapper'); $formStyle->removeDecorator('DtDdWrapper'); $formLive->removeDecorator('DtDdWrapper'); $what = $formWhat->isValid($data); $when = $formWhen->isValid($data); $live = $formLive->isValid($data); if ($when) { $when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId); } //The way the following code works is that is parses the hour and //minute from a string with the format "1h 20m" or "2h" or "36m". //So we are detecting whether an hour or minute value exists via strpos //and then parse appropriately. A better way to do this in the future is //actually pass the format from javascript in the format hh:mm so we don't //have to do this extra String parsing. $hPos = strpos($data["add_show_duration"], 'h'); $mPos = strpos($data["add_show_duration"], 'm'); $hValue = 0; $mValue = 0; if ($hPos !== false) { $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); } if ($mPos !== false) { $hPos = $hPos === false ? 0 : $hPos + 1; $mValue = trim(substr($data["add_show_duration"], $hPos, -1)); } $data["add_show_duration"] = $hValue . ":" . $mValue; if (!$isSaas) { $formRecord = new Application_Form_AddShowRR(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); $formRecord->removeDecorator('DtDdWrapper'); $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); $formRebroadcast->removeDecorator('DtDdWrapper'); $record = $formRecord->isValid($data); } if ($data["add_show_repeats"]) { $repeats = $formRepeats->isValid($data); if ($repeats) { $repeats = $formRepeats->checkReliantFields($data); } if (!$isSaas) { $formAbsoluteRebroadcast->reset(); //make it valid, results don't matter anyways. $rebroadAb = 1; if ($data["add_show_rebroadcast"]) { $rebroad = $formRebroadcast->isValid($data); if ($rebroad) { $rebroad = $formRebroadcast->checkReliantFields($data); } } else { $rebroad = 1; } } } else { $repeats = 1; if (!$isSaas) { $formRebroadcast->reset(); //make it valid, results don't matter anyways. $rebroad = 1; if ($data["add_show_rebroadcast"]) { $rebroadAb = $formAbsoluteRebroadcast->isValid($data); if ($rebroadAb) { $rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data); } } else { $rebroadAb = 1; } } } $who = $formWho->isValid($data); $style = $formStyle->isValid($data); if ($what && $when && $repeats && $who && $style && $live) { if (!$isSaas) { if ($record && $rebroadAb && $rebroad) { if ($isAdminOrPM) { Application_Model_Show::create($data); } //send back a new form for the user. Application_Model_Schedule::createNewFormSections($controller->view); //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); return true; } else { $controller->view->what = $formWhat; $controller->view->when = $formWhen; $controller->view->repeats = $formRepeats; $controller->view->who = $formWho; $controller->view->style = $formStyle; $controller->view->rr = $formRecord; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; $controller->view->rebroadcast = $formRebroadcast; $controller->view->live = $formLive; //$controller->view->addNewShow = !$editShow; //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); return false; } } else { if ($isAdminOrPM) { Application_Model_Show::create($data); } //send back a new form for the user. Application_Model_Schedule::createNewFormSections($controller->view); //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); return true; } } else { $controller->view->what = $formWhat; $controller->view->when = $formWhen; $controller->view->repeats = $formRepeats; $controller->view->who = $formWho; $controller->view->style = $formStyle; $controller->view->live = $formLive; if (!$isSaas) { $controller->view->rr = $formRecord; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; $controller->view->rebroadcast = $formRebroadcast; } //$controller->view->addNewShow = !$editShow; //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); return false; } }