diff --git a/Changelog b/Changelog index b979e0399..0ff1c3f4b 100644 --- a/Changelog +++ b/Changelog @@ -17,6 +17,9 @@ Highlights: - When canceling a playing show, the currently playing audio file still showed as playing. This has been fixed. - Audio files greater than 100MB were not being played. - Fixed uploading audio on Chrome 11 and higher + - Fixed various editing show problems + - Fixed airtime-pypo-stop/start causing playback problems + - Fixed incorrect information being occasionally shown in the top panel 1.8.1 - May 2, 2011 diff --git a/VERSION b/VERSION index b185f70e7..1ec57110d 100644 --- a/VERSION +++ b/VERSION @@ -1,2 +1,2 @@ PRODUCT_ID=Airtime -PRODUCT_RELEASE=1.9.0-devel +PRODUCT_RELEASE=1.8.2 diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 706d3082a..3ef84548e 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -53,34 +53,8 @@ class ScheduleController extends Zend_Controller_Action $this->view->headLink()->appendStylesheet($baseUrl.'/css/colorpicker/css/colorpicker.css'); $this->view->headLink()->appendStylesheet($baseUrl.'/css/add-show.css'); $this->view->headLink()->appendStylesheet($baseUrl.'/css/contextmenu.css'); - - $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(); - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formRecord->removeDecorator('DtDdWrapper'); - - $this->view->what = $formWhat; - $this->view->when = $formWhen; - $this->view->repeats = $formRepeats; - $this->view->who = $formWho; - $this->view->style = $formStyle; - $this->view->rr = $formRecord; - $this->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $this->view->rebroadcast = $formRebroadcast; - $this->view->addNewShow = true; - - $formWhat->populate(array('add_show_id' => '-1')); + + Schedule::createNewFormSections($this->view); $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $user = new User($userInfo->id); @@ -446,10 +420,14 @@ class ScheduleController extends Zend_Controller_Action 'add_show_description' => $show->getDescription())); $formWhen->populate(array('add_show_start_date' => $show->getStartDate(), - 'add_show_start_time' => Show::removeSecondsFromTime($show->getStartTime()), + 'add_show_start_time' => DateHelper::removeSecondsFromTime($show->getStartTime()), 'add_show_duration' => $show->getDuration(), 'add_show_repeats' => $show->isRepeating() ? 1 : 0)); + if ($show->isStartDateTimeInPast()){ + $formWhen->getElement('add_show_start_date')->setOptions(array('disabled' => true)); + } + $days = array(); $showDays = CcShowDaysQuery::create()->filterByDbShowId($showInstance->getShowId())->find(); foreach($showDays as $showDay){ @@ -476,7 +454,7 @@ class ScheduleController extends Zend_Controller_Action $i = 1; foreach ($rebroadcastsRelative as $rebroadcast){ $rebroadcastFormValues["add_show_rebroadcast_date_$i"] = $rebroadcast['day_offset']; - $rebroadcastFormValues["add_show_rebroadcast_time_$i"] = Show::removeSecondsFromTime($rebroadcast['start_time']); + $rebroadcastFormValues["add_show_rebroadcast_time_$i"] = DateHelper::removeSecondsFromTime($rebroadcast['start_time']); $i++; } $formRebroadcast->populate($rebroadcastFormValues); @@ -486,7 +464,7 @@ class ScheduleController extends Zend_Controller_Action $i = 1; foreach ($rebroadcastsAbsolute as $rebroadcast){ $rebroadcastAbsoluteFormValues["add_show_rebroadcast_date_absolute_$i"] = $rebroadcast['start_date']; - $rebroadcastAbsoluteFormValues["add_show_rebroadcast_time_absolute_$i"] = Show::removeSecondsFromTime($rebroadcast['start_time']); + $rebroadcastAbsoluteFormValues["add_show_rebroadcast_time_absolute_$i"] = DateHelper::removeSecondsFromTime($rebroadcast['start_time']); $i++; } $formAbsoluteRebroadcast->populate($rebroadcastAbsoluteFormValues); @@ -506,35 +484,8 @@ class ScheduleController extends Zend_Controller_Action $this->view->entries = 5; } - public function getFormAction(){ - $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(); - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formRecord->removeDecorator('DtDdWrapper'); - - $this->view->what = $formWhat; - $this->view->when = $formWhen; - $this->view->repeats = $formRepeats; - $this->view->who = $formWho; - $this->view->style = $formStyle; - $this->view->rr = $formRecord; - $this->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $this->view->rebroadcast = $formRebroadcast; - $this->view->addNewShow = true; - - $formWhat->populate(array('add_show_id' => '-1')); - + public function getFormAction(){ + Schedule::createNewFormSections($this->view); $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } @@ -548,6 +499,16 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + $show = new Show($data['add_show_id']); + + $startDateModified = true; + if ($data['add_show_id'] != -1 && !array_key_exists('add_show_start_date', $data)){ + //show is being updated and changing the start date was disabled, since the + //array key does not exist. We need to repopulate this entry from the db. + $data['add_show_start_date'] = $show->getStartDate(); + $startDateModified = false; + } + $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); @@ -573,24 +534,13 @@ class ScheduleController extends Zend_Controller_Action $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); $formRebroadcast->removeDecorator('DtDdWrapper'); - $this->view->what = $formWhat; - $this->view->when = $formWhen; - $this->view->repeats = $formRepeats; - $this->view->who = $formWho; - $this->view->style = $formStyle; - $this->view->rr = $formRecord; - $this->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $this->view->rebroadcast = $formRebroadcast; - $this->view->addNewShow = true; - $what = $formWhat->isValid($data); $when = $formWhen->isValid($data); if($when) { - $when = $formWhen->checkReliantFields($data); + $when = $formWhen->checkReliantFields($data, $startDateModified); } if($data["add_show_repeats"]) { - $repeats = $formRepeats->isValid($data); if($repeats) { $repeats = $formRepeats->checkReliantFields($data); @@ -636,7 +586,6 @@ class ScheduleController extends Zend_Controller_Action //update this option. $record = false; if ($data['add_show_id'] != -1){ - $show = new Show($data['add_show_id']); $data['add_show_record'] = $show->isRecorded(); $record = $formRecord->isValid($data); $formRecord->getElement('add_show_record')->setOptions(array('disabled' => true)); @@ -650,32 +599,31 @@ class ScheduleController extends Zend_Controller_Action if ($user->isAdmin()) { Show::create($data); } - + //send back a new form for the user. - $formWhat->reset(); - $formWhat->populate(array('add_show_id' => '-1')); - - $formWho->reset(); - $formWhen->reset(); - $formWhen->populate(array('add_show_start_date' => date("Y-m-d"), - 'add_show_start_time' => '0:00', - 'add_show_duration' => '1:00')); - $formRepeats->reset(); - $formRepeats->populate(array('add_show_end_date' => date("Y-m-d"))); - - $formStyle->reset(); - $formRecord->reset(); - $formAbsoluteRebroadcast->reset(); - $formRebroadcast->reset(); + Schedule::createNewFormSections($this->view); $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); } - else { + else { + $this->view->what = $formWhat; + $this->view->when = $formWhen; + $this->view->repeats = $formRepeats; + $this->view->who = $formWho; + $this->view->style = $formStyle; + $this->view->rr = $formRecord; + $this->view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $this->view->rebroadcast = $formRebroadcast; + $this->view->addNewShow = true; + //the form still needs to be "update" since //the validity test failed. if ($data['add_show_id'] != -1){ $this->view->addNewShow = false; } + if (!$startDateModified){ + $formWhen->getElement('add_show_start_date')->setOptions(array('disabled' => true)); + } $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } diff --git a/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php b/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php index 062b959d2..68d4d80ad 100644 --- a/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php +++ b/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php @@ -48,8 +48,8 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm $this->getElement('add_show_rebroadcast_date_absolute_'.$i)->setErrors(array("Day must be specified")); $valid = false; } - - + + if (trim($time) == ""){ $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Time must be specified")); $valid = false; @@ -60,7 +60,7 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm continue; } - $show_start_time = $formData['add_show_start_date']."".$formData['add_show_start_time']; + $show_start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time']; $show_end = new DateTime($show_start_time); $duration = $formData['add_show_duration']; @@ -70,7 +70,7 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm $show_end->add(new DateInterval("PT$duration[1]M")); $show_end->add(new DateInterval("PT1H"));//min time to wait until a rebroadcast - $rebroad_start = $day."".$formData['add_show_rebroadcast_time_absolute_'.$i]; + $rebroad_start = $day." ".$formData['add_show_rebroadcast_time_absolute_'.$i]; $rebroad_start = new DateTime($rebroad_start); if($rebroad_start < $show_end) { diff --git a/airtime_mvc/application/forms/AddShowRebroadcastDates.php b/airtime_mvc/application/forms/AddShowRebroadcastDates.php index 015662463..6104d7836 100644 --- a/airtime_mvc/application/forms/AddShowRebroadcastDates.php +++ b/airtime_mvc/application/forms/AddShowRebroadcastDates.php @@ -53,8 +53,8 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm $this->getElement('add_show_rebroadcast_date_'.$i)->setErrors(array("Day must be specified")); $valid = false; } - - + + if (trim($time) == ""){ $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Time must be specified")); $valid = false; @@ -68,7 +68,7 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm $days = explode(" ", $days); $day = $days[0]; - $show_start_time = $formData['add_show_start_date']."".$formData['add_show_start_time']; + $show_start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time']; $show_end = new DateTime($show_start_time); $duration = $formData['add_show_duration']; @@ -78,7 +78,7 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm $show_end->add(new DateInterval("PT$duration[1]M")); $show_end->add(new DateInterval("PT1H"));//min time to wait until a rebroadcast - $rebroad_start = $formData['add_show_start_date']."".$formData['add_show_rebroadcast_time_'.$i]; + $rebroad_start = $formData['add_show_start_date']." ".$formData['add_show_rebroadcast_time_'.$i]; $rebroad_start = new DateTime($rebroad_start); $rebroad_start->add(new DateInterval("P".$day."D")); diff --git a/airtime_mvc/application/forms/AddShowWhen.php b/airtime_mvc/application/forms/AddShowWhen.php index 389b12989..847f26005 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -59,20 +59,22 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } - public function checkReliantFields($formData) { + public function checkReliantFields($formData, $startDateModified) { $valid = true; $now_timestamp = date("Y-m-d H:i:s"); - $start_timestamp = $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); - if($start_epoch < $now_epoch) { - $this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past')); - $valid = false; - } + if ((($formData['add_show_id'] != -1) && $startDateModified) || ($formData['add_show_id'] == -1)){ + if($start_epoch < $now_epoch) { + $this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past')); + $valid = false; + } + } if(strtotime("00:00") == strtotime($formData["add_show_duration"])) { $this->getElement('add_show_duration')->setErrors(array('Cannot have duration 00:00')); diff --git a/airtime_mvc/application/layouts/scripts/library.phtml b/airtime_mvc/application/layouts/scripts/library.phtml index 1ea03f7a8..cd55c2ec5 100644 --- a/airtime_mvc/application/layouts/scripts/library.phtml +++ b/airtime_mvc/application/layouts/scripts/library.phtml @@ -19,8 +19,8 @@
-
layout()->spl ?>
-
layout()->library ?>
+
layout()->library ?>
+
layout()->spl ?>
diff --git a/airtime_mvc/application/models/Dashboard.php b/airtime_mvc/application/models/Dashboard.php index f7d5113b2..1234c96e2 100644 --- a/airtime_mvc/application/models/Dashboard.php +++ b/airtime_mvc/application/models/Dashboard.php @@ -16,8 +16,10 @@ class Application_Model_Dashboard if (count($row) == 0){ return null; } else { - //should never reach here. Doesnt make sense to have - //a schedule item not within a show_instance. + return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], + "starts"=>$row[0]["starts"], + "ends"=>$row[0]["ends"]); + } } else { if (count($row) == 0){ @@ -46,15 +48,23 @@ class Application_Model_Dashboard //after the last item in the schedule table, then return the show's //name. Else return the last item from the schedule. + $row = array(); $showInstance = ShowInstance::GetCurrentShowInstance($p_timeNow); - $row = Schedule::GetCurrentScheduleItem($p_timeNow); - + if (!is_null($showInstance)){ + $instanceId = $showInstance->getShowInstanceId(); + $row = Schedule::GetCurrentScheduleItem($p_timeNow, $instanceId); + } if (is_null($showInstance)){ if (count($row) == 0){ return null; } else { - //should never reach here. Doesnt make sense to have - //a schedule item not within a show_instance. + /* Should never reach here, but lets return the track information + * just in case we allow tracks to be scheduled without a show + * in the future. + */ + return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], + "starts"=>$row[0]["starts"], + "ends"=>$row[0]["ends"]); } } else { if (count($row) == 0){ @@ -62,8 +72,8 @@ class Application_Model_Dashboard return array("name"=>$showInstance->getName(), "starts"=>$showInstance->getShowStart(), "ends"=>$showInstance->getShowEnd(), - "media_item_played"=>false, //TODO - "record"=>$showInstance->isRecorded()); //TODO + "media_item_played"=>false, + "record"=>$showInstance->isRecorded()); } else { return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], "starts"=>$row[0]["starts"], diff --git a/airtime_mvc/application/models/DateHelper.php b/airtime_mvc/application/models/DateHelper.php index 97b7d9ae9..d8f44a3c5 100644 --- a/airtime_mvc/application/models/DateHelper.php +++ b/airtime_mvc/application/models/DateHelper.php @@ -18,6 +18,15 @@ class DateHelper return date("Y-m-d H:i:s", $this->_timestamp); } + /** + * Get date of object construction in the format + * YY:mm:dd + */ + function getDate() + { + return date("Y-m-d", $this->_timestamp); + } + /** * Get time of object construction in the format * HH:mm:ss @@ -83,5 +92,40 @@ class DateHelper return $hours.":".$minutes.":".$seconds.".".$ms; } + + /** + * This function formats a time by removing seconds + * + * When we receive a time from the database we get the + * format "hh:mm:ss". But when dealing with show times, we + * do not care about the seconds. + * + * @param int $p_timestamp + * The value which to format. + * @return int + * The timestamp with the new format "hh:mm", or + * the original input parameter, if it does not have + * the correct format. + */ + public static function removeSecondsFromTime($p_timestamp) + { + //Format is in hh:mm:ss. We want hh:mm + $timeExplode = explode(":", $p_timestamp); + + if (count($timeExplode) == 3) + return $timeExplode[0].":".$timeExplode[1]; + else + return $p_timestamp; + } + + public static function getDateFromTimestamp($p_timestamp){ + $explode = explode(" ", $p_timestamp); + return $explode[0]; + } + + public static function getTimeFromTimestamp($p_timestamp){ + $explode = explode(" ", $p_timestamp); + return $explode[1]; + } } diff --git a/airtime_mvc/application/models/Playlist.php b/airtime_mvc/application/models/Playlist.php index c71958ab4..1b7ee4e05 100644 --- a/airtime_mvc/application/models/Playlist.php +++ b/airtime_mvc/application/models/Playlist.php @@ -91,7 +91,7 @@ class Playlist { { $seconds = $p_seconds; $milliseconds = intval(($seconds - intval($seconds)) * 1000); - $milliStr = str_pad($milliseconds, 6, '0'); + $milliStr = str_pad($milliseconds, 3, '0'); $hours = floor($seconds / 3600); $seconds -= $hours * 3600; $minutes = floor($seconds / 60); @@ -387,9 +387,14 @@ class Playlist { ->orderByDbPosition() ->filterByDbPlaylistId($this->id) ->find(); - + + $i = 0; + $offset = 0; foreach ($rows as $row) { - $files[] = $row->toArray(BasePeer::TYPE_FIELDNAME, true, true); + $files[$i] = $row->toArray(BasePeer::TYPE_FIELDNAME, true, true); + $offset += Playlist::playlistTimeToSeconds($files[$i]['cliplength']); + $files[$i]['offset'] = Playlist::secondsToPlaylistTime($offset); + $i++; } return $files; diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index d6a647d8e..231d35e86 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -394,15 +394,24 @@ class Schedule { } - public static function GetCurrentScheduleItem($p_timeNow){ + public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId){ global $CC_CONFIG, $CC_DBC; + /* Note that usually there will be one result returned. In some + * rare cases two songs are returned. This happens when a track + * that was overbooked from a previous show appears as if it + * hasnt ended yet (track end time hasn't been reached yet). For + * this reason, we need to get the track that starts later, as + * this is the *real* track that is currently playing. So this + * is why we are ordering by track start time. */ $sql = "SELECT *" ." FROM $CC_CONFIG[scheduleTable] st" ." LEFT JOIN $CC_CONFIG[filesTable] ft" ." ON st.file_id = ft.id" ." WHERE st.starts <= TIMESTAMP '$p_timeNow'" + ." AND st.instance_id = $p_instanceId" ." AND st.ends > TIMESTAMP '$p_timeNow'" + ." ORDER BY st.starts DESC" ." LIMIT 1"; $row = $CC_DBC->GetAll($sql); @@ -725,5 +734,37 @@ class Schedule { global $CC_CONFIG, $CC_DBC; $CC_DBC->query("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]); } + + public static function createNewFormSections($p_view){ + $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(); + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + + $p_view->what = $formWhat; + $p_view->when = $formWhen; + $p_view->repeats = $formRepeats; + $p_view->who = $formWho; + $p_view->style = $formStyle; + $p_view->rr = $formRecord; + $p_view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $p_view->rebroadcast = $formRebroadcast; + $p_view->addNewShow = true; + + $formWhat->populate(array('add_show_id' => '-1')); + } } diff --git a/airtime_mvc/application/models/Shows.php b/airtime_mvc/application/models/Shows.php index 07a48f3f5..2340a6a1d 100644 --- a/airtime_mvc/application/models/Shows.php +++ b/airtime_mvc/application/models/Shows.php @@ -318,14 +318,19 @@ class Show { * certain date. * * @param string $p_date - * The date which to delete after + * The date which to delete after, if null deletes from the current timestamp. */ - public function removeAllInstancesFromDate($p_date){ + public function removeAllInstancesFromDate($p_date=null){ global $CC_DBC; $date = new DateHelper; $timestamp = $date->getTimestamp(); + if(is_null($p_date)) { + $date = new DateHelper; + $p_date = $date->getDate(); + } + $showId = $this->getId(); $sql = "DELETE FROM cc_show_instances " ." WHERE date(starts) >= DATE '$p_date'" @@ -333,6 +338,13 @@ class Show { ." AND show_id = $showId"; $CC_DBC->query($sql); + + /* + CcShowInstancesQuery::create() + ->filterByDbShowId($showId) + ->filterByDbStartTime($p_date, Criteria::GREATER_EQUAL) + ->delete(); + */ } /** @@ -402,6 +414,19 @@ class Show { } } + /** + * Indicate whether the starting point of the show is in the + * past. + * + * @return boolean + * true if the StartDate is in the past, false otherwise + */ + public function isStartDateTimeInPast(){ + $date = new DateHelper; + $current_timestamp = $date->getTimestamp(); + return ($current_timestamp > $this->getStartDate()." ".$this->getStartTime()); + } + /** * Get the ID's of future instance of the current show. * @@ -533,11 +558,13 @@ class Show { public static function deletePossiblyInvalidInstances($p_data, $p_show, $p_endDate, $isRecorded, $repeatType) { - if ($p_data['add_show_repeats'] != $p_show->isRepeating() - || $isRecorded){ - //repeat option was toggled or show is recorded. + if (($p_data['add_show_repeats'] != $p_show->isRepeating()) || ($isRecorded && !$p_data['add_show_repeats'])){ + //repeat option was toggled. $p_show->deleteAllInstances(); } + if($isRecorded && $p_data['add_show_repeats']) { + $p_show->removeAllInstancesFromDate(); + } if ($p_data['add_show_duration'] != $p_show->getDuration()){ //duration has changed @@ -545,6 +572,16 @@ class Show { } if ($p_data['add_show_repeats']){ + if (($repeatType == 1 || $repeatType == 2) && + $p_data['add_show_start_date'] != $p_show->getStartDate()){ + + //start date has changed when repeat type is bi-weekly or monthly. + //This screws up the repeating positions of show instances, so lets + //just delete them for now. + + $p_show->deleteAllInstances(); + } + if ($p_data['add_show_start_date'] != $p_show->getStartDate() || $p_data['add_show_start_time'] != $p_show->getStartTime()){ //start date/time has changed @@ -557,7 +594,7 @@ class Show { $p_show->updateStartDateTime($p_data, $p_endDate); } - + if ($repeatType != $p_show->getRepeatType()){ //repeat type changed. $p_show->deleteAllInstances(); @@ -571,7 +608,8 @@ class Show { if (count($intersect) != count($p_data['add_show_day_check'])){ $repeatingDaysChanged = true; } - } else { + } + else { $repeatingDaysChanged = true; } @@ -589,7 +627,8 @@ class Show { if ((strlen($p_show->getRepeatingEndDate()) == 0) == $p_data['add_show_no_end']){ //show "Never Ends" option was toggled. if ($p_data['add_show_no_end']){ - } else { + } + else { $p_show->removeAllInstancesFromDate($p_endDate); } } @@ -608,7 +647,7 @@ class Show { /** * Create a show. * - * Note: end dates are inclusive. + * Note: end dates are non inclusive. * * @param array $data * @return int @@ -685,7 +724,8 @@ class Show { $showDay->setDbShowId($showId); $showDay->setDbRecord($isRecorded); $showDay->save(); - } else { + } + else { foreach ($data['add_show_day_check'] as $day) { if ($startDow !== $day){ @@ -717,16 +757,20 @@ class Show { } } + $date = new DateHelper(); + $currentTimestamp = $date->getTimestamp(); + //check if we are adding or updating a show, and if updating - //erase all the show's show_rebroadcast information first. - if ($data['add_show_id'] != -1){ - CcShowRebroadcastQuery::create()->filterByDbShowId($data['add_show_id'])->delete(); + //erase all the show's future show_rebroadcast information first. + if (($data['add_show_id'] != -1) && $data['add_show_rebroadcast']){ + CcShowRebroadcastQuery::create() + ->filterByDbShowId($data['add_show_id']) + //->filterByDbStartTime($currentTimestamp, Criteria::GREATER_EQUAL) + ->delete(); } //adding rows to cc_show_rebroadcast - if ($isRecorded && $data['add_show_rebroadcast'] && $repeatType != -1) { - + if (($isRecorded && $data['add_show_rebroadcast']) && ($repeatType != -1)) { for ($i=1; $i<=10; $i++) { - if ($data['add_show_rebroadcast_date_'.$i]) { $showRebroad = new CcShowRebroadcast(); $showRebroad->setDbDayOffset($data['add_show_rebroadcast_date_'.$i]); @@ -735,10 +779,9 @@ class Show { $showRebroad->save(); } } - } else if ($isRecorded && $data['add_show_rebroadcast'] && $repeatType == -1){ - + } + else if ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)){ for ($i=1; $i<=10; $i++) { - if ($data['add_show_rebroadcast_date_absolute_'.$i]) { $sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' "; $r = $con->query($sql); @@ -845,30 +888,34 @@ class Show { private static function populateNonRepeatingShow($show_id, $first_show, $start_time, $duration, $day, $record, $end_timestamp) { global $CC_DBC; - $next_date = $first_show." ".$start_time; if (strtotime($next_date) < strtotime($end_timestamp)) { $start = $next_date; - $sql = "SELECT timestamp '{$start}' + interval '{$duration}'"; $end = $CC_DBC->GetOne($sql); + $date = new DateHelper(); + $currentTimestamp = $date->getTimestamp(); + $show = new Show($show_id); if ($show->hasInstance()){ $ccShowInstance = $show->getInstance(); $newInstance = false; - } else { + } + else { $ccShowInstance = new CcShowInstances(); $newInstance = true; } - - $ccShowInstance->setDbShowId($show_id); - $ccShowInstance->setDbStarts($start); - $ccShowInstance->setDbEnds($end); - $ccShowInstance->setDbRecord($record); - $ccShowInstance->save(); + + if ($newInstance || $ccShowInstance->getDbStarts() > $currentTimestamp){ + $ccShowInstance->setDbShowId($show_id); + $ccShowInstance->setDbStarts($start); + $ccShowInstance->setDbEnds($end); + $ccShowInstance->setDbRecord($record); + $ccShowInstance->save(); + } $show_instance_id = $ccShowInstance->getDbId(); $showInstance = new ShowInstance($show_instance_id); @@ -890,14 +937,16 @@ class Show { $sql = "SELECT timestamp '{$rebroadcast_start_time}' + interval '{$duration}'"; $rebroadcast_end_time = $CC_DBC->GetOne($sql); - $newRebroadcastInstance = new CcShowInstances(); - $newRebroadcastInstance->setDbShowId($show_id); - $newRebroadcastInstance->setDbStarts($rebroadcast_start_time); - $newRebroadcastInstance->setDbEnds($rebroadcast_end_time); - $newRebroadcastInstance->setDbRecord(0); - $newRebroadcastInstance->setDbRebroadcast(1); - $newRebroadcastInstance->setDbOriginalShow($show_instance_id); - $newRebroadcastInstance->save(); + if ($rebroadcast_start_time > $currentTimestamp){ + $newRebroadcastInstance = new CcShowInstances(); + $newRebroadcastInstance->setDbShowId($show_id); + $newRebroadcastInstance->setDbStarts($rebroadcast_start_time); + $newRebroadcastInstance->setDbEnds($rebroadcast_end_time); + $newRebroadcastInstance->setDbRecord(0); + $newRebroadcastInstance->setDbRebroadcast(1); + $newRebroadcastInstance->setDbOriginalShow($show_instance_id); + $newRebroadcastInstance->save(); + } } } RabbitMq::PushSchedule(); @@ -920,6 +969,9 @@ class Show { $rebroadcasts = $CC_DBC->GetAll($sql); $show = new Show($show_id); + $date = new DateHelper(); + $currentTimestamp = $date->getTimestamp(); + while(strtotime($next_date) <= strtotime($end_timestamp) && (strtotime($last_show) > strtotime($next_date) || is_null($last_show))) { $start = $next_date; @@ -934,11 +986,17 @@ class Show { $ccShowInstance = new CcShowInstances(); $newInstance = true; } - $ccShowInstance->setDbShowId($show_id); - $ccShowInstance->setDbStarts($start); - $ccShowInstance->setDbEnds($end); - $ccShowInstance->setDbRecord($record); - $ccShowInstance->save(); + + /* When editing the start/end time of a repeating show, we don't want to + * change shows that started in the past. So check the start time. + */ + if ($newInstance || $ccShowInstance->getDbStarts() > $currentTimestamp){ + $ccShowInstance->setDbShowId($show_id); + $ccShowInstance->setDbStarts($start); + $ccShowInstance->setDbEnds($end); + $ccShowInstance->setDbRecord($record); + $ccShowInstance->save(); + } $show_instance_id = $ccShowInstance->getDbId(); $showInstance = new ShowInstance($show_instance_id); @@ -957,14 +1015,16 @@ class Show { $sql = "SELECT timestamp '{$rebroadcast_start_time}' + interval '{$duration}'"; $rebroadcast_end_time = $CC_DBC->GetOne($sql); - $newRebroadcastInstance = new CcShowInstances(); - $newRebroadcastInstance->setDbShowId($show_id); - $newRebroadcastInstance->setDbStarts($rebroadcast_start_time); - $newRebroadcastInstance->setDbEnds($rebroadcast_end_time); - $newRebroadcastInstance->setDbRecord(0); - $newRebroadcastInstance->setDbRebroadcast(1); - $newRebroadcastInstance->setDbOriginalShow($show_instance_id); - $newRebroadcastInstance->save(); + if ($rebroadcast_start_time > $currentTimestamp){ + $newRebroadcastInstance = new CcShowInstances(); + $newRebroadcastInstance->setDbShowId($show_id); + $newRebroadcastInstance->setDbStarts($rebroadcast_start_time); + $newRebroadcastInstance->setDbEnds($rebroadcast_end_time); + $newRebroadcastInstance->setDbRecord(0); + $newRebroadcastInstance->setDbRebroadcast(1); + $newRebroadcastInstance->setDbOriginalShow($show_instance_id); + $newRebroadcastInstance->save(); + } } $sql = "SELECT timestamp '{$start}' + interval '{$interval}'"; @@ -1132,41 +1192,6 @@ class Show { return $event; } - - public static function getDateFromTimestamp($p_timestamp){ - $explode = explode(" ", $p_timestamp); - return $explode[0]; - } - - public static function getTimeFromTimestamp($p_timestamp){ - $explode = explode(" ", $p_timestamp); - return $explode[1]; - } - - /** - * This function formats a time by removing seconds - * - * When we receive a time from the database we get the - * format "hh:mm:ss". But when dealing with show times, we - * do not care about the seconds. - * - * @param int $p_timestamp - * The value which to format. - * @return int - * The timestamp with the new format "hh:mm", or - * the original input parameter, if it does not have - * the correct format. - */ - public static function removeSecondsFromTime($p_timestamp) - { - //Format is in hh:mm:ss. We want hh:mm - $timeExplode = explode(":", $p_timestamp); - - if (count($timeExplode) == 3) - return $timeExplode[0].":".$timeExplode[1]; - else - return $p_timestamp; - } } class ShowInstance { diff --git a/airtime_mvc/application/views/scripts/playlist/update.phtml b/airtime_mvc/application/views/scripts/playlist/update.phtml index 590f071cf..08085623f 100644 --- a/airtime_mvc/application/views/scripts/playlist/update.phtml +++ b/airtime_mvc/application/views/scripts/playlist/update.phtml @@ -15,6 +15,7 @@
+
pl->getContents()) -1): ?>
diff --git a/airtime_mvc/public/css/playlist_builder.css b/airtime_mvc/public/css/playlist_builder.css index d05a0a0d3..7aef3be75 100644 --- a/airtime_mvc/public/css/playlist_builder.css +++ b/airtime_mvc/public/css/playlist_builder.css @@ -81,6 +81,13 @@ color:#d5d5d5; } +.spl_offset { + float: right; + text-align: right; + padding: 0 5px 0 0; + color: #D5D5D5; +} + /*#spl_editor { height: 50px; }*/ @@ -402,7 +409,6 @@ font-size: 12px; margin: 0; padding: 2px 0 0 0; - text-indent: 3px; -moz-box-shadow: inset 0px 2px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow: inset 0px 2px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0px 2px 2px rgba(0, 0, 0, 0.1); diff --git a/airtime_mvc/public/css/plupload.queue.css b/airtime_mvc/public/css/plupload.queue.css index e54912b37..3766a71f7 100644 --- a/airtime_mvc/public/css/plupload.queue.css +++ b/airtime_mvc/public/css/plupload.queue.css @@ -56,9 +56,8 @@ .plupload_header {background: #2A2C2E url('img/backgrounds.gif') repeat-x;} .plupload_header_content { - background: url('img/backgrounds.gif') no-repeat 0 -317px; min-height: 56px; - padding-left: 60px; + padding-left: 10px; color: #FFF; } .plupload_header_title { diff --git a/airtime_mvc/public/js/airtime/library/plupload.js b/airtime_mvc/public/js/airtime/library/plupload.js index 930bb60f1..6dabd207b 100644 --- a/airtime_mvc/public/js/airtime/library/plupload.js +++ b/airtime_mvc/public/js/airtime/library/plupload.js @@ -25,5 +25,28 @@ $(document).ready(function() { $("#plupload_error").find("table").append(row); } }); + + var uploadProgress = false; + + uploader.bind('QueueChanged', function(){ + if(uploader.files.length > 0){ + uploadProgress = true; + }else{ + uploadProgress = false; + } + }); + + uploader.bind('UploadComplete', function(){ + uploadProgress = false; + }); + + + $(window).bind('beforeunload', function(){ + if(uploadProgress){ + if(!confirm("You are currently uploading files.\nGoing to another screen will cancel the upload process.\nAre you sure you want to cancel the upload process and go to the screen you clicked on?")){ + return false; + } + } + }); }); diff --git a/airtime_mvc/public/js/airtime/nowplaying/nowplayingdatagrid.js b/airtime_mvc/public/js/airtime/nowplaying/nowplayingdatagrid.js index 1e395fd6f..b20804745 100644 --- a/airtime_mvc/public/js/airtime/nowplaying/nowplayingdatagrid.js +++ b/airtime_mvc/public/js/airtime/nowplaying/nowplayingdatagrid.js @@ -181,7 +181,7 @@ function createDataGrid(){ var nCell = document.createElement('td'); nCell.colSpan = iColspan; nCell.className = "gap"; - nCell.innerHTML = "Gap until show end: " + gapTimeFormat + " seconds"; + nCell.innerHTML = "Gap until show end: " + gapTimeFormat; nGroup.appendChild(nCell); nTrs[i].parentNode.replaceChild(nGroup, nTrs[i]); } else if ( sType.indexOf("r") != -1 ){ diff --git a/install/airtime-install b/install/airtime-install new file mode 100755 index 000000000..b86f03ad8 --- /dev/null +++ b/install/airtime-install @@ -0,0 +1,31 @@ +#!/bin/bash + +#Cause bash script to exit if any of the installers +#return with a non-zero return value. +set -e + +# Absolute path to this script +SCRIPT=`readlink -f $0` +# Absolute directory this script is in +SCRIPTPATH=`dirname $SCRIPT` + +echo -e "\n******************************** Install Begin *********************************" + +php ${SCRIPTPATH}/airtime-install.php $@ + +echo -e "\n*** Creating Pypo User ***" +python ${SCRIPTPATH}/../python_apps/create-pypo-user.py + +echo -e "\n*** Pypo Installation ***" +python ${SCRIPTPATH}/../python_apps/pypo/install/pypo-install.py + +echo -e "\n*** Recorder Installation ***" +python ${SCRIPTPATH}/../python_apps/show-recorder/install/recorder-install.py + +echo -e "\n*** Media Monitor Installation ***" +python ${SCRIPTPATH}/../python_apps/media-monitor/install/media-monitor-install.py + +sleep 4 +airtime-check-system + +echo -e "\n******************************* Install Complete *******************************" diff --git a/install/airtime-install.php b/install/airtime-install.php index d316ced49..8a0a6f741 100644 --- a/install/airtime-install.php +++ b/install/airtime-install.php @@ -10,9 +10,6 @@ */ set_include_path(__DIR__.'/../airtime_mvc/library' . PATH_SEPARATOR . get_include_path()); -echo PHP_EOL; -echo "******************************** Install Begin *********************************".PHP_EOL; - require_once(dirname(__FILE__).'/include/AirtimeIni.php'); require_once(dirname(__FILE__).'/include/AirtimeInstall.php'); require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/constants.php'); @@ -43,20 +40,24 @@ catch (Zend_Console_Getopt_Exception $e) { if (isset($opts->h)) { echo $opts->getUsageMessage(); - exit; + exit(1); } // The current version is already installed. if(isset($version) && ($version != false) && ($version == AIRTIME_VERSION) && !isset($opts->r)) { echo "Airtime $version is already installed.".PHP_EOL; echo $opts->getUsageMessage(); - exit(); + exit(1); } // A previous version exists - if so, upgrade. if(isset($version) && ($version != false) && ($version < AIRTIME_VERSION)) { echo "Airtime version $version found.".PHP_EOL; require_once("airtime-upgrade.php"); - exit(); + + //Make sure to exit with non-zero error code so that airtime-install + //shell script does not continue with installing pypo, show-recorder, + //media-monitor etc. + exit(2); } // ------------------------------------------------------------------------- @@ -126,19 +127,5 @@ AirtimeInstall::CreateSymlinksToUtils(); AirtimeInstall::CreateZendPhpLogFile(); -echo PHP_EOL."*** Pypo Installation ***".PHP_EOL; -system("python ".__DIR__."/../python_apps/pypo/install/pypo-install.py"); - -echo PHP_EOL."*** Recorder Installation ***".PHP_EOL; -system("python ".__DIR__."/../python_apps/show-recorder/install/recorder-install.py"); - -//wait for 1.9.0 release -//echo PHP_EOL."*** Media Monitor Installation ***".PHP_EOL; -//system("python ".__DIR__."/../python_apps/pytag-fs/install/media-monitor-install.py"); - -echo PHP_EOL."*** Verifying Correct System Environment ***".PHP_EOL; -$command = "airtime-check-system"; -system($command); - -echo "******************************* Install Complete *******************************".PHP_EOL; +/* FINISHED AIRTIME PHP INSTALLER */ diff --git a/install/airtime-uninstall b/install/airtime-uninstall new file mode 100755 index 000000000..4168eb8e7 --- /dev/null +++ b/install/airtime-uninstall @@ -0,0 +1,27 @@ +#!/bin/bash + +# Absolute path to this script +SCRIPT=`readlink -f $0` +# Absolute directory this script is in +SCRIPTPATH=`dirname $SCRIPT` + +echo -e "\n******************************* Uninstall Begin ********************************" + +php ${SCRIPTPATH}/airtime-uninstall.php + +echo -e "\n*** Uninstalling Pypo ***" +python ${SCRIPTPATH}/../python_apps/pypo/install/pypo-uninstall.py + +#echo -e "\n*** Uninstalling Media Monitor ***" +#python ${SCRIPTPATH}/../python_apps/pytag-fs/install/media-monitor-uninstall.py + +echo -e "\n*** Uninstalling Show Recorder ***" +python ${SCRIPTPATH}/../python_apps/show-recorder/install/recorder-uninstall.py + +echo -e "\n*** Removing Pypo User ***" +python ${SCRIPTPATH}/../python_apps/remove-pypo-user.py + +echo -e "\n****************************** Uninstall Complete ******************************\n" +echo "NOTE: To fully remove all Airtime files, you will also have to manually delete" +echo " the directories '/srv/airtime'(default storage location of media files)" +echo -e " and '/etc/airtime'(where the config files are stored).\n" diff --git a/install/airtime-uninstall.php b/install/airtime-uninstall.php index 851ca8ce3..d1489d893 100644 --- a/install/airtime-uninstall.php +++ b/install/airtime-uninstall.php @@ -19,7 +19,6 @@ require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/constants. require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/conf.php'); echo PHP_EOL; -echo "******************************* Uninstall Begin ********************************".PHP_EOL; echo "* Uninstalling Airtime ".AIRTIME_VERSION.PHP_EOL; AirtimeInstall::UninstallPhpCode(); @@ -81,18 +80,7 @@ if ($results == 0) { # Disabled as this should be a manual process #AirtimeInstall::DeleteFilesRecursive(AirtimeInstall::CONF_DIR_STORAGE); -echo PHP_EOL."*** Uninstalling Pypo ***".PHP_EOL; -$command = "python ".__DIR__."/../python_apps/pypo/install/pypo-uninstall.py"; -system($command); -echo PHP_EOL."*** Uninstalling Show Recorder ***".PHP_EOL; -$command = "python ".__DIR__."/../python_apps/show-recorder/install/recorder-uninstall.py"; -system($command); - -//wait for 1.9.0 release -//echo PHP_EOL."*** Uninstalling Media Monitor ***".PHP_EOL; -//$command = "python ".__DIR__."/../python_apps/pytag-fs/install/media-monitor-uninstall.py"; -//system($command); #Disabled as this should be a manual process #AirtimeIni::RemoveIniFiles(); @@ -101,10 +89,4 @@ AirtimeInstall::RemoveSymlinks(); AirtimeInstall::UninstallBinaries(); AirtimeInstall::RemoveLogDirectories(); -echo PHP_EOL; -echo "****************************** Uninstall Complete ******************************".PHP_EOL; -echo PHP_EOL; -echo "NOTE: To fully remove all Airtime files, you will also have to manually delete".PHP_EOL; -echo " the directories '".AirtimeInstall::CONF_DIR_STORAGE."'(where the media files are stored)".PHP_EOL; -echo " and '/etc/airtime'(where the config files are stored).".PHP_EOL; -echo PHP_EOL; +/* FINISHED AIRTIME PHP UNINSTALLER */ diff --git a/install/airtime-upgrade.php b/install/airtime-upgrade.php index 4072473a2..a568fe9c5 100644 --- a/install/airtime-upgrade.php +++ b/install/airtime-upgrade.php @@ -63,35 +63,39 @@ if (!$version){ echo "******************************** Update Begin *********************************".PHP_EOL; -if(strcmp($version, "1.7.0") < 0) { +//convert strings like 1.9.0-devel to 1.9.0 +$version = substr($version, 0, 5); + +if (strcmp($version, "1.7.0") < 0){ system("php ".__DIR__."/upgrades/airtime-1.7/airtime-upgrade.php"); } -if(strcmp($version, "1.8.0") < 0) { +if (strcmp($version, "1.8.0") < 0){ system("php ".__DIR__."/upgrades/airtime-1.8/airtime-upgrade.php"); } -if(strcmp($version, "1.8.1") < 0) { +if (strcmp($version, "1.8.1") < 0){ system("php ".__DIR__."/upgrades/airtime-1.8.1/airtime-upgrade.php"); } -if(strcmp($version, "1.8.2") < 0) { +if (strcmp($version, "1.8.2") < 0){ system("php ".__DIR__."/upgrades/airtime-1.8.2/airtime-upgrade.php"); } -//if (strcmp($version, "1.9.0") < 0){ - //system("php ".__DIR__."/upgrades/airtime-1.9/airtime-upgrade.php"); -//} +if (strcmp($version, "1.9.0") < 0){ + system("php ".__DIR__."/upgrades/airtime-1.9/airtime-upgrade.php"); +} //set the new version in the database. $sql = "DELETE FROM cc_pref WHERE keystr = 'system_version'"; $CC_DBC->query($sql); -$sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '1.8.2')"; +$sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '1.9.0-devel')"; $CC_DBC->query($sql); -echo PHP_EOL."*** Updating Recorder ***".PHP_EOL; -system("python ".__DIR__."/../python_apps/show-recorder/install/recorder-install.py"); - echo PHP_EOL."*** Updating Pypo ***".PHP_EOL; -system("python ".__DIR__."/../python_apps/pypo/install/pypo-install.py"); +passthru("python ".__DIR__."/../python_apps/pypo/install/pypo-install.py"); + +echo PHP_EOL."*** Updating Recorder ***".PHP_EOL; +passthru("python ".__DIR__."/../python_apps/show-recorder/install/recorder-install.py"); + echo "******************************* Update Complete *******************************".PHP_EOL; diff --git a/install/include/AirtimeIni.php b/install/include/AirtimeIni.php index 65243eb08..7f2ff24e8 100644 --- a/install/include/AirtimeIni.php +++ b/install/include/AirtimeIni.php @@ -26,7 +26,7 @@ class AirtimeIni const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg"; const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg"; const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg"; - //const CONF_FILE_MEDIAMONITOR = "/etc/airtime/MediaMonitor.cfg"; + const CONF_FILE_MEDIAMONITOR = "/etc/airtime/media-monitor.cfg"; public static function IniFilesExist() { @@ -73,11 +73,10 @@ class AirtimeIni echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting."; exit(1); } - //wait until Airtime 1.9.0 - //if (!copy(__DIR__."/../../python_apps/pytag-fs/MediaMonitor.cfg", AirtimeIni::CONF_FILE_MEDIAMONITOR)){ - // echo "Could not copy MediaMonitor.cfg to /etc/airtime/. Exiting."; - // exit(1); - //} + if (!copy(__DIR__."/../../python_apps/media-monitor/media-monitor.cfg", AirtimeIni::CONF_FILE_MEDIAMONITOR)){ + echo "Could not copy MediaMonitor.cfg to /etc/airtime/. Exiting."; + exit(1); + } } /** diff --git a/install/upgrades/airtime-1.8.2/airtime-upgrade.php b/install/upgrades/airtime-1.8.2/airtime-upgrade.php index fb3ec1365..fc6786847 100644 --- a/install/upgrades/airtime-1.8.2/airtime-upgrade.php +++ b/install/upgrades/airtime-1.8.2/airtime-upgrade.php @@ -225,7 +225,6 @@ function InstallPhpCode() echo "* Installing PHP code to ".$CC_CONFIG['phpDir'].PHP_EOL; exec("mkdir -p ".$CC_CONFIG['phpDir']); exec("cp -R ".$AIRTIME_SRC."/* ".$CC_CONFIG['phpDir']); - } function InstallBinaries() diff --git a/install/upgrades/airtime-1.9/airtime-upgrade.php b/install/upgrades/airtime-1.9/airtime-upgrade.php index 99ff40ee5..049962a61 100644 --- a/install/upgrades/airtime-1.9/airtime-upgrade.php +++ b/install/upgrades/airtime-1.9/airtime-upgrade.php @@ -12,3 +12,77 @@ require_once(dirname(__FILE__).'/../../include/AirtimeInstall.php'); require_once(dirname(__FILE__).'/../../include/AirtimeIni.php'); AirtimeInstall::CreateZendPhpLogFile(); + +const CONF_DIR_BINARIES = "/usr/lib/airtime"; +const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf"; + +function InstallPhpCode($phpDir) +{ + global $CC_CONFIG; + + $AIRTIME_SRC = realpath(__DIR__.'/../../../airtime_mvc'); + + echo "* Installing PHP code to ".$phpDir.PHP_EOL; + exec("mkdir -p ".$phpDir); + exec("cp -R ".$AIRTIME_SRC."/* ".$phpDir); +} + +function InstallBinaries() +{ + $utilsSrc = __DIR__."/../../../utils"; + + echo "* Installing binaries to ".CONF_DIR_BINARIES.PHP_EOL; + exec("mkdir -p ".CONF_DIR_BINARIES); + exec("cp -R ".$utilsSrc." ".CONF_DIR_BINARIES); +} + +function UninstallBinaries() +{ + echo "* Removing Airtime binaries from ".CONF_DIR_BINARIES.PHP_EOL; + exec("rm -rf ".CONF_DIR_BINARIES); +} + + +/* In version 1.9.0 we have have switched from daemontools to more traditional + * init.d daemon system. Let's remove all the daemontools files + */ + +exec("/usr/bin/airtime-pypo-stop"); +exec("/usr/bin/airtime-show-recorder-stop"); +exec("/usr/bin/airtime-media-monitor-stop"); + +exec("svc -d /etc/service/pypo"); +exec("svc -d /etc/service/pypo/log"); +exec("svc -d /etc/service/pypo-liquidsoap"); +exec("svc -d /etc/service/pypo-liquidsoap/log"); +exec("svc -d /etc/service/recorder"); +exec("svc -d /etc/service/recorder/log"); + +$pathnames = array("/usr/bin/airtime-pypo-start", + "/usr/bin/airtime-pypo-stop", + "/usr/bin/airtime-show-recorder-start", + "/usr/bin/airtime-show-recorder-stop", + "/usr/bin/airtime-media-monitor-start", + "/usr/bin/airtime-media-monitor-stop", + "/etc/service/pypo", + "/etc/service/pypo-liquidsoap", + "/etc/service/media-monitor", + "/etc/service/recorder", + "/var/log/airtime/pypo/main", + "/var/log/airtime/show-recorder/main" + ); + +foreach ($pathnames as $pn){ + echo "Removing $pn\n"; + exec("rm -rf ".$pn); +} + + +$values = parse_ini_file(CONF_FILE_AIRTIME, true); +$phpDir = $values['general']['airtime_dir']; + +InstallPhpCode($phpDir); + +//update utils (/usr/lib/airtime) folder +UninstallBinaries(); +InstallBinaries(); diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py index 0dcd423c7..84e1a4d43 100644 --- a/python_apps/api_clients/api_client.py +++ b/python_apps/api_clients/api_client.py @@ -22,13 +22,13 @@ from urlparse import urlparse AIRTIME_VERSION = "1.9.0-devel" def api_client_factory(config): + logger = logging.getLogger() if config["api_client"] == "airtime": return AirTimeApiClient(config) elif config["api_client"] == "obp": return ObpApiClient(config) else: - print 'API Client "'+config["api_client"]+'" not supported. Please check your config file.' - print + logger.info('API Client "'+config["api_client"]+'" not supported. Please check your config file.\n') sys.exit() def recursive_urlencode(d): @@ -152,24 +152,25 @@ class AirTimeApiClient(ApiClientInterface): response_json = json.loads(data) version = response_json['version'] logger.debug("Airtime Version %s detected", version) - except Exception, e: + except IOError, e: + logger.error("Unable to detect Airtime Version - %s, Response: %s", e, data) if e[1] == 401: if (verbose): - print '#####################################' - print '# YOUR API KEY SEEMS TO BE INVALID:' - print '# ' + self.config["api_key"] - print '#####################################' - return -1 + logger.info('#####################################') + logger.info('# YOUR API KEY SEEMS TO BE INVALID:') + logger.info('# ' + self.config["api_key"]) + logger.info('#####################################') if e[1] == 404: if (verbose): - print '#####################################' - print '# Unable to contact the Airtime-API' - print '# ' + url - print '#####################################' - return -1 - - logger.error("Unable to detect Airtime Version - %s, Response: %s", e, response) + logger.info('#####################################') + logger.info('# Unable to contact the Airtime-API') + logger.info('# ' + url) + logger.info('#####################################') + return -1 + except Exception, e: + logger.error("Unable to detect Airtime Version - %s, Response: %s", e, data) + return -1 return version @@ -190,23 +191,21 @@ class AirTimeApiClient(ApiClientInterface): def is_server_compatible(self, verbose = True): + logger = logging.getLogger() version = self.__get_airtime_version(verbose) if (version == -1): if (verbose): - print 'Unable to get Airtime version number.' - print + logger.info('Unable to get Airtime version number.\n') return False elif (version[0:3] != AIRTIME_VERSION[0:3]): if (verbose): - print 'Airtime version found: ' + str(version) - print 'pypo is at version ' +AIRTIME_VERSION+' and is not compatible with this version of Airtime.' - print + logger.info('Airtime version found: ' + str(version)) + logger.info('pypo is at version ' +AIRTIME_VERSION+' and is not compatible with this version of Airtime.\n') return False else: if (verbose): - print 'Airtime version: ' + str(version) - print 'pypo is at version ' +AIRTIME_VERSION+' and is compatible with this version of Airtime.' - print + logger.info('Airtime version: ' + str(version)) + logger.info('pypo is at version ' +AIRTIME_VERSION+' and is compatible with this version of Airtime.') return True @@ -226,7 +225,7 @@ class AirTimeApiClient(ApiClientInterface): response = json.loads(response_json) status = response['check'] except Exception, e: - print e + logger.error(e) return status, response @@ -319,6 +318,7 @@ class AirTimeApiClient(ApiClientInterface): except Exception, e: logger.error("Exception: %s", e) + response = None return response @@ -393,29 +393,25 @@ class ObpApiClient(): self.api_auth = urllib.urlencode({'api_key': self.config["api_key"]}) def is_server_compatible(self, verbose = True): + logger = logging.getLogger() obp_version = self.get_obp_version() if obp_version == 0: if (verbose): - print '#################################################' - print 'Unable to get OBP version. Is OBP up and running?' - print '#################################################' - print + logger.error('Unable to get OBP version. Is OBP up and running?\n') return False elif obp_version < OBP_MIN_VERSION: if (verbose): - print 'OBP version: ' + str(obp_version) - print 'OBP min-version: ' + str(OBP_MIN_VERSION) - print 'pypo not compatible with this version of OBP' - print + logger.warn('OBP version: ' + str(obp_version)) + logger.warn('OBP min-version: ' + str(OBP_MIN_VERSION)) + logger.warn('pypo not compatible with this version of OBP\n') return False else: if (verbose): - print 'OBP API: ' + str(API_BASE) - print 'OBP version: ' + str(obp_version) - print 'OBP min-version: ' + str(OBP_MIN_VERSION) - print 'pypo is compatible with this version of OBP' - print + logger.warn('OBP API: ' + str(API_BASE)) + logger.warn('OBP version: ' + str(obp_version)) + logger.warn('OBP min-version: ' + str(OBP_MIN_VERSION)) + logger.warn('pypo is compatible with this version of OBP\n') return True @@ -437,10 +433,10 @@ class ObpApiClient(): except Exception, e: try: if e[1] == 401: - print '#####################################' - print '# YOUR API KEY SEEMS TO BE INVALID' - print '# ' + self.config["api_auth"] - print '#####################################' + logger.error('#####################################') + logger.error('# YOUR API KEY SEEMS TO BE INVALID') + logger.error('# ' + self.config["api_auth"]) + logger.error('#####################################') sys.exit() except Exception, e: @@ -448,10 +444,10 @@ class ObpApiClient(): try: if e[1] == 404: - print '#####################################' - print '# Unable to contact the OBP-API' - print '# ' + url - print '#####################################' + logger.error('#####################################') + logger.error('# Unable to contact the OBP-API') + logger.error('# ' + url) + logger.error('#####################################') sys.exit() except Exception, e: @@ -502,15 +498,14 @@ class ObpApiClient(): logger.info("export status %s", response['check']) status = response['check'] except Exception, e: - print e + logger.error(e) return status, response def get_media(self, src, dest): try: - print '** urllib auth with: ', - print self.api_auth + logger.info('** urllib auth with: ' + self.api_auth) urllib.urlretrieve(src, dst, False, self.api_auth) logger.info("downloaded %s to %s", src, dst) except Exception, e: @@ -535,7 +530,6 @@ class ObpApiClient(): logger.info("API-Message %s", response['message']) except Exception, e: - print e api_status = False logger.error("Unable to connect to the OBP API - %s", e) @@ -561,7 +555,7 @@ class ObpApiClient(): url = url.replace("%%media_id%%", str(media_id)) url = url.replace("%%playlist_id%%", str(playlist_id)) url = url.replace("%%transmission_id%%", str(transmission_id)) - print url + logger.info(url) try: response = urllib.urlopen(url, self.api_auth) @@ -571,7 +565,6 @@ class ObpApiClient(): logger.info("TXT %s", response['str_dls']) except Exception, e: - print e api_status = False logger.error("Unable to connect to the OBP API - %s", e) @@ -592,7 +585,6 @@ class ObpApiClient(): logger.info("API-Message %s", response['message']) except Exception, e: - print e api_status = False logger.error("Unable to handle the OBP API request - %s", e) diff --git a/python_apps/create-pypo-user.py b/python_apps/create-pypo-user.py new file mode 100644 index 000000000..38619a0f3 --- /dev/null +++ b/python_apps/create-pypo-user.py @@ -0,0 +1,33 @@ +import os +from subprocess import Popen, PIPE, STDOUT + +def create_user(username): + print "Checking for user "+username + + p = Popen('id '+username, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) + output = p.stdout.read() + + if (output[0:3] != "uid"): + # Make the pypo user + print "Creating user "+username + os.system("adduser --system --quiet --group --shell /bin/bash "+username) + + #set pypo password + p = os.popen('/usr/bin/passwd pypo 1>/dev/null 2>&1', 'w') + p.write('pypo\n') + p.write('pypo\n') + p.close() + else: + print "User already exists." + #add pypo to audio group + os.system("adduser " + username + " audio 1>/dev/null 2>&1") + #add pypo to www-data group + os.system("adduser " + username + " www-data 1>/dev/null 2>&1") + + +if __name__ == "__main__": + if os.geteuid() != 0: + print "Please run this as root." + sys.exit(1) + + create_user("pypo") diff --git a/python_apps/media-monitor/MediaMonitor.py b/python_apps/media-monitor/MediaMonitor.py index 38423fcc9..afb249f73 100644 --- a/python_apps/media-monitor/MediaMonitor.py +++ b/python_apps/media-monitor/MediaMonitor.py @@ -31,9 +31,10 @@ except Exception, e: # loading config file try: - config = ConfigObj('/etc/airtime/MediaMonitor.cfg') + config = ConfigObj('/etc/airtime/media-monitor.cfg') except Exception, e: - print 'Error loading config file: ', e + logger = logging.getLogger(); + logger.error('Error loading config file: %s', e) sys.exit() """ diff --git a/python_apps/media-monitor/install/media-monitor-daemontools.sh b/python_apps/media-monitor/airtime-media-monitor similarity index 69% rename from python_apps/media-monitor/install/media-monitor-daemontools.sh rename to python_apps/media-monitor/airtime-media-monitor index d629ec49d..26c5e7999 100755 --- a/python_apps/media-monitor/install/media-monitor-daemontools.sh +++ b/python_apps/media-monitor/airtime-media-monitor @@ -1,5 +1,4 @@ #!/bin/sh -media_monitor_user="pypo" # Location of pypo_cli.py Python script media_monitor_path="/usr/lib/airtime/media-monitor/" @@ -8,10 +7,11 @@ media_monitor_script="MediaMonitor.py" api_client_path="/usr/lib/airtime/pypo/" cd ${media_monitor_path} -echo "*** Daemontools: starting daemon" exec 2>&1 -# Note the -u when calling python! we need it to get unbuffered binary stdout and stderr export PYTHONPATH=${api_client_path} -setuidgid ${media_monitor_user} python -u ${media_monitor_path}${media_monitor_script} + +# Note the -u when calling python! we need it to get unbuffered binary stdout and stderr +exec python -u ${media_monitor_path}${media_monitor_script} + # EOF diff --git a/python_apps/media-monitor/airtime-media-monitor-init-d b/python_apps/media-monitor/airtime-media-monitor-init-d new file mode 100755 index 000000000..afe45e137 --- /dev/null +++ b/python_apps/media-monitor/airtime-media-monitor-init-d @@ -0,0 +1,58 @@ +#!/bin/bash + +### BEGIN INIT INFO +# Provides: airtime-media-monitor +# Required-Start: $local_fs $remote_fs $network $syslog +# Required-Stop: $local_fs $remote_fs $network $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Manage airtime-media-monitor daemon +### END INIT INFO + +USERID=pypo +GROUPID=pypo +NAME=Airtime + +DAEMON=/usr/bin/airtime-media-monitor +PIDFILE=/var/run/airtime-media-monitor.pid + +start () { + start-stop-daemon --start --background --quiet --chuid $USERID:$GROUPID --make-pidfile --pidfile $PIDFILE --startas $DAEMON +} + +stop () { + # Send TERM after 5 seconds, wait at most 30 seconds. + start-stop-daemon --stop --oknodo --retry TERM/5/0/30 --quiet --pidfile $PIDFILE + rm -f $PIDFILE +} + + +case "${1:-''}" in + 'start') + # start commands here + echo -n "Starting $NAME: " + start + echo "Done." + ;; + 'stop') + # stop commands here + echo -n "Stopping $NAME: " + stop + echo "Done." + ;; + 'restart') + # restart commands here + echo -n "Restarting $NAME: " + stop + start + echo "Done." + ;; + 'status') + # status commands here + /usr/bin/airtime-check-system + ;; + *) # no parameter specified + echo "Usage: $SELF start|stop|restart|status" + exit 1 + ;; +esac diff --git a/python_apps/media-monitor/airtime-media-monitor-start b/python_apps/media-monitor/airtime-media-monitor-start deleted file mode 100755 index 2b50bb0f4..000000000 --- a/python_apps/media-monitor/airtime-media-monitor-start +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys - -if os.geteuid() != 0: - print "Please run this as root." - sys.exit(1) - -try: - print "Starting daemontool script recorder" - os.system("svc -u /etc/service/recorder") - os.system("svc -u /etc/service/recorder/log") - -except Exception, e: - print "exception:" + str(e) diff --git a/python_apps/media-monitor/airtime-media-monitor-stop b/python_apps/media-monitor/airtime-media-monitor-stop deleted file mode 100755 index 735464dd8..000000000 --- a/python_apps/media-monitor/airtime-media-monitor-stop +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys -import subprocess - -if os.geteuid() != 0: - print "Please run this as root." - sys.exit(1) - -try: - print "Stopping daemontool script recorder" - - p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) - p2 = subprocess.Popen(["awk", "/recorder.py/ && !/awk/ {print $2}"], stdin=p1.stdout, stdout=subprocess.PIPE) - recorder_pid = p2.communicate()[0].strip(" \n\r\t") - if (len(recorder_pid) > 0): - os.system("svc -d /etc/service/recorder 1>/dev/null 2>&1") - os.system("svc -d /etc/service/recorder/log 1>/dev/null 2>&1") - os.system("kill -2 %s" % recorder_pid) - print "Shutting down process id %s" % recorder_pid - print "Success." - else: - print "Not Running." - -except Exception, e: - print "exception:" + str(e) diff --git a/python_apps/media-monitor/install/media-monitor-daemontools-logger.sh b/python_apps/media-monitor/install/media-monitor-daemontools-logger.sh deleted file mode 100755 index 6819f837d..000000000 --- a/python_apps/media-monitor/install/media-monitor-daemontools-logger.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec setuidgid pypo multilog t /var/log/airtime/media-monitor/main diff --git a/python_apps/media-monitor/install/media-monitor-install.py b/python_apps/media-monitor/install/media-monitor-install.py index 8f3fb804e..36f491c57 100755 --- a/python_apps/media-monitor/install/media-monitor-install.py +++ b/python_apps/media-monitor/install/media-monitor-install.py @@ -14,40 +14,19 @@ import shutil import string import platform from configobj import ConfigObj -from subprocess import Popen, PIPE, STDOUT +from subprocess import Popen if os.geteuid() != 0: print "Please run this as root." sys.exit(1) -PATH_INI_FILE = '/etc/airtime/MediaMonitor.cfg' +PATH_INI_FILE = '/etc/airtime/media-monitor.cfg' def create_path(path): if not (os.path.exists(path)): print "Creating directory " + path os.makedirs(path) -def create_user(username): - print "Checking for user "+username - p = Popen('id '+username, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - if (output[0:3] != "uid"): - # Make the pypo user - print "Creating user "+username - os.system("adduser --system --quiet --group --shell /bin/bash "+username) - - #set pypo password - p = os.popen('/usr/bin/passwd pypo 1>/dev/null 2>&1', 'w') - p.write('pypo\n') - p.write('pypo\n') - p.close() - else: - print "User already exists." - #add pypo to audio group - os.system("adduser " + username + " audio 1>/dev/null 2>&1") - #add pypo to www-data group - os.system("adduser " + username + " www-data 1>/dev/null 2>&1") - def copy_dir(src_dir, dest_dir): if (os.path.exists(dest_dir)) and (dest_dir != "/"): print "Removing old directory "+dest_dir @@ -59,7 +38,6 @@ def copy_dir(src_dir, dest_dir): def get_current_script_dir(): current_script_dir = os.path.realpath(__file__) index = current_script_dir.rindex('/') - #print current_script_dir[0:index] return current_script_dir[0:index] @@ -69,15 +47,12 @@ try: config = ConfigObj(PATH_INI_FILE) except Exception, e: print 'Error loading config file: ', e - sys.exit() + sys.exit(1) current_script_dir = get_current_script_dir() - print "Checking and removing any existing media monitor processes" - os.system("python %s/media-monitor-uninstall.py 1>/dev/null 2>&1"% current_script_dir) - time.sleep(5) - # Create users - create_user("pypo") + p = Popen("/etc/init.d/airtime-media-monitor stop >/dev/null 2>&1", shell=True) + sts = os.waitpid(p.pid, 0)[1] print "Creating log directories" create_path(config["log_dir"]) @@ -91,37 +66,20 @@ try: os.system("chown -R pypo:pypo "+config["bin_dir"]) print "Creating symbolic links" - os.system("rm -f /usr/bin/airtime-media-monitor-start") - os.system("ln -s "+config["bin_dir"]+"/airtime-media-monitor-start /usr/bin/") - os.system("rm -f /usr/bin/airtime-media-monitor-stop") - os.system("ln -s "+config["bin_dir"]+"/airtime-media-monitor-stop /usr/bin/") - - print "Installing recorder daemon" - create_path("/etc/service/media-monitor") - create_path("/etc/service/media-monitor/log") - shutil.copy("%s/media-monitor-daemontools.sh"%current_script_dir, "/etc/service/media-monitor/run") - shutil.copy("%s/media-monitor-daemontools-logger.sh"%current_script_dir, "/etc/service/media-monitor/log/run") - os.system("chmod -R 755 /etc/service/media-monitor") - os.system("chown -R pypo:pypo /etc/service/media-monitor") + os.system("rm -f /usr/bin/airtime-media-monitor") + os.system("ln -s "+config["bin_dir"]+"/airtime-media-monitor /usr/bin/") + + print "Installing media-monitor daemon" + shutil.copy(config["bin_dir"]+"/airtime-media-monitor-init-d", "/etc/init.d/airtime-media-monitor") + + p = Popen("update-rc.d airtime-media-monitor defaults", shell=True) + sts = os.waitpid(p.pid, 0)[1] print "Waiting for processes to start..." - time.sleep(5) - os.system("python /usr/bin/airtime-media-monitor-start") - time.sleep(2) + p = Popen("/etc/init.d/airtime-media-monitor start", shell=True) + sts = os.waitpid(p.pid, 0)[1] - found = True - - p = Popen('svstat /etc/service/media-monitor', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - if (output.find("unable to open supervise/ok: file does not exist") >= 0): - found = False - print output - - if not found: - print "Media monitor install has completed, but daemontools is not running, please make sure you have it installed and then reboot." except Exception, e: print "exception:" + str(e) sys.exit(1) - - diff --git a/python_apps/media-monitor/install/media-monitor-uninstall.py b/python_apps/media-monitor/install/media-monitor-uninstall.py index e0a5ca262..d2732bffb 100755 --- a/python_apps/media-monitor/install/media-monitor-uninstall.py +++ b/python_apps/media-monitor/install/media-monitor-uninstall.py @@ -3,27 +3,17 @@ import os import sys -import time from configobj import ConfigObj if os.geteuid() != 0: print "Please run this as root." sys.exit(1) -PATH_INI_FILE = '/etc/airtime/MediaMonitor.cfg' +PATH_INI_FILE = '/etc/airtime/media-monitor.cfg' def remove_path(path): os.system("rm -rf " + path) -def remove_user(username): - os.system("killall -u %s 1>/dev/null 2>&1" % username) - - #allow all process to be completely closed before we attempt to delete user - print "Waiting for processes to close..." - time.sleep(5) - - os.system("deluser --remove-home " + username + " 1>/dev/null 2>&1") - def get_current_script_dir(): current_script_dir = os.path.realpath(__file__) index = current_script_dir.rindex('/') @@ -35,24 +25,21 @@ try: config = ConfigObj(PATH_INI_FILE) except Exception, e: print 'Error loading config file: ', e - sys.exit() + sys.exit(1) - os.system("python /usr/bin/airtime-media-monitor-stop") + os.system("/etc/init.d/airtime-media-monitor stop") + os.system("rm -f /etc/init.d/airtime-media-monitor") + os.system("update-rc.d -f airtime-media-monitor remove") print "Removing log directories" remove_path(config["log_dir"]) print "Removing symlinks" - os.system("rm -f /usr/bin/airtime-media-monitor-start") - os.system("rm -f /usr/bin/airtime-media-monitor-stop") + os.system("rm -f /usr/bin/airtime-media-monitor") print "Removing application files" remove_path(config["bin_dir"]) - print "Removing daemontool script media-monitor" - remove_path("rm -rf /etc/service/media-monitor") - - remove_user("pypo") print "Uninstall complete." except Exception, e: print "exception:" + str(e) diff --git a/python_apps/media-monitor/logging.cfg b/python_apps/media-monitor/logging.cfg index 251fce8d7..c0a43564c 100644 --- a/python_apps/media-monitor/logging.cfg +++ b/python_apps/media-monitor/logging.cfg @@ -2,20 +2,20 @@ keys=root [handlers] -keys=consoleHandler +keys=fileOutHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG -handlers=consoleHandler +handlers=fileOutHandler -[handler_consoleHandler] -class=StreamHandler +[handler_fileOutHandler] +class=logging.handlers.RotatingFileHandler level=DEBUG formatter=simpleFormatter -args=(sys.stdout,) +args=("/var/log/airtime/media-monitor/media-monitor.log", 'a', 1000000, 5,) [formatter_simpleFormatter] format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s diff --git a/python_apps/media-monitor/MediaMonitor.cfg b/python_apps/media-monitor/media-monitor.cfg similarity index 100% rename from python_apps/media-monitor/MediaMonitor.cfg rename to python_apps/media-monitor/media-monitor.cfg diff --git a/python_apps/pypo/install/pypo-daemontools-liquidsoap.sh b/python_apps/pypo/airtime-liquidsoap similarity index 79% rename from python_apps/pypo/install/pypo-daemontools-liquidsoap.sh rename to python_apps/pypo/airtime-liquidsoap index 6c4ebe65a..377ae9a3c 100755 --- a/python_apps/pypo/install/pypo-daemontools-liquidsoap.sh +++ b/python_apps/pypo/airtime-liquidsoap @@ -10,8 +10,6 @@ exec 2>&1 cd /usr/lib/airtime/pypo/bin/scripts export PYTHONPATH=${api_client_path} -#su ${ls_user} -c "${ls_path} ${ls_param}" 2>&1 - -setuidgid ${ls_user} ${ls_path} ${ls_param} +exec ${ls_path} ${ls_param} # EOF diff --git a/python_apps/pypo/install/pypo-daemontools.sh b/python_apps/pypo/airtime-playout similarity index 64% rename from python_apps/pypo/install/pypo-daemontools.sh rename to python_apps/pypo/airtime-playout index 891c3b259..995575622 100755 --- a/python_apps/pypo/install/pypo-daemontools.sh +++ b/python_apps/pypo/airtime-playout @@ -1,18 +1,18 @@ #!/bin/sh + pypo_user="pypo" -export HOME="/var/tmp/airtime/pypo/" + # Location of pypo_cli.py Python script pypo_path="/usr/lib/airtime/pypo/bin/" api_client_path="/usr/lib/airtime/pypo/" pypo_script="pypo-cli.py" -echo "*** Daemontools: starting daemon" cd ${pypo_path} exec 2>&1 -PYTHONPATH=${api_client_path}:$PYTHONPATH -export PYTHONPATH +export HOME="/var/tmp/airtime/pypo/" +export PYTHONPATH=${api_client_path}:$PYTHONPATH # Note the -u when calling python! we need it to get unbuffered binary stdout and stderr -exec setuidgid ${pypo_user} \ - python -u ${pypo_path}${pypo_script} +exec python -u ${pypo_path}${pypo_script} + # EOF diff --git a/python_apps/pypo/airtime-playout-init-d b/python_apps/pypo/airtime-playout-init-d new file mode 100755 index 000000000..5634baa13 --- /dev/null +++ b/python_apps/pypo/airtime-playout-init-d @@ -0,0 +1,64 @@ +#!/bin/bash + +### BEGIN INIT INFO +# Provides: airtime-playout +# Required-Start: $local_fs $remote_fs $network $syslog +# Required-Stop: $local_fs $remote_fs $network $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Manage airtime-playout daemon +### END INIT INFO + +USERID=pypo +GROUPID=pypo +NAME=Airtime + +DAEMON0=/usr/bin/airtime-playout +PIDFILE0=/var/run/airtime-playout.pid + +DAEMON1=/usr/bin/airtime-liquidsoap +PIDFILE1=/var/run/airtime-liquidsoap.pid + +start () { + start-stop-daemon --start --background --quiet --chuid $USERID:$GROUPID --make-pidfile --pidfile $PIDFILE0 --startas $DAEMON0 + start-stop-daemon --start --background --quiet --chuid $USERID:$GROUPID --make-pidfile --pidfile $PIDFILE1 --startas $DAEMON1 +} + +stop () { + # Send TERM after 5 seconds, wait at most 30 seconds. + start-stop-daemon --stop --oknodo --retry TERM/5/0/30 --quiet --pidfile $PIDFILE0 + start-stop-daemon --stop --oknodo --retry TERM/5/0/30 --quiet --pidfile $PIDFILE1 + rm -f $PIDFILE0 + rm -f $PIDFILE1 +} + + +case "${1:-''}" in + 'start') + # start commands here + echo -n "Starting $NAME: " + start + echo "Done." + ;; + 'stop') + # stop commands here + echo -n "Stopping $NAME: " + stop + echo "Done." + ;; + 'restart') + # restart commands here + echo -n "Restarting $NAME: " + stop + start + echo "Done." + ;; + 'status') + # status commands here + /usr/bin/airtime-check-system + ;; + *) # no parameter specified + echo "Usage: $SELF start|stop|restart|status" + exit 1 + ;; +esac diff --git a/python_apps/pypo/airtime-pypo-start b/python_apps/pypo/airtime-pypo-start deleted file mode 100755 index 68e323c6c..000000000 --- a/python_apps/pypo/airtime-pypo-start +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys - -if os.geteuid() != 0: - print "Please run this as root." - sys.exit(1) - -try: - print "Starting daemontool script pypo" - os.system("svc -u /etc/service/pypo") - os.system("svc -u /etc/service/pypo/log") - - print "Starting daemontool script pypo-liquidsoap" - os.system("svc -u /etc/service/pypo-liquidsoap") - os.system("svc -u /etc/service/pypo-liquidsoap/log") - -except Exception, e: - print "exception:" + str(e) diff --git a/python_apps/pypo/airtime-pypo-stop b/python_apps/pypo/airtime-pypo-stop deleted file mode 100755 index 009be17fc..000000000 --- a/python_apps/pypo/airtime-pypo-stop +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys -import subprocess - -if os.geteuid() != 0: - print "Please run this as root." - sys.exit(1) - -try: - print "Stopping daemontool script pypo..." - p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) - p2 = subprocess.Popen(["awk", "/pypo-cli.py/ && !/awk/ {print $2}"], stdin=p1.stdout, stdout=subprocess.PIPE) - pypo_pid = p2.communicate()[0].strip(" \n\r\t") - if (len(pypo_pid) > 0): - os.system("svc -d /etc/service/pypo 1>/dev/null 2>&1") - os.system("svc -d /etc/service/pypo/log 1>/dev/null 2>&1") - print "Shutting down process id %s" % pypo_pid - print "Success." - else: - print "Not Running." - - print "Stopping daemontool script pypo-liquidsoap..." - p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) - p2 = subprocess.Popen(["awk", "/ls_script.liq/ && !/awk/ {print $2}"], stdin=p1.stdout, stdout=subprocess.PIPE) - liquidsoap_pid = p2.communicate()[0].strip(" \n\r\t") - if (len(liquidsoap_pid) > 0): - os.system("svc -d /etc/service/pypo-liquidsoap 1>/dev/null 2>&1") - os.system("svc -d /etc/service/pypo-liquidsoap/log 1>/dev/null 2>&1") - - pids = liquidsoap_pid.split("\n") - for pid in pids: - os.system("kill -2 %s" % pid) - print "Shutting down process id %s" % liquidsoap_pid - print "Success." - else: - print "Not Running." - -except Exception, e: - print "exception:" + str(e) diff --git a/python_apps/pypo/install/pypo-daemontools-logger.sh b/python_apps/pypo/install/pypo-daemontools-logger.sh deleted file mode 100755 index 249bfd78b..000000000 --- a/python_apps/pypo/install/pypo-daemontools-logger.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec setuidgid pypo multilog t /var/log/airtime/pypo/main diff --git a/python_apps/pypo/install/pypo-install.py b/python_apps/pypo/install/pypo-install.py index 716521d88..29b3edb58 100755 --- a/python_apps/pypo/install/pypo-install.py +++ b/python_apps/pypo/install/pypo-install.py @@ -3,18 +3,12 @@ import time import os -import traceback from optparse import * import sys -import time -import datetime -import logging -import logging.config import shutil -import string import platform from configobj import ConfigObj -from subprocess import Popen, PIPE, STDOUT +from subprocess import Popen if os.geteuid() != 0: print "Please run this as root." @@ -26,29 +20,6 @@ def create_path(path): if not (os.path.exists(path)): print "Creating directory " + path os.makedirs(path) - else: - print "Directory already exists " + path - -def create_user(username): - print "Checking for user "+username - p = Popen('id '+username, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - if (output[0:3] != "uid"): - # Make the pypo user - print "Creating user "+username - os.system("adduser --system --quiet --group --shell /bin/bash "+username) - - #set pypo password - p = os.popen('/usr/bin/passwd pypo 1>/dev/null 2>&1', 'w') - p.write('pypo\n') - p.write('pypo\n') - p.close() - else: - print "User already exists." - #add pypo to audio group - os.system("adduser " + username + " audio 1>/dev/null 2>&1") - #add pypo to pulse-access group - #os.system("adduser " + username + " pulse-access 1>/dev/null 2>&1") def copy_dir(src_dir, dest_dir): if (os.path.exists(dest_dir)) and (dest_dir != "/"): @@ -61,7 +32,6 @@ def copy_dir(src_dir, dest_dir): def get_current_script_dir(): current_script_dir = os.path.realpath(__file__) index = current_script_dir.rindex('/') - #print current_script_dir[0:index] return current_script_dir[0:index] def is_natty(): @@ -86,15 +56,12 @@ try: config = ConfigObj(PATH_INI_FILE) except Exception, e: print 'Error loading config file: ', e - sys.exit() + sys.exit(1) current_script_dir = get_current_script_dir() - print "Checking and removing any existing pypo processes" - os.system("python %s/pypo-uninstall.py 1>/dev/null 2>&1"% current_script_dir) - time.sleep(5) - # Create users - create_user("pypo") + p = Popen("/etc/init.d/airtime-playout stop >/dev/null 2>&1", shell=True) + sts = os.waitpid(p.pid, 0)[1] create_path(config["pypo_log_dir"]) os.system("chmod -R 755 " + config["pypo_log_dir"]) @@ -135,51 +102,26 @@ try: os.system("chmod -R 755 "+config["bin_dir"]) os.system("chown -R pypo:pypo "+config["bin_dir"]) os.system("chown -R pypo:pypo "+config["cache_base_dir"]) - + print "Creating symbolic links" - os.system("rm -f /usr/bin/airtime-pypo-start") - os.system("ln -s "+config["bin_dir"]+"/bin/airtime-pypo-start /usr/bin/") - os.system("rm -f /usr/bin/airtime-pypo-stop") - os.system("ln -s "+config["bin_dir"]+"/bin/airtime-pypo-stop /usr/bin/") - + os.system("rm -f /usr/bin/airtime-playout") + os.system("ln -s "+config["bin_dir"]+"/bin/airtime-playout /usr/bin/") + os.system("rm -f /usr/bin/airtime-liquidsoap") + os.system("ln -s "+config["bin_dir"]+"/bin/airtime-liquidsoap /usr/bin/") + print "Installing pypo daemon" - create_path("/etc/service/pypo") - create_path("/etc/service/pypo/log") - shutil.copy("%s/pypo-daemontools.sh"%current_script_dir, "/etc/service/pypo/run") - shutil.copy("%s/pypo-daemontools-logger.sh"%current_script_dir, "/etc/service/pypo/log/run") - os.system("chmod -R 755 /etc/service/pypo") - os.system("chown -R pypo:pypo /etc/service/pypo") - - print "Installing liquidsoap daemon" - create_path("/etc/service/pypo-liquidsoap") - create_path("/etc/service/pypo-liquidsoap/log") - shutil.copy("%s/pypo-daemontools-liquidsoap.sh"%current_script_dir, "/etc/service/pypo-liquidsoap/run") - shutil.copy("%s/pypo-liquidsoap-daemontools-logger.sh"%current_script_dir, "/etc/service/pypo-liquidsoap/log/run") - os.system("chmod -R 755 /etc/service/pypo-liquidsoap") - os.system("chown -R pypo:pypo /etc/service/pypo-liquidsoap") + shutil.copy(config["bin_dir"]+"/bin/airtime-playout-init-d", "/etc/init.d/airtime-playout") + + p = Popen("update-rc.d airtime-playout defaults", shell=True) + sts = os.waitpid(p.pid, 0)[1] print "Waiting for processes to start..." - time.sleep(5) - os.system("python /usr/bin/airtime-pypo-start") - time.sleep(2) - - found = True - - p = Popen('svstat /etc/service/pypo', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - if (output.find("unable to open supervise/ok: file does not exist") >= 0): - found = False - print output - - p = Popen('svstat /etc/service/pypo-liquidsoap', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - print output - - if not found: - print "Pypo install has completed, but daemontools is not running, please make sure you have it installed and then reboot." + p = Popen("/etc/init.d/airtime-playout start", shell=True) + sts = os.waitpid(p.pid, 0)[1] + + except Exception, e: print "exception:" + str(e) sys.exit(1) - diff --git a/python_apps/pypo/install/pypo-liquidsoap-daemontools-logger.sh b/python_apps/pypo/install/pypo-liquidsoap-daemontools-logger.sh deleted file mode 100644 index 98ac88c3b..000000000 --- a/python_apps/pypo/install/pypo-liquidsoap-daemontools-logger.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec setuidgid pypo multilog t /var/log/airtime/pypo-liquidsoap/main diff --git a/python_apps/pypo/install/pypo-uninstall.py b/python_apps/pypo/install/pypo-uninstall.py index 242787a25..bfa77eb0e 100755 --- a/python_apps/pypo/install/pypo-uninstall.py +++ b/python_apps/pypo/install/pypo-uninstall.py @@ -3,7 +3,6 @@ import os import sys -import time from configobj import ConfigObj if os.geteuid() != 0: @@ -15,15 +14,6 @@ PATH_INI_FILE = '/etc/airtime/pypo.cfg' def remove_path(path): os.system("rm -rf " + path) -def remove_user(username): - os.system("killall -u %s 1>/dev/null 2>&1" % username) - - #allow all process to be completely closed before we attempt to delete user - print "Waiting for processes to close..." - time.sleep(5) - - os.system("deluser --remove-home " + username + " 1>/dev/null 2>&1") - def get_current_script_dir(): current_script_dir = os.path.realpath(__file__) index = current_script_dir.rindex('/') @@ -35,33 +25,21 @@ try: config = ConfigObj(PATH_INI_FILE) except Exception, e: print 'Error loading config file: ', e - sys.exit() + sys.exit(1) - os.system("python /usr/bin/airtime-pypo-stop") + os.system("/etc/init.d/airtime-playout stop") + os.system("rm -f /etc/init.d/airtime-playout") + os.system("update-rc.d -f airtime-playout remove") print "Removing cache directories" remove_path(config["cache_base_dir"]) print "Removing symlinks" - os.system("rm -f /usr/bin/airtime-pypo-start") - os.system("rm -f /usr/bin/airtime-pypo-stop") + os.system("rm -f /usr/bin/airtime-playout") print "Removing pypo files" remove_path(config["bin_dir"]) - print "Removing daemontool script pypo" - remove_path("/etc/service/pypo") - - if os.path.exists("/etc/service/pypo-fetch"): - remove_path("/etc/service/pypo-fetch") - - if os.path.exists("/etc/service/pypo-push"): - remove_path("/etc/service/pypo-push") - - print "Removing daemontool script pypo-liquidsoap" - remove_path("/etc/service/pypo-liquidsoap") - - remove_user("pypo") print "Pypo uninstall complete." except Exception, e: print "exception:" + str(e) diff --git a/python_apps/pypo/logging.cfg b/python_apps/pypo/logging.cfg index 7b679d40c..234a094f0 100644 --- a/python_apps/pypo/logging.cfg +++ b/python_apps/pypo/logging.cfg @@ -1,33 +1,39 @@ [loggers] -keys=root,fetch,push +keys=root,fetch,push,cue_file [handlers] -keys=consoleHandler +keys=fileOutHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG -handlers=consoleHandler +handlers=fileOutHandler [logger_fetch] level=DEBUG -handlers=consoleHandler +handlers=fileOutHandler qualname=fetch propagate=0 [logger_push] level=DEBUG -handlers=consoleHandler +handlers=fileOutHandler qualname=push propagate=0 -[handler_consoleHandler] -class=StreamHandler +[logger_cue_file] +level=DEBUG +handlers=fileOutHandler +qualname=push +propagate=0 + +[handler_fileOutHandler] +class=logging.handlers.RotatingFileHandler level=DEBUG formatter=simpleFormatter -args=(sys.stdout,) +args=("/var/log/airtime/pypo/pypo.log", 'a', 1000000, 5,) [formatter_simpleFormatter] format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s diff --git a/python_apps/pypo/pypo-cli.py b/python_apps/pypo/pypo-cli.py index ab83eb94f..3ac2e8f50 100755 --- a/python_apps/pypo/pypo-cli.py +++ b/python_apps/pypo/pypo-cli.py @@ -11,6 +11,7 @@ import os import signal import logging import logging.config +import logging.handlers from Queue import Queue from pypopush import PypoPush @@ -48,7 +49,8 @@ logging.config.fileConfig("logging.cfg") try: config = ConfigObj('/etc/airtime/pypo.cfg') except Exception, e: - print 'Error loading config file: ', e + logger = logging.getLogger() + logger.error('Error loading config file: %s', e) sys.exit() class Global: @@ -70,6 +72,7 @@ class Global: def test_api(self): self.api_client.test() +""" def check_schedule(self, export_source): logger = logging.getLogger() @@ -96,27 +99,33 @@ class Global: for media in playlist['medias']: print media +""" def keyboardInterruptHandler(signum, frame): - print "\nKeyboard Interrupt\n" - sys.exit(); + logger = logging.getLogger() + logger.info('\nKeyboard Interrupt\n') + sys.exit(0) if __name__ == '__main__': - print '###########################################' - print '# *** pypo *** #' - print '# Liquidsoap Scheduled Playout System #' - print '###########################################' + logger = logging.getLogger() + logger.info('###########################################') + logger.info('# *** pypo *** #') + logger.info('# Liquidsoap Scheduled Playout System #') + logger.info('###########################################') signal.signal(signal.SIGINT, keyboardInterruptHandler) + + #import daemonize + #daemonize.createDaemon() + #open("airtime.pid", "w").write(str(os.getpid()) + "\n") + #daemonize.drop_privileges("pypo", "pypo") + # initialize g = Global() - #NOTE: MUST EXIT HERE!! while not g.selfcheck(): time.sleep() - #Causes pypo to hang on system boot!!! - if not g.selfcheck(): - sys.exit() + while not g.selfcheck(): time.sleep(5) logger = logging.getLogger() @@ -127,11 +136,9 @@ if __name__ == '__main__': q = Queue() pp = PypoPush(q) - pp.daemon = True pp.start() pf = PypoFetch(q) - pf.daemon = True pf.start() while True: time.sleep(3600) diff --git a/python_apps/pypo/pypo-log.sh b/python_apps/pypo/pypo-log.sh deleted file mode 100755 index 0e3c91275..000000000 --- a/python_apps/pypo/pypo-log.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh - -clear -echo -echo "##############################" -echo "# STARTING PYPO MULTI-LOG #" -echo "##############################" -sleep 1 -clear - -# split -multitail -s 2 /var/log/pypo/debug.log \ -/var/log/pypo-push/log/main/current \ -/var/log/pypo-fetch/log/main/current \ -/var/log/pypo-liquidsoap/log/main/current diff --git a/python_apps/pypo/pypofetch.py b/python_apps/pypo/pypofetch.py index 224d256ee..616a347aa 100755 --- a/python_apps/pypo/pypofetch.py +++ b/python_apps/pypo/pypofetch.py @@ -33,7 +33,8 @@ try: POLL_INTERVAL = int(config['poll_interval']) except Exception, e: - print 'Error loading config file: ', e + logger = logging.getLogger() + logger.error('Error loading config file: %s', e) sys.exit() # Yuk - using a global, i know! @@ -242,8 +243,7 @@ class PypoFetch(Thread): #logger.debug("everything ok, adding %s to playlist", pl_entry) else: - print 'zero-file: ' + dst + ' from ' + media['uri'] - logger.warning("zero-size file - skipping %s. will not add it to playlist", dst) + logger.warning("zero-size file - skipping %s. will not add it to playlist at %s", media['uri'], dst) else: logger.warning("something went wrong. file %s not available. will not add it to playlist", dst) @@ -325,8 +325,7 @@ class PypoFetch(Thread): else: logger.info('sucessfully removed %s', os.path.join(r, dir)) except Exception, e: - print e - logger.error("%s", e) + logger.error(e) """ diff --git a/python_apps/pypo/pypopush.py b/python_apps/pypo/pypopush.py index 573770694..da9e06e32 100755 --- a/python_apps/pypo/pypopush.py +++ b/python_apps/pypo/pypopush.py @@ -3,6 +3,7 @@ import sys import time import logging import logging.config +import logging.handlers import pickle import telnetlib import calendar @@ -15,6 +16,7 @@ from util import CueFile from configobj import ConfigObj + # configure logging logging.config.fileConfig("logging.cfg") @@ -25,6 +27,7 @@ try: LS_PORT = config['ls_port'] PUSH_INTERVAL = 2 except Exception, e: + logger = logging.getLogger() logger.error('Error loading config file %s', e) sys.exit() @@ -130,14 +133,19 @@ class PypoPush(Thread): else: pass #logger.debug('Empty schedule') - - if not currently_on_air and self.liquidsoap_state_play: - logger.debug('Notifying Liquidsoap to stop playback.') - tn = telnetlib.Telnet(LS_HOST, LS_PORT) - tn.write('source.skip\n') - tn.write('exit\n') - tn.read_all() + + try: + if not currently_on_air and self.liquidsoap_state_play: + logger.debug('Notifying Liquidsoap to stop playback.') + tn = telnetlib.Telnet(LS_HOST, LS_PORT) + tn.write('source.skip\n') + tn.write('exit\n') + tn.read_all() + self.liquidsoap_state_play = False + except Exception, e: self.liquidsoap_state_play = False + logger.debug('Could not connect to liquidsoap') + def push_liquidsoap(self, pkey, schedule, playlists): logger = logging.getLogger('push') diff --git a/python_apps/pypo/util/cue_file.py b/python_apps/pypo/util/cue_file.py index 8b3a158be..034515f23 100755 --- a/python_apps/pypo/util/cue_file.py +++ b/python_apps/pypo/util/cue_file.py @@ -21,7 +21,7 @@ class CueFile(): def cue(self, src, dst, cue_in, cue_out): - logger = logging.getLogger("cue_file.cue") + logger = logging.getLogger("cue_file") logger.debug("cue file: %s %s %s %s", src, dst, cue_in, cue_out) if src.lower().endswith('.mp3'): @@ -61,12 +61,10 @@ class CueFile(): command = 'mp3cut -o %s -t %s-%s %s' % (dst + '.tmp.mp3', str_cue_in, str_cue_out, src); logger.info("command: %s", command) - print command os.system(command + ' > /dev/null 2>&1') command = 'lame -b 128 %s %s' % (dst + '.tmp.mp3', dst); logger.info("command: %s", command) - print command os.system(command + ' > /dev/null 2>&1') elif src.lower().endswith('.ogg'): audio = OggVorbis(src) diff --git a/python_apps/remove-pypo-user.py b/python_apps/remove-pypo-user.py new file mode 100644 index 000000000..278d6f783 --- /dev/null +++ b/python_apps/remove-pypo-user.py @@ -0,0 +1,18 @@ +import os +import time + +def remove_user(username): + os.system("killall -u %s 1>/dev/null 2>&1" % username) + + #allow all process to be completely closed before we attempt to delete user + print "Waiting for processes to close..." + time.sleep(3) + + os.system("deluser --remove-home " + username + " 1>/dev/null 2>&1") + +if __name__ == "__main__": + if os.geteuid() != 0: + print "Please run this as root." + sys.exit(1) + + remove_user("pypo") diff --git a/python_apps/show-recorder/install/recorder-daemontools.sh b/python_apps/show-recorder/airtime-show-recorder similarity index 62% rename from python_apps/show-recorder/install/recorder-daemontools.sh rename to python_apps/show-recorder/airtime-show-recorder index f7409f600..97124ff6f 100755 --- a/python_apps/show-recorder/install/recorder-daemontools.sh +++ b/python_apps/show-recorder/airtime-show-recorder @@ -1,7 +1,7 @@ #!/bin/sh + recorder_user="pypo" -export HOME="/var/tmp/airtime/show-recorder/" -export TERM=xterm + # Location of pypo_cli.py Python script recorder_path="/usr/lib/airtime/show-recorder/" @@ -10,16 +10,14 @@ recorder_script="recorder.py" api_client_path="/usr/lib/airtime/pypo/" cd ${recorder_path} -echo "*** Daemontools: starting daemon" exec 2>&1 -# Note the -u when calling python! we need it to get unbuffered binary stdout and stderr +export HOME="/var/tmp/airtime/show-recorder/" +export TERM=xterm export PYTHONPATH=${api_client_path} -su ${recorder_user} -c "python -u ${recorder_path}${recorder_script}" - -#ecasound does not work when recorder script is called with setuidgid. -#setuidgid ${recorder_user} python -u ${recorder_path}${recorder_script} - +#this line works: su ${recorder_user} -c "python -u ${recorder_path}${recorder_script}" +# Note the -u when calling python! we need it to get unbuffered binary stdout and stderr +exec python -u ${recorder_path}${recorder_script} # EOF diff --git a/python_apps/show-recorder/airtime-show-recorder-init-d b/python_apps/show-recorder/airtime-show-recorder-init-d new file mode 100755 index 000000000..9444a307e --- /dev/null +++ b/python_apps/show-recorder/airtime-show-recorder-init-d @@ -0,0 +1,58 @@ +#!/bin/bash + +### BEGIN INIT INFO +# Provides: airtime-show-recorder +# Required-Start: $local_fs $remote_fs $network $syslog +# Required-Stop: $local_fs $remote_fs $network $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Manage airtime-show-recorder daemon +### END INIT INFO + +USERID=pypo +GROUPID=pypo +NAME=Airtime + +DAEMON=/usr/bin/airtime-show-recorder +PIDFILE=/var/run/airtime-show-recorder.pid + +start () { + start-stop-daemon --start --background --quiet --chuid $USERID:$GROUPID --make-pidfile --pidfile $PIDFILE --startas $DAEMON +} + +stop () { + # Send TERM after 5 seconds, wait at most 30 seconds. + start-stop-daemon --stop --oknodo --retry TERM/5/0/30 --quiet --pidfile $PIDFILE + rm -f $PIDFILE +} + + +case "${1:-''}" in + 'start') + # start commands here + echo -n "Starting $NAME: " + start + echo "Done." + ;; + 'stop') + # stop commands here + echo -n "Stopping $NAME: " + stop + echo "Done." + ;; + 'restart') + # restart commands here + echo -n "Restarting $NAME: " + stop + start + echo "Done." + ;; + 'status') + # status commands here + /usr/bin/airtime-check-system + ;; + *) # no parameter specified + echo "Usage: $SELF start|stop|restart|status" + exit 1 + ;; +esac diff --git a/python_apps/show-recorder/airtime-show-recorder-start b/python_apps/show-recorder/airtime-show-recorder-start deleted file mode 100755 index 2b50bb0f4..000000000 --- a/python_apps/show-recorder/airtime-show-recorder-start +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys - -if os.geteuid() != 0: - print "Please run this as root." - sys.exit(1) - -try: - print "Starting daemontool script recorder" - os.system("svc -u /etc/service/recorder") - os.system("svc -u /etc/service/recorder/log") - -except Exception, e: - print "exception:" + str(e) diff --git a/python_apps/show-recorder/airtime-show-recorder-stop b/python_apps/show-recorder/airtime-show-recorder-stop deleted file mode 100755 index e9a529bfd..000000000 --- a/python_apps/show-recorder/airtime-show-recorder-stop +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys -import subprocess - -if os.geteuid() != 0: - print "Please run this as root." - sys.exit(1) - -try: - print "Stopping daemontool script recorder..." - - p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) - p2 = subprocess.Popen(["awk", "/recorder.py/ && !/awk/ {print $2}"], stdin=p1.stdout, stdout=subprocess.PIPE) - recorder_pid = p2.communicate()[0].strip(" \n\r\t") - if (len(recorder_pid) > 0): - os.system("svc -d /etc/service/recorder 1>/dev/null 2>&1") - os.system("svc -d /etc/service/recorder/log 1>/dev/null 2>&1") - - pids = recorder_pid.split("\n") - for pid in pids: - os.system("kill -2 %s" % pid) - print "Shutting down process id %s" % pid - print "Success." - else: - print "Not Running." - -except Exception, e: - print "exception:" + str(e) diff --git a/python_apps/show-recorder/install/recorder-daemontools-logger.sh b/python_apps/show-recorder/install/recorder-daemontools-logger.sh deleted file mode 100755 index 3510acf44..000000000 --- a/python_apps/show-recorder/install/recorder-daemontools-logger.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec setuidgid pypo multilog t /var/log/airtime/show-recorder/main diff --git a/python_apps/show-recorder/install/recorder-install.py b/python_apps/show-recorder/install/recorder-install.py index f5169a9c9..cb84ee95d 100755 --- a/python_apps/show-recorder/install/recorder-install.py +++ b/python_apps/show-recorder/install/recorder-install.py @@ -3,18 +3,11 @@ import time import os -import traceback from optparse import * import sys -import time -import datetime -import logging -import logging.config import shutil -import string -import platform from configobj import ConfigObj -from subprocess import Popen, PIPE, STDOUT +from subprocess import Popen if os.geteuid() != 0: print "Please run this as root." @@ -27,25 +20,6 @@ def create_path(path): print "Creating directory " + path os.makedirs(path) -def create_user(username): - print "Checking for user "+username - p = Popen('id '+username, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - if (output[0:3] != "uid"): - # Make the pypo user - print "Creating user "+username - os.system("adduser --system --quiet --group --shell /bin/bash "+username) - - #set pypo password - p = os.popen('/usr/bin/passwd pypo 1>/dev/null 2>&1', 'w') - p.write('pypo\n') - p.write('pypo\n') - p.close() - else: - print "User already exists." - #add pypo to audio group - os.system("adduser " + username + " audio 1>/dev/null 2>&1") - def copy_dir(src_dir, dest_dir): if (os.path.exists(dest_dir)) and (dest_dir != "/"): print "Removing old directory "+dest_dir @@ -57,7 +31,6 @@ def copy_dir(src_dir, dest_dir): def get_current_script_dir(): current_script_dir = os.path.realpath(__file__) index = current_script_dir.rindex('/') - #print current_script_dir[0:index] return current_script_dir[0:index] @@ -67,15 +40,12 @@ try: config = ConfigObj(PATH_INI_FILE) except Exception, e: print 'Error loading config file: ', e - sys.exit() + sys.exit(1) current_script_dir = get_current_script_dir() - print "Checking and removing any existing recorder processes" - os.system("python %s/recorder-uninstall.py 1>/dev/null 2>&1"% current_script_dir) - time.sleep(5) - # Create users - create_user("pypo") + p = Popen("/etc/init.d/airtime-show-recorder stop >/dev/null 2>&1", shell=True) + sts = os.waitpid(p.pid, 0)[1] print "Creating temporary media storage directory" create_path(config["base_recorded_files"]) @@ -94,37 +64,20 @@ try: os.system("chown -R pypo:pypo "+config["bin_dir"]) print "Creating symbolic links" - os.system("rm -f /usr/bin/airtime-show-recorder-start") - os.system("ln -s "+config["bin_dir"]+"/airtime-show-recorder-start /usr/bin/") - os.system("rm -f /usr/bin/airtime-show-recorder-stop") - os.system("ln -s "+config["bin_dir"]+"/airtime-show-recorder-stop /usr/bin/") - - print "Installing recorder daemon" - create_path("/etc/service/recorder") - create_path("/etc/service/recorder/log") - shutil.copy("%s/recorder-daemontools.sh"%current_script_dir, "/etc/service/recorder/run") - shutil.copy("%s/recorder-daemontools-logger.sh"%current_script_dir, "/etc/service/recorder/log/run") - os.system("chmod -R 755 /etc/service/recorder") - os.system("chown -R pypo:pypo /etc/service/recorder") - + os.system("rm -f /usr/bin/airtime-show-recorder") + os.system("ln -s "+config["bin_dir"]+"/airtime-show-recorder /usr/bin/") + + print "Installing show-recorder daemon" + shutil.copy(config["bin_dir"]+"/airtime-show-recorder-init-d", "/etc/init.d/airtime-show-recorder") + + p = Popen("update-rc.d airtime-show-recorder defaults", shell=True) + sts = os.waitpid(p.pid, 0)[1] + print "Waiting for processes to start..." - time.sleep(5) - os.system("python /usr/bin/airtime-show-recorder-start") - time.sleep(2) + p = Popen("/etc/init.d/airtime-show-recorder start", shell=True) + sts = os.waitpid(p.pid, 0)[1] - found = True - - p = Popen('svstat /etc/service/recorder', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) - output = p.stdout.read() - if (output.find("unable to open supervise/ok: file does not exist") >= 0): - found = False - print output - - if not found: - print "Recorder install has completed, but daemontools is not running, please make sure you have it installed and then reboot." except Exception, e: print "exception:" + str(e) sys.exit(1) - - diff --git a/python_apps/show-recorder/install/recorder-uninstall.py b/python_apps/show-recorder/install/recorder-uninstall.py index fceabfa78..14cb63504 100755 --- a/python_apps/show-recorder/install/recorder-uninstall.py +++ b/python_apps/show-recorder/install/recorder-uninstall.py @@ -3,7 +3,6 @@ import os import sys -import time from configobj import ConfigObj if os.geteuid() != 0: @@ -15,15 +14,6 @@ PATH_INI_FILE = '/etc/airtime/recorder.cfg' def remove_path(path): os.system("rm -rf " + path) -def remove_user(username): - os.system("killall -u %s 1>/dev/null 2>&1" % username) - - #allow all process to be completely closed before we attempt to delete user - print "Waiting for processes to close..." - time.sleep(5) - - os.system("deluser --remove-home " + username + " 1>/dev/null 2>&1") - def get_current_script_dir(): current_script_dir = os.path.realpath(__file__) index = current_script_dir.rindex('/') @@ -35,16 +25,17 @@ try: config = ConfigObj(PATH_INI_FILE) except Exception, e: print 'Error loading config file: ', e - sys.exit() + sys.exit(1) - os.system("python /usr/bin/airtime-show-recorder-stop") + os.system("/etc/init.d/airtime-show-recorder stop") + os.system("rm -f /etc/init.d/airtime-show-recorder") + os.system("update-rc.d -f airtime-show-recorder remove") print "Removing log directories" remove_path(config["log_dir"]) print "Removing symlinks" - os.system("rm -f /usr/bin/airtime-show-recorder-start") - os.system("rm -f /usr/bin/airtime-show-recorder-stop") + os.system("rm -f /usr/bin/airtime-show-recorder") print "Removing application files" remove_path(config["bin_dir"]) @@ -52,10 +43,6 @@ try: print "Removing media files" remove_path(config["base_recorded_files"]) - print "Removing daemontool script recorder" - remove_path("rm -rf /etc/service/recorder") - - remove_user("pypo") print "Uninstall complete." except Exception, e: print "exception:" + str(e) diff --git a/python_apps/show-recorder/logging.cfg b/python_apps/show-recorder/logging.cfg index 251fce8d7..766f56972 100644 --- a/python_apps/show-recorder/logging.cfg +++ b/python_apps/show-recorder/logging.cfg @@ -2,20 +2,20 @@ keys=root [handlers] -keys=consoleHandler +keys=fileOutHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG -handlers=consoleHandler +handlers=fileOutHandler -[handler_consoleHandler] -class=StreamHandler +[handler_fileOutHandler] +class=logging.handlers.RotatingFileHandler level=DEBUG formatter=simpleFormatter -args=(sys.stdout,) +args=("/var/log/airtime/show-recorder/show-recorder.log", 'a', 1000000, 5,) [formatter_simpleFormatter] format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s diff --git a/python_apps/show-recorder/recorder.py b/python_apps/show-recorder/recorder.py index 367779a5a..a6352729a 100644 --- a/python_apps/show-recorder/recorder.py +++ b/python_apps/show-recorder/recorder.py @@ -34,7 +34,8 @@ except Exception, e: try: config = ConfigObj('/etc/airtime/recorder.cfg') except Exception, e: - print 'Error loading config file: ', e + logger = logging.getLogger() + logger.error('Error loading config file: %s', e) sys.exit() def getDateTimeObj(time): @@ -165,21 +166,18 @@ class Record(): def get_shows(self): - shows = self.api_client.get_shows_to_record() - - if self.sr is not None: - if not shows['is_recording'] and self.sr.is_recording(): - self.sr.cancel_recording() - - - if shows is not None: - shows = shows[u'shows'] - else: - shows = [] + response = self.api_client.get_shows_to_record() - if len(shows): - self.process_shows(shows) - self.check_record() + if response is not None and 'is_recording' in response: + if self.sr is not None: + if not response['is_recording'] and self.sr.is_recording(): + self.sr.cancel_recording() + + shows = response[u'shows'] + + if len(shows): + self.process_shows(shows) + self.check_record() if __name__ == '__main__': diff --git a/utils/airtime-check-system b/utils/airtime-check-system index 45477df43..7a67e6845 100755 --- a/utils/airtime-check-system +++ b/utils/airtime-check-system @@ -25,7 +25,7 @@ # # Absolute path to this script SCRIPT=`readlink -f $0` -# Absolute path this script is in +# Absolute directory this script is in SCRIPTPATH=`dirname $SCRIPT` invokePwd=$PWD diff --git a/utils/airtime-check-system.php b/utils/airtime-check-system.php index 1f7823214..15cfac174 100644 --- a/utils/airtime-check-system.php +++ b/utils/airtime-check-system.php @@ -1,7 +1,5 @@