/** * Returns data related to the scheduled items. * * @param int $p_prev * @param int $p_next * @return date */ public static function GetPlayOrderRange($p_prev = 1, $p_next = 1) { //Everything in this function must be done in UTC. You will get a swift kick in the pants if you mess that up. if (!is_int($p_prev) || !is_int($p_next)) { //must enter integers to specify ranges Logging::info("Invalid range parameters: {$p_prev} or {$p_next}"); return array(); } $utcNow = new DateTime("now", new DateTimeZone("UTC")); $shows = Application_Model_Show::getPrevCurrentNext($utcNow); $previousShowID = count($shows['previousShow']) > 0 ? $shows['previousShow'][0]['instance_id'] : null; $currentShowID = count($shows['currentShow']) > 0 ? $shows['currentShow'][0]['instance_id'] : null; $nextShowID = count($shows['nextShow']) > 0 ? $shows['nextShow'][0]['instance_id'] : null; $results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcNow); $range = array("env" => APPLICATION_ENV, "schedulerTime" => $utcNow->format("Y-m-d H:i:s"), "previous" => $results['previous'] != null ? $results['previous'] : (count($shows['previousShow']) > 0 ? $shows['previousShow'][0] : null), "current" => $results['current'] != null ? $results['current'] : (count($shows['currentShow']) > 0 && $shows['currentShow'][0]['record'] == 1 ? $shows['currentShow'][0] : null), "next" => $results['next'] != null ? $results['next'] : (count($shows['nextShow']) > 0 ? $shows['nextShow'][0] : null), "currentShow" => $shows['currentShow'], "nextShow" => $shows['nextShow']); return $range; }
public function playoutHistoryFeedAction() { $request = $this->getRequest(); $current_time = time(); $params = $request->getParams(); $starts_epoch = $request->getParam("start", $current_time - 60 * 60 * 24); $ends_epoch = $request->getParam("end", $current_time); $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); Logging::info("history starts {$startsDT->format("Y-m-d H:i:s")}"); Logging::info("history ends {$endsDT->format("Y-m-d H:i:s")}"); $history = new Application_Model_PlayoutHistory($startsDT, $endsDT, $params); $r = $history->getItems(); $this->view->sEcho = $r["sEcho"]; $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; $this->view->iTotalRecords = $r["iTotalRecords"]; $this->view->history = $r["history"]; }
/** * Returns data related to the scheduled items. * * @param int $p_prev * @param int $p_next * @return date */ public static function GetPlayOrderRange($p_prev = 1, $p_next = 1) { if (!is_int($p_prev) || !is_int($p_next)) { //must enter integers to specify ranges Logging::info("Invalid range parameters: {$p_prev} or {$p_next}"); return array(); } $date = new Application_Common_DateHelper(); $timeNow = $date->getTimestamp(); $utcTimeNow = $date->getUtcTimestamp(); $shows = Application_Model_Show::getPrevCurrentNext($utcTimeNow); $previousShowID = count($shows['previousShow']) > 0 ? $shows['previousShow'][0]['instance_id'] : null; $currentShowID = count($shows['currentShow']) > 0 ? $shows['currentShow'][0]['instance_id'] : null; $nextShowID = count($shows['nextShow']) > 0 ? $shows['nextShow'][0]['instance_id'] : null; $results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcTimeNow); $range = array("env" => APPLICATION_ENV, "schedulerTime" => $timeNow, "previous" => $results['previous'] != null ? $results['previous'] : (count($shows['previousShow']) > 0 ? $shows['previousShow'][0] : null), "current" => $results['current'] != null ? $results['current'] : (count($shows['currentShow']) > 0 && $shows['currentShow'][0]['record'] == 1 ? $shows['currentShow'][0] : null), "next" => $results['next'] != null ? $results['next'] : (count($shows['nextShow']) > 0 ? $shows['nextShow'][0] : null), "currentShow" => $shows['currentShow'], "nextShow" => $shows['nextShow'], "timezone" => date("T"), "timezoneOffset" => date("Z")); return $range; }
public function indexAction() { $CC_CONFIG = Config::getConfig(); $request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir(); $this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.crosshair.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl . 'js/airtime/listenerstat/listenerstat.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl . 'js/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl . 'js/airtime/buttons/buttons.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl . 'js/airtime/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']); //default time is the last 24 hours. $now = time(); $from = $request->getParam("from", $now - 24 * 60 * 60); $to = $request->getParam("to", $now); $utcTimezone = new DateTimeZone("UTC"); $displayTimeZone = new DateTimeZone(Application_Model_Preference::GetTimezone()); $start = DateTime::createFromFormat("U", $from, $utcTimezone); $start->setTimezone($displayTimeZone); $end = DateTime::createFromFormat("U", $to, $utcTimezone); $end->setTimezone($displayTimeZone); $form = new Application_Form_DateRange(); $form->populate(array('his_date_start' => $start->format("Y-m-d"), 'his_time_start' => $start->format("H:i"), 'his_date_end' => $end->format("Y-m-d"), 'his_time_end' => $end->format("H:i"))); $errorStatus = Application_Model_StreamSetting::GetAllListenerStatErrors(); Logging::info($errorStatus); $out = array(); foreach ($errorStatus as $v) { $key = explode('_listener_stat_error', $v['keyname']); if ($v['value'] != 'OK') { $v['value'] = _("Please make sure admin user/password is correct on System->Streams page."); } $out[$key[0]] = $v['value']; } $this->view->errorStatus = $out; $this->view->date_form = $form; }
public function scheduleMoveAction() { $request = $this->getRequest(); $selectedItems = $request->getParam("selectedItem"); $afterItem = $request->getParam("afterItem"); try { $scheduler = new Application_Model_Scheduler(); $scheduler->moveItem($selectedItems, $afterItem); } catch (OutDatedScheduleException $e) { $this->view->error = $e->getMessage(); Logging::info($e->getMessage()); } catch (Exception $e) { $this->view->error = $e->getMessage(); Logging::info($e->getMessage()); } }
public function getListofFilesMeetCriteria() { $storedCrit = $this->getCriteria(); $qry = CcFilesQuery::create(); $qry->useFkOwnerQuery("subj", "left join"); if (isset($storedCrit["crit"])) { foreach ($storedCrit["crit"] as $crit) { $i = 0; foreach ($crit as $criteria) { //$spCriteriaPhpName = self::$criteria2PeerMap[$criteria['criteria']]; $spCriteria = $criteria['criteria']; $spCriteriaModifier = $criteria['modifier']; $column = CcFilesPeer::getTableMap()->getColumnByPhpName(self::$criteria2PeerMap[$spCriteria]); // if the column is timestamp, convert it into UTC if ($column->getType() == PropelColumnTypes::TIMESTAMP) { $spCriteriaValue = Application_Common_DateHelper::ConvertToUtcDateTimeString($criteria['value']); /* Check if only a date was supplied and trim * the time after it is converted to UTC time */ if (strlen($criteria['value']) <= 10) { //extract date only from timestamp in db $spCriteria = 'date(' . $spCriteria . ')'; $spCriteriaValue = substr($spCriteriaValue, 0, 10); } if (isset($criteria['extra'])) { $spCriteriaExtra = Application_Common_DateHelper::ConvertToUtcDateTimeString($criteria['extra']); if (strlen($criteria['extra']) <= 10) { $spCriteriaExtra = substr($spCriteriaExtra, 0, 10); } } } elseif ($spCriteria == "bit_rate" || $spCriteria == 'sample_rate') { // multiply 1000 because we store only number value // e.g 192kps is stored as 192000 $spCriteriaValue = $criteria['value'] * 1000; if (isset($criteria['extra'])) { $spCriteriaExtra = $criteria['extra'] * 1000; } /* * If user is searching for an exact match of length we need to * search as if it starts with the specified length because the * user only sees the rounded version (i.e. 4:02.7 is 4:02.761625 * in the database) */ } elseif ($spCriteria == 'length' && $spCriteriaModifier == "is") { $spCriteriaModifier = "starts with"; $spCriteria = $spCriteria . '::text'; $spCriteriaValue = $criteria['value']; } else { /* Propel does not escape special characters properly when using LIKE/ILIKE * We have to add extra slashes in these cases */ $tempModifier = trim(self::$modifier2CriteriaMap[$spCriteriaModifier]); if ($tempModifier == 'ILIKE') { $spCriteriaValue = addslashes($criteria['value']); // addslashes() does not esapce '%' so we have to do it manually $spCriteriaValue = str_replace('%', '\\%', $spCriteriaValue); } else { $spCriteriaValue = $criteria['value']; } $spCriteriaExtra = $criteria['extra']; } if ($spCriteriaModifier == "starts with") { $spCriteriaValue = "{$spCriteriaValue}%"; } elseif ($spCriteriaModifier == "ends with") { $spCriteriaValue = "%{$spCriteriaValue}"; } elseif ($spCriteriaModifier == "contains" || $spCriteriaModifier == "does not contain") { $spCriteriaValue = "%{$spCriteriaValue}%"; } elseif ($spCriteriaModifier == "is in the range") { $spCriteriaValue = "{$spCriteria} >= '{$spCriteriaValue}' AND {$spCriteria} <= '{$spCriteriaExtra}'"; } $spCriteriaModifier = self::$modifier2CriteriaMap[$spCriteriaModifier]; try { if ($spCriteria == "owner_id") { $spCriteria = "subj.login"; } if ($i > 0) { $qry->addOr($spCriteria, $spCriteriaValue, $spCriteriaModifier); } else { $qry->add($spCriteria, $spCriteriaValue, $spCriteriaModifier); } if ($spCriteriaModifier == Criteria::NOT_ILIKE || $spCriteriaModifier == Criteria::NOT_EQUAL) { $qry->addOr($spCriteria, null, Criteria::ISNULL); } } catch (Exception $e) { Logging::info($e); } $i++; } } // check if file exists $qry->add("file_exists", "true", Criteria::EQUAL); $qry->addAscendingOrderByColumn('random()'); } // construct limit restriction $limits = array(); if (isset($storedCrit['limit'])) { if ($storedCrit['limit']['modifier'] == "items") { $limits['time'] = 1440 * 60; $limits['items'] = $storedCrit['limit']['value']; } else { $limits['time'] = $storedCrit['limit']['modifier'] == "hours" ? intval(floatval($storedCrit['limit']['value']) * 60 * 60) : intval($storedCrit['limit']['value'] * 60); $limits['items'] = null; } } try { $out = $qry->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find(); return array("files" => $out, "limit" => $limits, "count" => $out->count()); } catch (Exception $e) { Logging::info($e); } }
public function smartBlockGenerateAction() { $request = $this->getRequest(); $params = $request->getPost(); //make sure block exists try { $bl = new Application_Model_Block($params['obj_id']); $form = new Application_Form_SmartBlockCriteria(); $form->startForm($params['obj_id']); if ($form->isValid($params)) { $result = $bl->generateSmartBlock($params['data']); $this->_helper->json->sendJson(array("result" => 0, "html" => $this->createFullResponse($bl, true, true))); } else { $this->view->obj = $bl; $this->view->id = $bl->getId(); $this->view->form = $form; $viewPath = 'playlist/smart-block.phtml'; $result['html'] = $this->view->render($viewPath); $result['result'] = 1; $this->_helper->json->sendJson($result); } } catch (BlockNotFoundException $e) { $this->playlistNotFound('block', true); } catch (Exception $e) { Logging::info($e); $this->playlistUnknownError($e); } }
private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) { try { $affectedShowInstances = array(); //dont want to recalculate times for moved items. $excludeIds = array(); foreach ($schedFiles as $file) { if (isset($file["sched_id"])) { $excludeIds[] = intval($file["sched_id"]); } } $startProfile = microtime(true); foreach ($scheduleItems as $schedule) { $id = intval($schedule["id"]); if ($id !== 0) { $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); $instance = $schedItem->getCcShowInstances($this->con); $schedItemEndDT = $schedItem->getDbEnds(null); $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); } else { $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); $showStartDT = $instance->getDbStarts(null); $nextStartDT = $this->findNextStartTime($showStartDT, $instance); } if (!in_array($instance->getDbId(), $affectedShowInstances)) { $affectedShowInstances[] = $instance->getDbId(); } if ($adjustSched === true) { $pstart = microtime(true); $followingSchedItems = CcScheduleQuery::create()->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL)->filterByDbInstanceId($instance->getDbId())->filterByDbId($excludeIds, Criteria::NOT_IN)->orderByDbStarts()->find($this->con); $pend = microtime(true); Logging::debug("finding all following items."); Logging::debug(floatval($pend) - floatval($pstart)); } foreach ($schedFiles as $file) { $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); //item existed previously and is being moved. //need to keep same id for resources if we want REST. if (isset($file['sched_id'])) { $sched = CcScheduleQuery::create()->findPK($file['sched_id'], $this->con); } else { $sched = new CcSchedule(); } Logging::info($file); $sched->setDbStarts($nextStartDT)->setDbEnds($endTimeDT)->setDbCueIn($file['cuein'])->setDbCueOut($file['cueout'])->setDbFadeIn($file['fadein'])->setDbFadeOut($file['fadeout'])->setDbClipLength($file['cliplength'])->setDbInstanceId($instance->getDbId()); switch ($file["type"]) { case 0: $sched->setDbFileId($file['id']); break; case 1: $sched->setDbStreamId($file['id']); break; default: break; } $sched->save($this->con); $nextStartDT = $endTimeDT; } if ($adjustSched === true) { $pstart = microtime(true); //recalculate the start/end times after the inserted items. foreach ($followingSchedItems as $item) { $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); $item->setDbStarts($nextStartDT); $item->setDbEnds($endTimeDT); $item->save($this->con); $nextStartDT = $endTimeDT; } $pend = microtime(true); Logging::debug("adjusting all following items."); Logging::debug(floatval($pend) - floatval($pstart)); } } $endProfile = microtime(true); Logging::debug("finished adding scheduled items."); Logging::debug(floatval($endProfile) - floatval($startProfile)); //update the status flag in cc_schedule. $instances = CcShowInstancesQuery::create()->filterByPrimaryKeys($affectedShowInstances)->find($this->con); $startProfile = microtime(true); foreach ($instances as $instance) { $instance->updateScheduleStatus($this->con); } $endProfile = microtime(true); Logging::debug("updating show instances status."); Logging::debug(floatval($endProfile) - floatval($startProfile)); $startProfile = microtime(true); //update the last scheduled timestamp. CcShowInstancesQuery::create()->filterByPrimaryKeys($affectedShowInstances)->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con); $endProfile = microtime(true); Logging::debug("updating last scheduled timestamp."); Logging::debug(floatval($endProfile) - floatval($startProfile)); } catch (Exception $e) { Logging::debug($e->getMessage()); throw $e; } }
public static function getSoundCloudUploads() { try { $con = Propel::getConnection(); $sql = <<<SQL SELECT soundcloud_id AS id, soundcloud_upload_time FROM CC_FILES WHERE (id != -2 AND id != -3) AND (soundcloud_upload_time >= (now() - (INTERVAL '1 day'))) SQL; $rows = $con->query($sql)->fetchAll(); return count($rows); } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); Logging::info("Could not connect to database."); exit; } }
public function updateFileItemAction() { $request = $this->getRequest(); $params = $request->getPost(); Logging::info($params); $historyService = new Application_Service_HistoryService(); $json = $historyService->editPlayedFile($params); $this->_helper->json->sendJson($json); }
public function cancelCurrentShowAction() { $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $id = $this->_getParam('id'); try { $scheduler = new Application_Model_Scheduler(); $scheduler->cancelShow($id); // send kick out source stream signal to pypo $data = array("sourcename" => "live_dj"); Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); } catch (Exception $e) { $this->view->error = $e->getMessage(); Logging::info($e->getMessage()); } } }
/** * create new database table for current DatabaseTable object * @param $force bool indicates if existing database table should be removed (FALSE if not provided) * @return bool indicates if table has been created */ function create($force = FALSE) { global $firstthingsfirst_field_descriptions; $this->_log->trace("creating DatabaseTable (table=" . $this->table_name . ")"); # check if database connection is working if ($this->_check_database_connection() == FALSE) { return FALSE; } # check if database table already exists if ($this->_database->table_exists($this->table_name)) { # drop the existing table if ($force) { $this->_log->debug("dropping table (table=" . $this->table_name . ")"); $query = "DROP TABLE " . $this->table_name; $result = $this->_database->query($query); if ($result == FALSE) { $this->_handle_error("could not drop DatabaseTable", "ERROR_DATABASE_PROBLEM"); return FALSE; } } else { # do not drop the table by force $this->_handle_error("table (table=" . $this->table_name . ") already exists and (force=FALSE)", "ERROR_DUPLICATE_LIST_NAME"); return FALSE; } } $query_postfix = ""; $query = "CREATE TABLE " . $this->table_name . " ("; foreach ($this->db_field_names as $db_field_name) { $field_type = $this->fields[$db_field_name][1]; $field_options = $this->fields[$db_field_name][2]; $this->_log->trace("found field (db_field_name=" . $db_field_name . ", field_type=" . $field_type . ", field_options=" . $field_options . ")"); $query .= $db_field_name . " " . $firstthingsfirst_field_descriptions[$field_type][FIELD_DESCRIPTION_FIELD_DB_DEFINITION] . ", "; # check for postfix if ($this->fields[$db_field_name][2] == DATABASETABLE_UNIQUE_FIELD) { $query_postfix .= ", " . DATABASETABLE_UNIQUE_FIELD . " " . $db_field_name . " (" . $db_field_name . ")"; } } # add archiver name and datetime if ($this->metadata_str[DATABASETABLE_METADATA_ENABLE_ARCHIVE] != DATABASETABLE_METADATA_FALSE) { $query .= DB_ARCHIVER_FIELD_NAME . " " . DB_DATATYPE_USERNAME . ", "; $query .= DB_TS_ARCHIVED_FIELD_NAME . " " . DB_DATATYPE_DATETIME . ", "; } # add creator name and datetime if ($this->metadata_str[DATABASETABLE_METADATA_ENABLE_CREATE] != DATABASETABLE_METADATA_FALSE) { $query .= DB_CREATOR_FIELD_NAME . " " . DB_DATATYPE_USERNAME . ", "; $query .= DB_TS_CREATED_FIELD_NAME . " " . DB_DATATYPE_DATETIME . ", "; } # add modifier name and datetime if ($this->metadata_str[DATABASETABLE_METADATA_ENABLE_MODIFY] != DATABASETABLE_METADATA_FALSE) { $query .= DB_MODIFIER_FIELD_NAME . " " . DB_DATATYPE_USERNAME . ", "; $query .= DB_TS_MODIFIED_FIELD_NAME . " " . DB_DATATYPE_DATETIME . ", "; } $query .= "PRIMARY KEY (" . DB_ID_FIELD_NAME . ")"; # add postfix if (strlen($query_postfix) > 0) { $query .= $query_postfix; } $query .= ") ENGINE=MyISAM"; $result = $this->_database->query($query); if ($result == FALSE) { $this->_handle_error("could not create DatabaseTable", "ERROR_DATABASE_PROBLEM"); return FALSE; } $this->_log->info("created DatabaseTable (table_name=" . $this->table_name . ")"); return TRUE; }
public static function getOrderingMap($pref_param) { $v = self::getValue($pref_param, true); $id = function ($x) { return $x; }; if ($v === '') { return $id; } $ds = unserialize($v); if (!array_key_exists('ColReorder', $ds)) { return $id; } return function ($x) use($ds) { if (array_key_exists($x, $ds['ColReorder'])) { return $ds['ColReorder'][$x]; } else { /*For now we just have this hack for debugging. We should not rely on this crappy behaviour in case of failure*/ Logging::info("Pref: {$pref_param}"); Logging::warn("Index {$x} does not exist preferences"); Logging::warn("Defaulting to identity and printing preferences"); Logging::warn($ds); return $x; } }; }
public function removeGaps($showInstance, $exclude = null) { Logging::info("removing gaps from show instance #" . $showInstance); $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con); if (is_null($instance)) { throw new OutDatedScheduleException(_("The schedule you're viewing is out of date!")); } $itemStartDT = $instance->getDbStarts(null); $schedule = CcScheduleQuery::create()->filterByDbInstanceId($showInstance)->filterByDbId($exclude, Criteria::NOT_IN)->orderByDbStarts()->find($this->con); foreach ($schedule as $item) { $itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength()); $item->setDbStarts($itemStartDT)->setDbEnds($itemEndDT); $itemStartDT = $itemEndDT; } $schedule->save($this->con); }
public function emptyShowContent($instanceId) { try { $ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); $instances = array(); $instanceIds = array(); if ($ccShowInstance->getCcShow()->isLinked()) { foreach ($ccShowInstance->getCcShow()->getCcShowInstancess() as $instance) { $instanceIds[] = $instance->getDbId(); $instances[] = $instance; } } else { $instanceIds[] = $ccShowInstance->getDbId(); $instances[] = $ccShowInstance; } /* Get the file ids of the tracks we are about to delete * from cc_schedule. We need these so we can update the * is_scheduled flag in cc_files */ $ccSchedules = CcScheduleQuery::create()->filterByDbInstanceId($instanceIds, Criteria::IN)->setDistinct(CcSchedulePeer::FILE_ID)->find(); $fileIds = array(); foreach ($ccSchedules as $ccSchedule) { $fileIds[] = $ccSchedule->getDbFileId(); } /* Clear out the schedule */ CcScheduleQuery::create()->filterByDbInstanceId($instanceIds, Criteria::IN)->delete(); /* Now that the schedule has been cleared we need to make * sure we do not update the is_scheduled flag for tracks * that are scheduled in other shows */ $futureScheduledFiles = Application_Model_Schedule::getAllFutureScheduledFiles(); foreach ($fileIds as $k => $v) { if (in_array($v, $futureScheduledFiles)) { unset($fileIds[$k]); } } $selectCriteria = new Criteria(); $selectCriteria->add(CcFilesPeer::ID, $fileIds, Criteria::IN); $updateCriteria = new Criteria(); $updateCriteria->add(CcFilesPeer::IS_SCHEDULED, false); BasePeer::doUpdate($selectCriteria, $updateCriteria, Propel::getConnection()); Application_Model_RabbitMq::PushSchedule(); $con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME); foreach ($instances as $instance) { $instance->updateDbTimeFilled($con); } return true; } catch (Exception $e) { Logging::info($e->getMessage()); return false; } }
public function setfades($fadein, $fadeout) { if (isset($fadein)) { Logging::info("Setting playlist fade in {$fadein}"); $row = CcPlaylistcontentsQuery::create()->filterByDbPlaylistId($this->id)->filterByDbPosition(0)->findOne($this->con); $this->changeFadeInfo($row->getDbId(), $fadein, null); } if (isset($fadeout)) { Logging::info("Setting playlist fade out {$fadeout}"); $row = CcPlaylistcontentsQuery::create()->filterByDbPlaylistId($this->id)->filterByDbPosition($this->getSize() - 1)->findOne($this->con); $this->changeFadeInfo($row->getDbId(), null, $fadeout); } }
public function isAuthorized($webstream_id) { $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { return true; } if ($user->isHost()) { // not creating a webstream if ($webstream_id != -1) { $webstream = CcWebstreamQuery::create()->findPK($webstream_id); /*we are updating a playlist. Ensure that if the user is a host/dj, that he has the correct permission.*/ $user = Application_Model_User::getCurrentUser(); //only allow when webstream belongs to the DJ return $webstream->getDbCreatorId() == $user->getId(); } /*we are creating a new stream. Don't need to check whether the DJ/Host owns the stream*/ return true; } else { Logging::info($user); } return false; }
set_include_path(APPLICATION_PATH . '/controllers/plugins' . PATH_SEPARATOR . get_include_path()); //Zend framework if (file_exists('/usr/share/php/libzend-framework-php')) { set_include_path('/usr/share/php/libzend-framework-php' . PATH_SEPARATOR . get_include_path()); } /** Zend_Application */ require_once 'Zend/Application.php'; $application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'); require_once APPLICATION_PATH . "/logging/Logging.php"; Logging::setLogPath('/var/log/airtime/zendphp.log'); // Create application, bootstrap, and run try { $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cli') { set_include_path(APPLICATION_PATH . PATH_SEPARATOR . get_include_path()); require_once "Bootstrap.php"; } else { $application->bootstrap()->run(); } } catch (Exception $e) { echo $e->getMessage(); echo "<pre>"; echo $e->getTraceAsString(); echo "</pre>"; Logging::info($e->getMessage()); if (VERBOSE_STACK_TRACE) { Logging::info($e->getTraceAsString()); } else { Logging::info($e->getTrace()); } }
public function rabbitmqDoPushAction() { Logging::info("Notifying RabbitMQ to send message to pypo"); Application_Model_RabbitMq::SendMessageToPypo("reset_liquidsoap_bootstrap", array()); Application_Model_RabbitMq::PushSchedule(); }
public function rescanWatchDirectoryAction() { $dir_path = $this->getRequest()->getParam('dir'); $dir = Application_Model_MusicDir::getDirByPath($dir_path); $data = array('directory' => $dir->getDirectory(), 'id' => $dir->getId()); Application_Model_RabbitMq::SendMessageToMediaMonitor('rescan_watch', $data); Logging::info("Unhiding all files belonging to:: {$dir_path}"); $dir->unhideFiles(); $this->_helper->json->sendJson(null); }
public static function GetDiskInfo() { $partions = array(); if (isset($_SERVER['AIRTIME_SRV'])) { //connect to DB and find how much total space user has allocated. $totalSpace = Application_Model_Preference::GetDiskQuota(); $storPath = Application_Model_MusicDir::getStorDir()->getDirectory(); list($usedSpace, ) = preg_split("/[\\s]+/", exec("du -bs {$storPath}")); $partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace; Logging::info($partitions[$totalSpace]->totalFreeSpace); } else { /* First lets get all the watched directories. Then we can group them * into the same partitions by comparing the partition sizes. */ $musicDirs = Application_Model_MusicDir::getWatchedDirs(); $musicDirs[] = Application_Model_MusicDir::getStorDir(); foreach ($musicDirs as $md) { $totalSpace = disk_total_space($md->getDirectory()); if (!isset($partitions[$totalSpace])) { $partitions[$totalSpace] = new StdClass(); $partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory()); } $partitions[$totalSpace]->dirs[] = $md->getDirectory(); } } return array_values($partitions); }
public function calculateDuration($start, $end, $timezone) { try { $tz = new DateTimeZone($timezone); $startDateTime = new DateTime($start, $tz); $endDateTime = new DateTime($end, $tz); $duration = $startDateTime->diff($endDateTime); $day = intval($duration->format('%d')); if ($day > 0) { $hour = intval($duration->format('%h')); $min = intval($duration->format('%i')); $hour += $day * 24; $hour = min($hour, 99); $sign = $duration->format('%r'); return sprintf('%s%02dh %02dm', $sign, $hour, $min); } else { return $duration->format('%r%Hh %Im'); } } catch (Exception $e) { Logging::info($e->getMessage()); return "Invalid Date"; } }
public function updateCueValuesBySilanAction() { $request = $this->getRequest(); $data = json_decode($request->getParam('data'), $assoc = true); foreach ($data as $pair) { list($id, $info) = $pair; // TODO : move this code into model -- RG $file = Application_Model_StoredFile::RecallById($p_id = $id)->getPropelOrm(); //What we are doing here is setting a more accurate length that was //calculated with silan by actually scanning the entire file. This //process takes a really long time, and so we only do it in the background //after the file has already been imported -MK try { $length = $file->getDbLength(); if (isset($info['length'])) { $length = $info['length']; //length decimal number in seconds. Need to convert it to format //HH:mm:ss to get around silly PHP limitations. $length = Application_Common_DateHelper::secondsToPlaylistTime($length); $file->setDbLength($length); } $cuein = isset($info['cuein']) ? $info['cuein'] : 0; $cueout = isset($info['cueout']) ? $info['cueout'] : $length; $file->setDbCuein($cuein); $file->setDbCueout($cueout); $file->setDbSilanCheck(true); $file->save(); } catch (Exception $e) { Logging::info("Failed to update silan values for " . $file->getDbTrackTitle()); Logging::info("File length analyzed by Silan is: " . $length); //set silan_check to true so we don't attempt to re-anaylze again $file->setDbSilanCheck(true); $file->save(); } } $this->_helper->json->sendJson(array()); }
/** * Create a show. * * Note: end dates are non inclusive. * * @param array $data * @return int * Show ID */ public static function create($data) { $startDateTime = new DateTime($data['add_show_start_date'] . " " . $data['add_show_start_time']); $utcStartDateTime = clone $startDateTime; $utcStartDateTime->setTimezone(new DateTimeZone('UTC')); if ($data['add_show_no_end']) { $endDate = NULL; } elseif ($data['add_show_repeats']) { $endDateTime = new DateTime($data['add_show_end_date']); //$endDateTime->setTimezone(new DateTimeZone('UTC')); $endDateTime->add(new DateInterval("P1D")); $endDate = $endDateTime->format("Y-m-d"); } else { $endDateTime = new DateTime($data['add_show_start_date']); //$endDateTime->setTimezone(new DateTimeZone('UTC')); $endDateTime->add(new DateInterval("P1D")); $endDate = $endDateTime->format("Y-m-d"); } //What we are doing here is checking if the show repeats or if //any repeating days have been checked. If not, then by default //the "selected" DOW is the initial day. //DOW in local time. $startDow = date("w", $startDateTime->getTimestamp()); if (!$data['add_show_repeats']) { $data['add_show_day_check'] = array($startDow); } elseif ($data['add_show_repeats'] && $data['add_show_day_check'] == "") { $data['add_show_day_check'] = array($startDow); } //find repeat type or set to a non repeating show. $repeatType = $data['add_show_repeats'] ? $data['add_show_repeat_type'] : -1; if ($data['add_show_id'] == -1) { $ccShow = new CcShow(); } else { $ccShow = CcShowQuery::create()->findPK($data['add_show_id']); } $ccShow->setDbName($data['add_show_name']); $ccShow->setDbDescription($data['add_show_description']); $ccShow->setDbUrl($data['add_show_url']); $ccShow->setDbGenre($data['add_show_genre']); $ccShow->setDbColor($data['add_show_color']); $ccShow->setDbBackgroundColor($data['add_show_background_color']); $ccShow->setDbLiveStreamUsingAirtimeAuth($data['cb_airtime_auth'] == 1); $ccShow->setDbLiveStreamUsingCustomAuth($data['cb_custom_auth'] == 1); $ccShow->setDbLiveStreamUser($data['custom_username']); $ccShow->setDbLiveStreamPass($data['custom_password']); $ccShow->save(); $showId = $ccShow->getDbId(); $isRecorded = isset($data['add_show_record']) && $data['add_show_record'] ? 1 : 0; if ($data['add_show_id'] != -1) { $show = new Application_Model_Show($showId); $show->deletePossiblyInvalidInstances($data, $endDate, $isRecorded, $repeatType); } //check if we are adding or updating a show, and if updating //erase all the show's show_days information first. if ($data['add_show_id'] != -1) { CcShowDaysQuery::create()->filterByDbShowId($data['add_show_id'])->delete(); } //don't set day for monthly repeat type, it's invalid. if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2) { $showDay = new CcShowDays(); $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTime->format("H:i:s")); $showDay->setDbTimezone(date_default_timezone_get()); $showDay->setDbDuration($data['add_show_duration']); $showDay->setDbRepeatType($repeatType); $showDay->setDbShowId($showId); $showDay->setDbRecord($isRecorded); $showDay->save(); } else { foreach ($data['add_show_day_check'] as $day) { $daysAdd = 0; $startDateTimeClone = clone $startDateTime; if ($startDow !== $day) { if ($startDow > $day) { $daysAdd = 6 - $startDow + 1 + $day; } else { $daysAdd = $day - $startDow; } $startDateTimeClone->add(new DateInterval("P" . $daysAdd . "D")); } if (is_null($endDate) || $startDateTimeClone->getTimestamp() <= $endDateTime->getTimestamp()) { $showDay = new CcShowDays(); $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d")); $showDay->setDbLastShow($endDate); $showDay->setDbStartTime($startDateTimeClone->format("H:i")); $showDay->setDbTimezone(date_default_timezone_get()); $showDay->setDbDuration($data['add_show_duration']); $showDay->setDbDay($day); $showDay->setDbRepeatType($repeatType); $showDay->setDbShowId($showId); $showDay->setDbRecord($isRecorded); $showDay->save(); } } } //check if we are adding or updating a show, and if updating //erase all the show's future show_rebroadcast information first. if ($data['add_show_id'] != -1 && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']) { CcShowRebroadcastQuery::create()->filterByDbShowId($data['add_show_id'])->delete(); } //adding rows to cc_show_rebroadcast /* TODO: Document magic constant 10 and define it properly somewhere --RG */ 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]); $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_' . $i]); $showRebroad->setDbShowId($showId); $showRebroad->save(); } } } elseif ($isRecorded && $data['add_show_rebroadcast'] && $repeatType == -1) { for ($i = 1; $i <= 10; $i++) { if ($data['add_show_rebroadcast_date_absolute_' . $i]) { //$con = Propel::getConnection(CcShowPeer::DATABASE_NAME); //$sql = "SELECT date '{$data['add_show_rebroadcast_date_absolute_'.$i]}' - date '{$data['add_show_start_date']}' "; $sql = <<<SQL SELECT :rebroadcast::date - :start::date SQL; $offset_days = Application_Common_Database::prepareAndExecute($sql, array('rebroadcast' => $data["add_show_rebroadcast_date_absolute_{$i}"], 'start' => $data['add_show_start_date']), "column"); //$r = $con->query($sql); //$offset_days = $r->fetchColumn(0); $showRebroad = new CcShowRebroadcast(); $showRebroad->setDbDayOffset($offset_days . " days"); $showRebroad->setDbStartTime($data['add_show_rebroadcast_time_absolute_' . $i]); $showRebroad->setDbShowId($showId); $showRebroad->save(); } } } //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) { CcShowHostsQuery::create()->filterByDbShow($data['add_show_id'])->delete(); } if (is_array($data['add_show_hosts'])) { //add selected hosts to cc_show_hosts table. foreach ($data['add_show_hosts'] as $host) { $showHost = new CcShowHosts(); $showHost->setDbShow($showId); $showHost->setDbHost($host); $showHost->save(); } } if ($data['add_show_id'] != -1) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $con->beginTransaction(); //current timesamp in UTC. $current_timestamp = gmdate("Y-m-d H:i:s"); try { //update the status flag in cc_schedule. $instances = CcShowInstancesQuery::create()->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN)->filterByDbShowId($data['add_show_id'])->find($con); foreach ($instances as $instance) { $instance->updateScheduleStatus($con); } $con->commit(); } catch (Exception $e) { $con->rollback(); Logging::info("Couldn't update schedule status."); Logging::info($e->getMessage()); } } Application_Model_Show::populateShowUntil($showId); Application_Model_RabbitMq::PushSchedule(); return $showId; }
public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData") { $where = array(); /* Holds the parameters for binding after the statement has been prepared */ $params = array(); if (isset($data['advSearch']) && $data['advSearch'] === 'true') { $librarySetting = Application_Model_Preference::getCurrentLibraryTableColumnMap(); //$displayColumns[] = 'owner'; // map that maps original column position to db name $current2dbname = array(); // array of search terms $orig2searchTerm = array(); foreach ($data as $key => $d) { if (strstr($key, "mDataProp_")) { list($dump, $index) = explode("_", $key); $current2dbname[$index] = $d; } elseif (strstr($key, "sSearch_")) { list($dump, $index) = explode("_", $key); $orig2searchTerm[$index] = $d; } } // map that maps dbname to searchTerm $dbname2searchTerm = array(); foreach ($current2dbname as $currentPos => $dbname) { $new_index = $librarySetting($currentPos); // TODO : Fix this retarded hack later. Just a band aid for // now at least we print some warnings so that we don't // forget about this -- cc-4462 if (array_key_exists($new_index, $orig2searchTerm)) { $dbname2searchTerm[$dbname] = $orig2searchTerm[$new_index]; } else { Logging::warn("Trying to reorder to unknown index\n printing as much debugging as possible..."); $debug = array('$new_index' => $new_index, '$currentPos' => $currentPos, '$orig2searchTerm' => $orig2searchTerm); Logging::warn($debug); } } $advancedWhere = self::buildWhereClauseForAdvancedSearch($dbname2searchTerm); if (!empty($advancedWhere['clause'])) { $where[] = join(" AND ", $advancedWhere['clause']); $params = $advancedWhere['params']; } } if ($data["sSearch"] !== "") { $searchTerms = explode(" ", $data["sSearch"]); } $selectorCount = "SELECT COUNT(*) "; $selectorRows = "SELECT " . join(",", $displayColumns) . " "; $sql = $selectorCount . " FROM " . $fromTable; $sqlTotalRows = $sql; if (isset($searchTerms)) { $searchCols = array(); for ($i = 0; $i < $data["iColumns"]; $i++) { if ($data["bSearchable_" . $i] == "true") { $searchCols[] = $data["mDataProp_{$i}"]; } } $outerCond = array(); $simpleWhere = array(); foreach ($searchTerms as $term) { foreach ($searchCols as $col) { $simpleWhere['clause']["simple_" . $col] = "{$col}::text ILIKE :simple_" . $col; $simpleWhere['params']["simple_" . $col] = "%" . $term . "%"; } $outerCond[] = "(" . implode(" OR ", $simpleWhere['clause']) . ")"; } $where[] = "(" . implode(" AND ", $outerCond) . ")"; $params = array_merge($params, $simpleWhere['params']); } // End Where clause // Order By clause $orderby = array(); for ($i = 0; $i < $data["iSortingCols"]; $i++) { $num = $data["iSortCol_" . $i]; $orderby[] = $data["mDataProp_{$num}"] . " " . $data["sSortDir_" . $i]; } $orderby[] = "id"; $orderby = join(",", $orderby); // End Order By clause $displayLength = intval($data["iDisplayLength"]); $needToBind = false; if (count($where) > 0) { $needToBind = true; $where = join(" OR ", $where); $sql = $selectorCount . " FROM " . $fromTable . " WHERE " . $where; $sqlTotalDisplayRows = $sql; $sql = $selectorRows . " FROM " . $fromTable . " WHERE " . $where . " ORDER BY " . $orderby; } else { $sql = $selectorRows . " FROM " . $fromTable . " ORDER BY " . $orderby; } //limit the results returned. if ($displayLength !== -1) { $sql .= " OFFSET " . $data["iDisplayStart"] . " LIMIT " . $displayLength; } try { //Logging::info($sqlTotalRows); $r = $con->query($sqlTotalRows); $totalRows = $r->fetchColumn(0); if (isset($sqlTotalDisplayRows)) { //Logging::info("sql is set"); //Logging::info($sqlTotalDisplayRows); $totalDisplayRows = Application_Common_Database::prepareAndExecute($sqlTotalDisplayRows, $params, 'column'); } else { //Logging::info("sql is not set."); $totalDisplayRows = $totalRows; } //TODO if ($needToBind) { $results = Application_Common_Database::prepareAndExecute($sql, $params); } else { $stmt = $con->query($sql); $stmt->setFetchMode(PDO::FETCH_ASSOC); $results = $stmt->fetchAll(); } } catch (Exception $e) { Logging::info($e->getMessage()); } return array("sEcho" => intval($data["sEcho"]), "iTotalDisplayRecords" => intval($totalDisplayRows), "iTotalRecords" => intval($totalRows), $dataProp => $results); }
public function cancelShow($day_timestamp) { $timeinfo = explode(" ", $day_timestamp); CcShowDaysQuery::create()->filterByDbShowId($this->_showId)->update(array('DbLastShow' => $timeinfo[0])); $sql = <<<SQL SELECT id from cc_show_instances WHERE starts >= :dayTimestamp::TIMESTAMP AND show_id = :showId SQL; $rows = Application_Common_Database::prepareAndExecute($sql, array(':dayTimestamp' => $day_timestamp, ':showId' => $this->getId()), 'all'); foreach ($rows as $row) { try { $showInstance = new Application_Model_ShowInstance($row["id"]); $showInstance->delete($rabbitmqPush = false); } catch (Exception $e) { Logging::info($e->getMessage()); } } Application_Model_RabbitMq::PushSchedule(); }
public function removeUserAction() { // action body $delId = $this->_getParam('id'); $valid_actions = array("delete_cascade", "reassign_to"); $files_action = $this->_getParam('deleted_files'); # TODO : remove this. we only use default for now not to break the UI. if (!$files_action) { # set default action $files_action = "reassign_to"; $new_owner = Application_Model_User::getFirstAdmin(); } # only delete when valid action is selected for the owned files if (!in_array($files_action, $valid_actions)) { return; } $userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userId = $userInfo->id; # Don't let users delete themselves if ($delId == $userId) { return; } $user = new Application_Model_User($delId); # Take care of the user's files by either assigning them to somebody # or deleting them all if ($files_action == "delete_cascade") { $user->deleteAllFiles(); } elseif ($files_action == "reassign_to") { // TODO : fix code to actually use the line below and pick a // real owner instead of defaulting to the first found admin //$new_owner_id = $this->_getParam("new_owner"); //$new_owner = new Application_Model_User($new_owner_id); $user->donateFilesTo($new_owner); Logging::info("Reassign to user {$new_owner->getDbId()}"); } # Finally delete the user $this->view->entries = $user->delete(); }
public static function uploadSoundcloud($id) { $cmd = "/usr/lib/airtime/utils/soundcloud-uploader {$id} > /dev/null &"; Logging::info("Uploading soundcloud with command: {$cmd}"); exec($cmd); }
public function setRecordedFile($file_id) { $showInstance = CcShowInstancesQuery::create()->findPK($this->_instanceId); $showInstance->setDbRecordedFile($file_id)->save(); $rebroadcasts = CcShowInstancesQuery::create()->filterByDbOriginalShow($this->_instanceId)->find(); foreach ($rebroadcasts as $rebroadcast) { try { $rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId()); $rebroad->addFileToShow($file_id, false); } catch (Exception $e) { Logging::info($e->getMessage()); } } }
$doc = <<<DOC get_job_logs.php Usage: get_job_logs.php [-h | -q | -d ] [-m methods] [-t task_ids] -h, --help Show this help -q, --quiet Run quietly -d, --debug Show informations. -m, --methods=methods Show only tasks defined with a list of methods (separated by commas). -t, --tasks=task_ids Filter logs by tasks (separated by commas) DOC; chdir(dirname($_SERVER["SCRIPT_FILENAME"])); include "../../../inc/includes.php"; include "./docopt.php"; require "./logging.php"; /** * Process arguments passed to the script */ $docopt = new \Docopt\Handler(); $args = $docopt->handle($doc); $logger = new Logging(); $logger->setLevelFromArgs($args['--quiet'], $args['--debug']); $logger->debug($args); /* * Get Running Tasks */ $logs = PluginFusioninventoryTask::getJobLogs(); $logger->info($logs);