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

This commit is contained in:
Rudi Grinberg 2012-11-02 14:59:02 -04:00
commit aec11feba5
62 changed files with 918 additions and 868 deletions

View file

@ -42,14 +42,32 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
$view = $this->getResource('view'); $view = $this->getResource('view');
$view->doctype('XHTML1_STRICT'); $view->doctype('XHTML1_STRICT');
} }
protected function _initGlobals()
{
$view = $this->getResource('view');
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headScript()->appendScript("var baseUrl = '$baseUrl'");
$user = Application_Model_User::GetCurrentUser();
if (!is_null($user)){
$userType = $user->getType();
} else {
$userType = "";
}
$view->headScript()->appendScript("var userType = '$userType';");
}
protected function _initHeadLink() protected function _initHeadLink()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$view = $this->getResource('view'); $view = $this->getResource('view');
$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headLink()->appendStylesheet($baseUrl.'/css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/pro_dropdown_3.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/pro_dropdown_3.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/qtip/jquery.qtip.min.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/qtip/jquery.qtip.min.css?'.$CC_CONFIG['airtime_version']);
@ -63,17 +81,18 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
global $CC_CONFIG; global $CC_CONFIG;
$view = $this->getResource('view'); $view = $this->getResource('view');
$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headScript()->appendFile($baseUrl.'/js/libs/jquery-1.7.2.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/libs/jquery-ui-1.8.18.custom.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-1.7.2.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/libs/jquery.stickyPanel.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-ui-1.8.18.custom.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/qtip/jquery.qtip.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/jquery.stickyPanel.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/qtip/jquery.qtip.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/jplayer/jquery.jplayer.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/jplayer/jquery.jplayer.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/sprintf/sprintf-0.7-beta1.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/sprintf/sprintf-0.7-beta1.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/bootstrap/bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/bootstrap/bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendScript("var baseUrl='$baseUrl/'"); $view->headScript()->appendScript("var baseUrl='$baseUrl'");
//scripts for now playing bar //scripts for now playing bar
$view->headScript()->appendFile($baseUrl.'/js/airtime/airtime_bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/airtime_bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/helperfunctions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/helperfunctions.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -95,6 +114,15 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) { if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) {
$view->headScript()->appendFile($baseUrl.'/js/libs/google-analytics.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/google-analytics.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
} }
if (Application_Model_Preference::GetPlanLevel() != "disabled"
&& !($_SERVER['REQUEST_URI'] == $baseUrl.'/Dashboard/stream-player' ||
strncmp($_SERVER['REQUEST_URI'], $baseUrl.'/audiopreview/audio-preview', strlen($baseUrl.'/audiopreview/audio-preview'))==0)) {
$client_id = Application_Model_Preference::GetClientId();
$view->headScript()->appendScript("var livechat_client_id = '$client_id';");
$view->headScript()->appendFile($baseUrl . '/js/airtime/common/livechat.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
}
} }
protected function _initViewHelpers() protected function _initViewHelpers()

View file

@ -63,4 +63,11 @@ class Application_Common_OsPath{
return join(DIRECTORY_SEPARATOR, $paths); return join(DIRECTORY_SEPARATOR, $paths);
} }
public static function getBaseDir() {
$baseUrl = dirname($_SERVER['SCRIPT_NAME']);
if (strcmp($baseUrl, '/') ==0) $baseUrl = "";
return $baseUrl;
}
} }

View file

@ -26,8 +26,7 @@ class AudiopreviewController extends Zend_Controller_Action
$audioFileTitle = $this->_getParam('audioFileTitle'); $audioFileTitle = $this->_getParam('audioFileTitle');
$type = $this->_getParam('type'); $type = $this->_getParam('type');
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile( $this->view->headScript()->appendFile(
$baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'], $baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],
@ -79,8 +78,7 @@ class AudiopreviewController extends Zend_Controller_Action
$playlistIndex = $this->_getParam('playlistIndex'); $playlistIndex = $this->_getParam('playlistIndex');
$playlistID = $this->_getParam('playlistID'); $playlistID = $this->_getParam('playlistID');
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -106,8 +104,7 @@ class AudiopreviewController extends Zend_Controller_Action
$blockIndex = $this->_getParam('blockIndex'); $blockIndex = $this->_getParam('blockIndex');
$blockId = $this->_getParam('blockId'); $blockId = $this->_getParam('blockId');
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -232,8 +229,8 @@ class AudiopreviewController extends Zend_Controller_Action
$showID = $this->_getParam('showID'); $showID = $this->_getParam('showID');
$showIndex = $this->_getParam('showIndex'); $showIndex = $this->_getParam('showIndex');
$request = $this->getRequest(); $baseUrl = dirname($_SERVER['SCRIPT_NAME']);
$baseUrl = $request->getBaseUrl(); if (strcmp($baseUrl, '/') ==0) $baseUrl = "";
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -258,6 +255,7 @@ class AudiopreviewController extends Zend_Controller_Action
*/ */
public function getShowAction() public function getShowAction()
{ {
$baseUrl = Application_Common_OsPath::getBaseDir();
// disable the view and the layout // disable the view and the layout
$this->view->layout()->disableLayout(); $this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true); $this->_helper->viewRenderer->setNoRender(true);
@ -298,7 +296,7 @@ class AudiopreviewController extends Zend_Controller_Action
throw new Exception("Unknown file type: $mime"); throw new Exception("Unknown file type: $mime");
} }
$elementMap['uri'] = "/api/get-media/file/".$track['item_id']; $elementMap['uri'] = $baseUrl."/api/get-media/file/".$track['item_id'];
} else { } else {
$elementMap['uri'] = $track['filepath']; $elementMap['uri'] = $track['filepath'];
} }

View file

@ -98,8 +98,7 @@ class DashboardController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.blue.monday.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.blue.monday.css?'.$CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('bare'); $this->_helper->layout->setLayout('bare');
@ -108,7 +107,7 @@ class DashboardController extends Zend_Controller_Action
if ($logo) { if ($logo) {
$this->view->logo = "data:image/png;base64,$logo"; $this->view->logo = "data:image/png;base64,$logo";
} else { } else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; $this->view->logo = $baseUrl."/css/images/airtime_logo_jp.png";
} }
} }

View file

@ -26,7 +26,7 @@ class LibraryController extends Zend_Controller_Action
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
@ -142,12 +142,14 @@ class LibraryController extends Zend_Controller_Action
public function contextMenuAction() public function contextMenuAction()
{ {
$baseUrl = Application_Common_OsPath::getBaseDir();
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$type = $this->_getParam('type'); $type = $this->_getParam('type');
//playlist||timeline //playlist||timeline
$screen = $this->_getParam('screen'); $screen = $this->_getParam('screen');
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = Application_Common_OsPath::getBaseDir();
$menu = array(); $menu = array();
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
@ -181,10 +183,10 @@ class LibraryController extends Zend_Controller_Action
} }
} }
} }
if ($isAdminOrPM || $file->getFileOwnerId() == $user->getId()) { if ($isAdminOrPM || $file->getFileOwnerId() == $user->getId()) {
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete"); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => $baseUrl."/library/delete");
$menu["edit"] = array("name"=> "Edit Metadata", "icon" => "edit", "url" => "/library/edit-file-md/id/{$id}"); $menu["edit"] = array("name"=> "Edit Metadata", "icon" => "edit", "url" => $baseUrl."/library/edit-file-md/id/{$id}");
} }
$url = $file->getRelativeFileUrl($baseUrl).'/download/true'; $url = $file->getRelativeFileUrl($baseUrl).'/download/true';
@ -209,8 +211,9 @@ class LibraryController extends Zend_Controller_Action
$menu["edit"] = array("name"=> "Edit", "icon" => "edit"); $menu["edit"] = array("name"=> "Edit", "icon" => "edit");
} }
} }
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete"); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => $baseUrl."/library/delete");
} }
} elseif ($type == "stream") { } elseif ($type == "stream") {
@ -225,9 +228,9 @@ class LibraryController extends Zend_Controller_Action
} }
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) { if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
if ($screen == "playlist") { if ($screen == "playlist") {
$menu["edit"] = array("name"=> "Edit", "icon" => "edit", "url" => "/library/edit-file-md/id/{$id}"); $menu["edit"] = array("name"=> "Edit", "icon" => "edit", "url" => $baseUrl."/library/edit-file-md/id/{$id}");
} }
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete"); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => $baseUrl."/library/delete");
} }
} }
@ -253,7 +256,7 @@ class LibraryController extends Zend_Controller_Action
$text = "Upload to SoundCloud"; $text = "Upload to SoundCloud";
} }
$menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}"); $menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => $baseUrl."/library/upload-file-soundcloud/id/{$id}");
} }
if (empty($menu)) { if (empty($menu)) {

View file

@ -11,8 +11,12 @@ class LoginController extends Zend_Controller_Action
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest();
if (Zend_Auth::getInstance()->hasIdentity())
{
if (Zend_Auth::getInstance()->hasIdentity()) {
$this->_redirect('Showbuilder'); $this->_redirect('Showbuilder');
} }
@ -20,8 +24,8 @@ class LoginController extends Zend_Controller_Action
$this->_helper->layout->setLayout('login'); $this->_helper->layout->setLayout('login');
$error = false; $error = false;
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/login.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/login.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -96,8 +100,8 @@ class LoginController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/password-restore.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/password-restore.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
if (!Application_Model_Preference::GetEnableSystemEmail()) { if (!Application_Model_Preference::GetEnableSystemEmail()) {

View file

@ -8,14 +8,15 @@ class PlayouthistoryController extends Zend_Controller_Action
$ajaxContext $ajaxContext
->addActionContext('playout-history-feed', 'json') ->addActionContext('playout-history-feed', 'json')
->initContext(); ->initContext();
} }
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$baseUrl = Application_Common_OsPath::getBaseDir();
//default time is the last 24 hours. //default time is the last 24 hours.
$now = time(); $now = time();
@ -81,4 +82,5 @@ class PlayouthistoryController extends Zend_Controller_Action
$this->view->iTotalRecords = $r["iTotalRecords"]; $this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->history = $r["history"]; $this->view->history = $r["history"];
} }
} }

View file

@ -15,8 +15,7 @@ class PluploadController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/plupload/plupload.full.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/plupload/plupload.full.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/plupload/jquery.plupload.queue.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/plupload/jquery.plupload.queue.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');

View file

@ -21,11 +21,12 @@ class PreferenceController extends Zend_Controller_Action
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/preferences.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/preferences.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->statusMsg = ""; $this->view->statusMsg = "";
@ -33,37 +34,47 @@ class PreferenceController extends Zend_Controller_Action
$form = new Application_Form_Preferences(); $form = new Application_Form_Preferences();
if ($request->isPost()) { if ($request->isPost()) {
if ($form->isValid($request->getPost())) { $params = $request->getPost();
$values = $form->getValues(); $postData = explode('&', $params['data']);
foreach($postData as $k=>$v) {
$v = explode('=', $v);
$values[$v[0]] = urldecode($v[1]);
}
if ($form->isValid($values)) {
Application_Model_Preference::SetHeadTitle($values["preferences_general"]["stationName"], $this->view); Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view);
Application_Model_Preference::SetDefaultFade($values["preferences_general"]["stationDefaultFade"]); Application_Model_Preference::SetDefaultFade($values["stationDefaultFade"]);
Application_Model_Preference::SetAllow3rdPartyApi($values["preferences_general"]["thirdPartyApi"]); Application_Model_Preference::SetAllow3rdPartyApi($values["thirdPartyApi"]);
Application_Model_Preference::SetTimezone($values["preferences_general"]["timezone"]); Application_Model_Preference::SetTimezone($values["timezone"]);
Application_Model_Preference::SetWeekStartDay($values["preferences_general"]["weekStartDay"]); Application_Model_Preference::SetWeekStartDay($values["weekStartDay"]);
if (!$isSaas) { if (!$isSaas) {
Application_Model_Preference::SetEnableSystemEmail($values["preferences_email_server"]["enableSystemEmail"]); Application_Model_Preference::SetEnableSystemEmail($values["enableSystemEmail"]);
Application_Model_Preference::SetSystemEmail($values["preferences_email_server"]["systemEmail"]); Application_Model_Preference::SetSystemEmail($values["systemEmail"]);
Application_Model_Preference::SetMailServerConfigured($values["preferences_email_server"]["configureMailServer"]); Application_Model_Preference::SetMailServerConfigured($values["configureMailServer"]);
Application_Model_Preference::SetMailServer($values["preferences_email_server"]["mailServer"]); Application_Model_Preference::SetMailServer($values["mailServer"]);
Application_Model_Preference::SetMailServerEmailAddress($values["preferences_email_server"]["email"]); Application_Model_Preference::SetMailServerEmailAddress($values["email"]);
Application_Model_Preference::SetMailServerPassword($values["preferences_email_server"]["ms_password"]); Application_Model_Preference::SetMailServerPassword($values["ms_password"]);
Application_Model_Preference::SetMailServerPort($values["preferences_email_server"]["port"]); Application_Model_Preference::SetMailServerPort($values["port"]);
Application_Model_Preference::SetMailServerRequiresAuth($values["preferences_email_server"]["msRequiresAuth"]); Application_Model_Preference::SetMailServerRequiresAuth($values["msRequiresAuth"]);
} }
Application_Model_Preference::SetAutoUploadRecordedShowToSoundcloud($values["preferences_soundcloud"]["UseSoundCloud"]); Application_Model_Preference::SetAutoUploadRecordedShowToSoundcloud($values["UseSoundCloud"]);
Application_Model_Preference::SetUploadToSoundcloudOption($values["preferences_soundcloud"]["UploadToSoundcloudOption"]); Application_Model_Preference::SetUploadToSoundcloudOption($values["UploadToSoundcloudOption"]);
Application_Model_Preference::SetSoundCloudDownloadbleOption($values["preferences_soundcloud"]["SoundCloudDownloadbleOption"]); Application_Model_Preference::SetSoundCloudDownloadbleOption($values["SoundCloudDownloadbleOption"]);
Application_Model_Preference::SetSoundCloudUser($values["preferences_soundcloud"]["SoundCloudUser"]); Application_Model_Preference::SetSoundCloudUser($values["SoundCloudUser"]);
Application_Model_Preference::SetSoundCloudPassword($values["preferences_soundcloud"]["SoundCloudPassword"]); Application_Model_Preference::SetSoundCloudPassword($values["SoundCloudPassword"]);
Application_Model_Preference::SetSoundCloudTags($values["preferences_soundcloud"]["SoundCloudTags"]); Application_Model_Preference::SetSoundCloudTags($values["SoundCloudTags"]);
Application_Model_Preference::SetSoundCloudGenre($values["preferences_soundcloud"]["SoundCloudGenre"]); Application_Model_Preference::SetSoundCloudGenre($values["SoundCloudGenre"]);
Application_Model_Preference::SetSoundCloudTrackType($values["preferences_soundcloud"]["SoundCloudTrackType"]); Application_Model_Preference::SetSoundCloudTrackType($values["SoundCloudTrackType"]);
Application_Model_Preference::SetSoundCloudLicense($values["preferences_soundcloud"]["SoundCloudLicense"]); Application_Model_Preference::SetSoundCloudLicense($values["SoundCloudLicense"]);
$this->view->statusMsg = "<div class='success'>Preferences updated.</div>"; $this->view->statusMsg = "<div class='success'>Preferences updated.</div>";
$this->view->form = $form;
die(json_encode(array("valid"=>"true", "html"=>$this->view->render('preference/index.phtml'))));
} else {
$this->view->form = $form;
die(json_encode(array("valid"=>"false", "html"=>$this->view->render('preference/index.phtml'))));
} }
} }
$this->view->form = $form; $this->view->form = $form;
@ -72,9 +83,10 @@ class PreferenceController extends Zend_Controller_Action
public function supportSettingAction() public function supportSettingAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/support-setting.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/support-setting.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->statusMsg = ""; $this->view->statusMsg = "";
@ -133,9 +145,9 @@ class PreferenceController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
if (Application_Model_Preference::GetPlanLevel() == 'disabled') { if(Application_Model_Preference::GetPlanLevel() == 'disabled'){
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'/js/serverbrowse/serverbrowser.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/serverbrowse/serverbrowser.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/musicdirs.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/musicdirs.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -151,7 +163,8 @@ class PreferenceController extends Zend_Controller_Action
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/streamsetting.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/streamsetting.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -203,10 +216,37 @@ class PreferenceController extends Zend_Controller_Action
$form->addSubForm($subform, "s".$i."_subform"); $form->addSubForm($subform, "s".$i."_subform");
} }
if ($request->isPost()) { if ($request->isPost()) {
$values = $request->getPost(); $params = $request->getPost();
/* Parse through post data and put in format
* $form->isValid() is expecting it in
*/
$postData = explode('&', $params['data']);
$s1_data = array();
$s2_data = array();
$s3_data = array();
foreach($postData as $k=>$v) {
$v = explode('=', urldecode($v));
if (strpos($v[0], "s1_data") !== false) {
/* In this case $v[0] may be 's1_data[enable]' , for example.
* We only want the 'enable' part
*/
preg_match('/\[(.*)\]/', $v[0], $matches);
$s1_data[$matches[1]] = $v[1];
} elseif (strpos($v[0], "s2_data") !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
$s2_data[$matches[1]] = $v[1];
} elseif (strpos($v[0], "s3_data") !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
$s3_data[$matches[1]] = $v[1];
} else {
$values[$v[0]] = $v[1];
}
}
$values["s1_data"] = $s1_data;
$values["s2_data"] = $s2_data;
$values["s3_data"] = $s3_data;
$error = false; $error = false;
if ($form->isValid($values)) { if ($form->isValid($values)) {
if (!$isSaas) { if (!$isSaas) {
$values['output_sound_device'] = $form->getValue('output_sound_device'); $values['output_sound_device'] = $form->getValue('output_sound_device');
@ -267,12 +307,23 @@ class PreferenceController extends Zend_Controller_Action
} }
Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data); Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data);
$live_stream_subform->updateVariables();
$this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf();
$this->view->form = $form;
$this->view->num_stream = $num_of_stream;
$this->view->statusMsg = "<div class='success'>Stream Setting Updated.</div>"; $this->view->statusMsg = "<div class='success'>Stream Setting Updated.</div>";
die(json_encode(array("valid"=>"true", "html"=>$this->view->render('preference/stream-setting.phtml'))));
} else {
$live_stream_subform->updateVariables();
$this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf();
$this->view->form = $form;
$this->view->num_stream = $num_of_stream;
die(json_encode(array("valid"=>"false", "html"=>$this->view->render('preference/stream-setting.phtml'))));
} }
} }
$live_stream_subform->updateVariables(); $live_stream_subform->updateVariables();
$this->view->confirm_pypo_restart_text = "If you change the username or password values for an enabled stream the playout engine will be rebooted and your listeners will hear silence for 5-10 seconds. Changing the following fields will NOT cause a reboot: Stream Label (Global Settings), and Switch Transition Fade(s), Master Username, and Master Password (Input Stream Settings). If Airtime is recording, and if the change causes a playout engine restart, the recording will be interrupted.";
$this->view->num_stream = $num_of_stream; $this->view->num_stream = $num_of_stream;
$this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf(); $this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf();

View file

@ -227,6 +227,7 @@ class ScheduleController extends Zend_Controller_Action
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$menu = array(); $menu = array();
$epochNow = time(); $epochNow = time();
$baseUrl = Application_Common_OsPath::getBaseDir();
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
@ -250,7 +251,7 @@ class ScheduleController extends Zend_Controller_Action
$fileId = $file->getId(); $fileId = $file->getId();
$menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview", $menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview",
"url" => "/library/edit-file-md/id/".$fileId); "url" => $baseUrl."/library/edit-file-md/id/".$fileId);
} }
if ($epochNow < $showStartLocalDT->getTimestamp()) { if ($epochNow < $showStartLocalDT->getTimestamp()) {
@ -259,16 +260,16 @@ class ScheduleController extends Zend_Controller_Action
&& !$instance->isRebroadcast()) { && !$instance->isRebroadcast()) {
$menu["schedule"] = array("name"=> "Add / Remove Content", "icon" => "add-remove-content", $menu["schedule"] = array("name"=> "Add / Remove Content", "icon" => "add-remove-content",
"url" => "/showbuilder/builder-dialog/"); "url" => $baseUrl."/showbuilder/builder-dialog/");
$menu["clear"] = array("name"=> "Remove All Content", "icon" => "remove-all-content", $menu["clear"] = array("name"=> "Remove All Content", "icon" => "remove-all-content",
"url" => "/schedule/clear-show"); "url" => $baseUrl."/schedule/clear-show");
} }
} }
if (!$instance->isRecorded()) { if (!$instance->isRecorded()) {
$menu["content"] = array("name"=> "Show Content", "icon" => "overview", "url" => "/schedule/show-content-dialog"); $menu["content"] = array("name"=> "Show Content", "icon" => "overview", "url" => $baseUrl."/schedule/show-content-dialog");
} }
if ($showEndLocalDT->getTimestamp() <= $epochNow if ($showEndLocalDT->getTimestamp() <= $epochNow
@ -296,7 +297,7 @@ class ScheduleController extends Zend_Controller_Action
} else { } else {
if (!$instance->isRebroadcast()) { if (!$instance->isRebroadcast()) {
$menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => "/Schedule/populate-show-form"); $menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => $baseUrl."/Schedule/populate-show-form");
} }
$menu["cancel"] = array("name"=> "Cancel Current Show", "icon" => "delete"); $menu["cancel"] = array("name"=> "Cancel Current Show", "icon" => "delete");
@ -306,7 +307,7 @@ class ScheduleController extends Zend_Controller_Action
if ($epochNow < $showStartLocalDT->getTimestamp()) { if ($epochNow < $showStartLocalDT->getTimestamp()) {
if (!$instance->isRebroadcast() && $isAdminOrPM) { if (!$instance->isRebroadcast() && $isAdminOrPM) {
$menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => "/Schedule/populate-show-form"); $menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => $baseUrl."/Schedule/populate-show-form");
} }
if ($instance->getShow()->isRepeating() && $isAdminOrPM) { if ($instance->getShow()->isRepeating() && $isAdminOrPM) {
@ -314,12 +315,12 @@ class ScheduleController extends Zend_Controller_Action
//create delete sub menu. //create delete sub menu.
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "items" => array()); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "items" => array());
$menu["del"]["items"]["single"] = array("name"=> "Delete This Instance", "icon" => "delete", "url" => "/schedule/delete-show"); $menu["del"]["items"]["single"] = array("name"=> "Delete This Instance", "icon" => "delete", "url" => $baseUrl."/schedule/delete-show");
$menu["del"]["items"]["following"] = array("name"=> "Delete This Instance and All Following", "icon" => "delete", "url" => "/schedule/cancel-show"); $menu["del"]["items"]["following"] = array("name"=> "Delete This Instance and All Following", "icon" => "delete", "url" => $baseUrl."/schedule/cancel-show");
} elseif ($isAdminOrPM) { } elseif ($isAdminOrPM) {
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/schedule/delete-show"); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => $baseUrl."/schedule/delete-show");
} }
} }

View file

@ -18,12 +18,14 @@ class ShowbuilderController extends Zend_Controller_Action
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$user = Application_Model_User::getCurrentUser(); $baseUrl = Application_Common_OsPath::getBaseDir();
$user = Application_Model_User::GetCurrentUser();
$userType = $user->getType(); $userType = $user->getType();
$this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );"); $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );");
@ -42,7 +44,7 @@ class ShowbuilderController extends Zend_Controller_Action
} else { } else {
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );"); $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );");
} }
$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -62,8 +64,7 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$refer_sses = new Zend_Session_Namespace('referrer'); $refer_sses = new Zend_Session_Namespace('referrer');
if ($request->isPost()) { if ($request->isPost()) {
@ -173,6 +174,8 @@ class ShowbuilderController extends Zend_Controller_Action
public function contextMenuAction() public function contextMenuAction()
{ {
$baseUrl = Application_Common_OsPath::getBaseDir();
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$now = floatval(microtime(true)); $now = floatval(microtime(true));
@ -192,7 +195,7 @@ class ShowbuilderController extends Zend_Controller_Action
if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) { if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) {
//remove/truncate the item from the schedule //remove/truncate the item from the schedule
$menu["del"] = array("name"=> "Remove from show", "icon" => "delete", "url" => "/showbuilder/schedule-remove"); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => $baseUrl."/showbuilder/schedule-remove");
} }
$this->view->items = $menu; $this->view->items = $menu;

View file

@ -6,8 +6,7 @@ class SystemstatusController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $baseUrl = Application_Common_OsPath::getBaseDir();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/status/status.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/status/status.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
} }

View file

@ -18,7 +18,7 @@ class UserController extends Zend_Controller_Action
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = Application_Common_OsPath::getBaseDir();
$js_files = array( $js_files = array(
'/js/datatables/js/jquery.dataTables.js?', '/js/datatables/js/jquery.dataTables.js?',
@ -38,39 +38,53 @@ class UserController extends Zend_Controller_Action
$this->view->successMessage = ""; $this->view->successMessage = "";
if ($request->isPost()) { if ($request->isPost()) {
if ($form->isValid($request->getPost())) { $params = $request->getPost();
$postData = explode('&', $params['data']);
foreach($postData as $k=>$v) {
$v = explode('=', $v);
$formData[$v[0]] = urldecode($v[1]);
}
if ($form->isValid($formData)) {
$formdata = $form->getValues();
if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1 if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1
&& $formdata['login'] == 'admin' && $formData['login'] == 'admin'
&& $formdata['user_id'] != 0) { && $formData['user_id'] != 0) {
$this->view->form = $form;
$this->view->successMessage = "<div class='errors'>Specific action is not allowed in demo version!</div>"; $this->view->successMessage = "<div class='errors'>Specific action is not allowed in demo version!</div>";
} elseif ($form->validateLogin($formdata)) { die(json_encode(array("valid"=>"false", "html"=>$this->view->render('user/add-user.phtml'))));
$user = new Application_Model_User($formdata['user_id']); } elseif ($form->validateLogin($formData)) {
$user->setFirstName($formdata['first_name']); $user = new Application_Model_User($formData['user_id']);
$user->setLastName($formdata['last_name']); $user->setFirstName($formData['first_name']);
$user->setLogin($formdata['login']); $user->setLastName($formData['last_name']);
$user->setLogin($formData['login']);
// We don't allow 6 x's as a password. // We don't allow 6 x's as a password.
// The reason is because we that as a password placeholder // The reason is because we that as a password placeholder
// on the client side. // on the client side.
if ($formdata['password'] != "xxxxxx") { if ($formData['password'] != "xxxxxx") {
$user->setPassword($formdata['password']); $user->setPassword($formData['password']);
} }
$user->setType($formdata['type']); $user->setType($formData['type']);
$user->setEmail($formdata['email']); $user->setEmail($formData['email']);
$user->setCellPhone($formdata['cell_phone']); $user->setCellPhone($formData['cell_phone']);
$user->setSkype($formdata['skype']); $user->setSkype($formData['skype']);
$user->setJabber($formdata['jabber']); $user->setJabber($formData['jabber']);
$user->save(); $user->save();
$form->reset(); $form->reset();
$this->view->form = $form;
if (strlen($formdata['user_id']) == 0) { if (strlen($formData['user_id']) == 0) {
$this->view->successMessage = "<div class='success'>User added successfully!</div>"; $this->view->successMessage = "<div class='success'>User added successfully!</div>";
} else { } else {
$this->view->successMessage = "<div class='success'>User updated successfully!</div>"; $this->view->successMessage = "<div class='success'>User updated successfully!</div>";
} }
die(json_encode(array("valid"=>"true", "html"=>$this->view->render('user/add-user.phtml'))));
} }
} else {
$this->view->form = $form;
die(json_encode(array("valid"=>"false", "html"=>$this->view->render('user/add-user.phtml'))));
} }
} }

View file

@ -11,6 +11,8 @@ class Application_Form_AddUser extends Zend_Form
'validate'); 'validate');
* */ * */
$this->setAttrib('id', 'user_form');
$hidden = new Zend_Form_Element_Hidden('user_id'); $hidden = new Zend_Form_Element_Hidden('user_id');
$hidden->setDecorators(array('ViewHelper')); $hidden->setDecorators(array('ViewHelper'));
$this->addElement($hidden); $this->addElement($hidden);
@ -85,11 +87,11 @@ class Application_Form_AddUser extends Zend_Form
$select->setRequired(true); $select->setRequired(true);
$this->addElement($select); $this->addElement($select);
$submit = new Zend_Form_Element_Submit('submit'); $saveBtn = new Zend_Form_Element_Button('save_user');
$submit->setAttrib('class', 'ui-button ui-state-default right-floated'); $saveBtn->setAttrib('class', 'btn btn-small right-floated');
$submit->setIgnore(true); $saveBtn->setIgnore(true);
$submit->setLabel('Save'); $saveBtn->setLabel('Save');
$this->addElement($submit); $this->addElement($saveBtn);
} }
public function validateLogin($data) public function validateLogin($data)

View file

@ -4,6 +4,7 @@ class Application_Form_EditAudioMD extends Zend_Form
{ {
public function init() public function init()
{ {
$baseUrl = Application_Common_OsPath::getBaseDir();
// Set the method for the display form to POST // Set the method for the display form to POST
$this->setMethod('post'); $this->setMethod('post');
@ -135,7 +136,7 @@ class Application_Form_EditAudioMD extends Zend_Form
'ignore' => true, 'ignore' => true,
'class' => 'btn md-cancel', 'class' => 'btn md-cancel',
'label' => 'Cancel', 'label' => 'Cancel',
'onclick' => 'javascript:document.location.href = "/Library"', 'onclick' => 'javascript:document.location.href="'.$baseUrl.'/Library"',
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )

View file

@ -156,17 +156,20 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
if ($master_harbor_input_port == $dj_harbor_input_port && $master_harbor_input_port != "") { if ($master_harbor_input_port == $dj_harbor_input_port && $master_harbor_input_port != "") {
$element = $this->getElement("dj_harbor_input_port"); $element = $this->getElement("dj_harbor_input_port");
$element->addError("You cannot use same port as Master DJ port."); $element->addError("You cannot use same port as Master DJ port.");
$isValid = false;
} }
if ($master_harbor_input_port != "") { if ($master_harbor_input_port != "") {
if (is_numeric($master_harbor_input_port)) { if (is_numeric($master_harbor_input_port)) {
if ($master_harbor_input_port != Application_Model_StreamSetting::getMasterLiveStreamPort()) { if ($master_harbor_input_port != Application_Model_StreamSetting::getMasterLiveStreamPort()) {
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$res = socket_bind($sock, 0, $master_harbor_input_port); try {
if (!$res) { socket_bind($sock, 0, $master_harbor_input_port);
} catch (Exception $e) {
$element = $this->getElement("master_harbor_input_port"); $element = $this->getElement("master_harbor_input_port");
$element->addError("Port '$master_harbor_input_port' is not available."); $element->addError("Port '$master_harbor_input_port' is not available.");
$isValid = false; $isValid = false;
} }
socket_close($sock); socket_close($sock);
} }
} else { } else {
@ -177,8 +180,9 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
if (is_numeric($dj_harbor_input_port)) { if (is_numeric($dj_harbor_input_port)) {
if ($dj_harbor_input_port != Application_Model_StreamSetting::getDjLiveStreamPort()) { if ($dj_harbor_input_port != Application_Model_StreamSetting::getDjLiveStreamPort()) {
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$res = socket_bind($sock, 0, $dj_harbor_input_port); try {
if (!$res) { socket_bind($sock, 0, $dj_harbor_input_port);
} catch (Exception $e) {
$element = $this->getElement("dj_harbor_input_port"); $element = $this->getElement("dj_harbor_input_port");
$element->addError("Port '$dj_harbor_input_port' is not available."); $element->addError("Port '$dj_harbor_input_port' is not available.");
$isValid = false; $isValid = false;

View file

@ -6,7 +6,8 @@ class Application_Form_Preferences extends Zend_Form
public function init() public function init()
{ {
$this->setAction('/Preference'); $baseUrl = Application_Common_OsPath::getBaseDir();
$this->setMethod('post'); $this->setMethod('post');
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
@ -27,13 +28,11 @@ class Application_Form_Preferences extends Zend_Form
$soundcloud_pref = new Application_Form_SoundcloudPreferences(); $soundcloud_pref = new Application_Form_SoundcloudPreferences();
$this->addSubForm($soundcloud_pref, 'preferences_soundcloud'); $this->addSubForm($soundcloud_pref, 'preferences_soundcloud');
$this->addElement('submit', 'submit', array( $saveBtn = new Zend_Form_Element_Button('pref_save');
'class' => 'ui-button ui-state-default right-floated', $saveBtn->setAttrib('class', 'btn btn-small right-floated');
'ignore' => true, $saveBtn->setIgnore(true);
'label' => 'Save', $saveBtn->setLabel('Save');
'decorators' => array( $this->addElement($saveBtn);
'ViewHelper'
)
));
} }
} }

View file

@ -6,6 +6,7 @@
<?php echo $this->headScript() ?> <?php echo $this->headScript() ?>
<?php echo $this->headLink() ?> <?php echo $this->headLink() ?>
<?php echo isset($this->google_analytics)?$this->google_analytics:"" ?> <?php echo isset($this->google_analytics)?$this->google_analytics:"" ?>
<?php $baseUrl = Application_Common_OsPath::getBaseDir(); ?>
</head> </head>
<body> <body>
@ -22,7 +23,7 @@
$this->navigation()->menu()->setPartial($partial); ?> $this->navigation()->menu()->setPartial($partial); ?>
<div class="personal-block solo"> <div class="personal-block solo">
<ul> <ul>
<li><span class="name"><?php echo $this->loggedInAs()?></span> | <a href="/Login/logout">Logout</a></li> <li><span class="name"><?php echo $this->loggedInAs()?></span> | <a href=<?php echo $baseUrl . "/Login/logout"?>>Logout</a></li>
</ul> </ul>
</div> </div>

View file

@ -500,6 +500,7 @@ class Application_Model_Preference
} else { } else {
$outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL; $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL;
} }
$outputArray['STATION_NAME'] = self::GetStationName(); $outputArray['STATION_NAME'] = self::GetStationName();
$outputArray['PHONE'] = self::GetPhone(); $outputArray['PHONE'] = self::GetPhone();
$outputArray['EMAIL'] = self::GetEmail(); $outputArray['EMAIL'] = self::GetEmail();
@ -513,7 +514,7 @@ class Application_Model_Preference
$url = $systemInfoArray["AIRTIME_VERSION_URL"]; $url = $systemInfoArray["AIRTIME_VERSION_URL"];
$index = strpos($url,'/api/'); $index = strpos($url,'/api/');
$url = substr($url, 0, $index); $url = substr($url, 0, $index);
$headerInfo = get_headers(trim($url),1); $headerInfo = get_headers(trim($url),1);
$outputArray['WEB_SERVER'] = $headerInfo['Server'][0]; $outputArray['WEB_SERVER'] = $headerInfo['Server'][0];
} }

View file

@ -610,6 +610,7 @@ SQL;
return $res; return $res;
} }
public static function getLibraryColumns() public static function getLibraryColumns()
{ {
return array("id", "track_title", "artist_name", "album_title", return array("id", "track_title", "artist_name", "album_title",
@ -620,9 +621,10 @@ SQL;
"conductor", "replay_gain", "lptime" ); "conductor", "replay_gain", "lptime" );
} }
public static function searchLibraryFiles($datatables) public static function searchLibraryFiles($datatables)
{ {
$baseUrl = Application_Common_OsPath::getBaseDir();
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME); $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$displayColumns = self::getLibraryColumns(); $displayColumns = self::getLibraryColumns();
@ -777,14 +779,14 @@ SQL;
// ugly // ugly
if ($type == "au") { if ($type == "au") {
$row['audioFile'] = $row['id'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION); $row['audioFile'] = $row['id'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION);
$row['image'] = '<img title="Track preview" src="/css/images/icon_audioclip.png">'; $row['image'] = '<img title="Track preview" src="'.$baseUrl.'/css/images/icon_audioclip.png">';
} elseif ($type == "pl") { } elseif ($type == "pl") {
$row['image'] = '<img title="Playlist preview" src="/css/images/icon_playlist.png">'; $row['image'] = '<img title="Playlist preview" src="'.$baseUrl.'/css/images/icon_playlist.png">';
} elseif ($type == "st") { } elseif ($type == "st") {
$row['audioFile'] = $row['id']; $row['audioFile'] = $row['id'];
$row['image'] = '<img title="Webstream preview" src="/css/images/icon_webstream.png">'; $row['image'] = '<img title="Webstream preview" src="'.$baseUrl.'/css/images/icon_webstream.png">';
} elseif ($type == "bl") { } elseif ($type == "bl") {
$row['image'] = '<img title="Smart Block" src="/css/images/icon_smart-block.png">'; $row['image'] = '<img title="Smart Block" src="'.$baseUrl.'/css/images/icon_smart-block.png">';
} }
} }

View file

@ -1,4 +1,4 @@
<img src="/css/images/big_gray_logo.png" width="287" height="109" alt="Airtime" class="gray-logo" /> <div class="gray-logo"></div>
<div class="text-content"> <div class="text-content">
<h2>Welcome to Airtime!</h2> <h2>Welcome to Airtime!</h2>
<p>Here's how you can get started using Airtime to automate your broadcasts: </p> <p>Here's how you can get started using Airtime to automate your broadcasts: </p>

View file

@ -46,7 +46,7 @@
</dt> </dt>
<dd id="add_show_duration-element"> <dd id="add_show_duration-element">
<?php echo $this->element->getElement('add_show_duration') ?> <?php echo $this->element->getElement('add_show_duration') ?>
<img id="icon-loader-small" src="/css/images/loader-small.gif" style="vertical-align:middle; display:none;"/> <img id="icon-loader-small"/>
</dd> </dd>
<?php if($this->element->getElement('add_show_duration')->hasErrors()){ ?> <?php if($this->element->getElement('add_show_duration')->hasErrors()){ ?>
<ul class='errors'> <ul class='errors'>

View file

@ -1,4 +1,4 @@
<form method="<?php echo $this->element->getMethod() ?>" action="<?php echo $this->element->getAction() ?>" enctype="multipart/form-data"> <form method="<?php echo $this->element->getMethod() ?>" enctype="multipart/form-data">
<?php echo $this->element->getSubform('preferences_general') ?> <?php echo $this->element->getSubform('preferences_general') ?>
@ -15,8 +15,6 @@
<?php echo $this->element->getSubform('preferences_soundcloud') ?> <?php echo $this->element->getSubform('preferences_soundcloud') ?>
</div> </div>
<div class="button-bar bottom" id="submit-element"> <?php echo $this->element->getElement('pref_save') ?>
<?php echo $this->element->getElement('submit') ?>
</div>
</form> </form>

View file

@ -1,7 +1,8 @@
<div id="import_status" class="library_import" style="display:none">File import in progress... <img src="/css/images/file_import_loader.gif"></img></div> <?php $baseUrl = Application_Common_OsPath::getBaseDir(); ?>
<fieldset class="toggle closed" id="filter_options"> <div id="import_status" class="library_import" style="display:none">File import in progress...<img src=<?php $baseUrl . "/css/images/file_import_loader.gif"?>></img></div>
<fieldset class="toggle" id="filter_options">
<legend style="cursor: pointer;"><span class="ui-icon ui-icon-triangle-2-n-s"></span>Advanced Search Options</legend> <legend style="cursor: pointer;"><span class="ui-icon ui-icon-triangle-2-n-s"></span>Advanced Search Options</legend>
<div id="advanced_search" class="advanced_search form-horizontal"></div> <div id="advanced_search" class="advanced_search form-horizontal"></div>
</fieldset> </fieldset>
<table id="library_display" cellpadding="0" cellspacing="0" class="datatable"> <table id="library_display" cellpadding="0" cellspacing="0" class="datatable">
</table> </table>

View file

@ -1,10 +1,9 @@
<div class="ui-widget ui-widget-content block-shadow simple-formblock clearfix padded-strong preferences"> <div class="ui-widget ui-widget-content block-shadow simple-formblock clearfix padded-strong preferences">
<h2 style="float:left">Preferences</h2> <h2 style="float:left">Preferences</h2>
<form method="post" action="/Preference/index" enctype="application/x-www-form-urlencoded"> <?php $baseUrl = Application_Common_OsPath::getBaseDir(); ?>
<form method="post" id="pref_form" enctype="application/x-www-form-urlencoded">
<div class="button-bar bottom" id="submit-element" style="float:right"> <button name="pref_save" id="pref_save" type="button" class="btn btn-small right-floated">Save</button>
<input type="submit" class="ui-button ui-state-default right-floated" value="Save" id="Save" name="Save" />
</div>
<div style="clear:both"></div> <div style="clear:both"></div>
<?php <?php

View file

@ -1,10 +1,9 @@
<div class="ui-widget ui-widget-content block-shadow simple-formblock clearfix padded-strong stream-config"> <div class="ui-widget ui-widget-content block-shadow simple-formblock clearfix padded-strong stream-config">
<h2 <?php if($this->enable_stream_conf == "true"){?>style="float:left"<?php }?>>Stream Settings</h2> <h2 <?php if($this->enable_stream_conf == "true"){?>style="float:left"<?php }?>>Stream Settings</h2>
<?php $baseUrl = Application_Common_OsPath::getBaseDir(); ?>
<?php if($this->enable_stream_conf == "true"){?> <?php if($this->enable_stream_conf == "true"){?>
<form method="post" action="/Preference/stream-setting" enctype="application/x-www-form-urlencoded" onsubmit="return confirm('<?php echo $this->confirm_pypo_restart_text ?>');"> <form method="post" id="stream_form" enctype="application/x-www-form-urlencoded">
<div class="button-bar bottom" id="submit-element" style="float:right"> <button name="stream_save" id="stream_save" type="button" class="btn btn-small right-floated">Save</button>
<input type="submit" class="ui-button ui-state-default right-floated" value="Save" id="Save" name="Save" />
</div>
<div style="clear:both"></div> <div style="clear:both"></div>
<?php }?> <?php }?>
<?php echo $this->statusMsg;?> <?php echo $this->statusMsg;?>
@ -78,9 +77,8 @@
?> ?>
</fieldset> </fieldset>
<?php if($this->enable_stream_conf == "true"){?> <?php if($this->enable_stream_conf == "true"){?>
<div class="button-bar bottom" id="submit-element"> <br />
<input type="submit" class="ui-button ui-state-default right-floated" value="Save" id="Save" name="Save" /> <button name="stream_save" id="stream_save" type="button" class="btn btn-small right-floated">Save</button>
</div>
<?php }?> <?php }?>
</div> </div>
</form> </form>

View file

@ -1,6 +1,7 @@
<div class="ui-widget ui-widget-content block-shadow simple-formblock clearfix padded-strong preferences"> <div class="ui-widget ui-widget-content block-shadow simple-formblock clearfix padded-strong preferences">
<h2><?php echo $this->section_title?></h2> <h2><?php echo $this->section_title?></h2>
<form method="post" action="/Preference/support-setting" enctype="multipart/form-data"> <?php $baseUrl = Application_Common_OsPath::getBaseDir(); ?>
<form method="post" action=<?php echo $baseUrl . "/Preference/support-setting"?> enctype="multipart/form-data">
<div id="support-settings"> <div id="support-settings">
<?php echo $this->statusMsg ?> <?php echo $this->statusMsg ?>
<?php echo $this->form ?> <?php echo $this->form ?>

View file

@ -17,6 +17,7 @@ web_server_user = www-data
airtime_dir = x airtime_dir = x
base_url = localhost base_url = localhost
base_port = 80 base_port = 80
base_dir = ''
;How many hours ahead of time should Airtime playout engine (PYPO) ;How many hours ahead of time should Airtime playout engine (PYPO)
;cache scheduled media files. ;cache scheduled media files.

View file

@ -10,7 +10,8 @@ RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L] RewriteRule ^.*$ index.php [NC,L]
RewriteBase / #RewriteBase /
AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/html

View file

@ -71,16 +71,16 @@ select {
background-position:center; background-position:center;
} }
#version-icon.outdated { #version-icon.outdated {
background-image:url(/css/images/icon_outdated.png); background-image:url(images/icon_outdated.png);
} }
#version-icon.update2 { #version-icon.update2 {
background-image:url(/css/images/icon_update2.png); background-image:url(images/icon_update2.png);
} }
#version-icon.update { #version-icon.update {
background-image:url(/css/images/icon_update.png); background-image:url(images/icon_update.png);
} }
#version-icon.uptodate { #version-icon.uptodate {
background-image:url(/css/images/icon_uptodate.png); background-image:url(images/icon_uptodate.png);
} }
#ui-tooltip-version a { #ui-tooltip-version a {
@ -99,7 +99,7 @@ select {
display:inline-block; zoom:1; display:inline; display:inline-block; zoom:1; display:inline;
width:14px; height:14px; width:14px; height:14px;
background:url(/css/images/icon_info.png) 0 0 no-repeat; background:url(images/icon_info.png) 0 0 no-repeat;
float:right; position:relative; top:2px; right:7px; float:right; position:relative; top:2px; right:7px;
line-height:16px !important; line-height:16px !important;
} }
@ -110,7 +110,7 @@ select {
position: relative; position: relative;
display:inline-block; zoom:1; display:inline-block; zoom:1;
width:14px; height:14px; width:14px; height:14px;
background:url(/css/images/icon_info.png) 0 0 no-repeat; background:url(images/icon_info.png) 0 0 no-repeat;
top:2px; right:7px; left: 3px; top:2px; right:7px; left: 3px;
line-height:16px !important; line-height:16px !important;
} }

View file

@ -75,8 +75,8 @@ function playAllPlaylist(p_playlistID, p_playlistIndex) {
if ( _idToPostionLookUp !== undefined && viewsPlaylistID == p_playlistID ) { if ( _idToPostionLookUp !== undefined && viewsPlaylistID == p_playlistID ) {
play(p_playlistIndex); play(p_playlistIndex);
} else { }else {
buildplaylist("/audiopreview/get-playlist/playlistID/"+p_playlistID, p_playlistIndex); buildplaylist(baseUrl+"/audiopreview/get-playlist/playlistID/"+p_playlistID, p_playlistIndex);
} }
} }
@ -87,7 +87,7 @@ function playBlock(p_blockId, p_blockIndex)
if ( _idToPostionLookUp !== undefined && viewsBlockId == p_blockId ) { if ( _idToPostionLookUp !== undefined && viewsBlockId == p_blockId ) {
play(p_blockIndex); play(p_blockIndex);
} else { } else {
buildplaylist("/audiopreview/get-block/blockId/"+p_blockId, p_blockIndex); buildplaylist(baseUrl+"/audiopreview/get-block/blockId/"+p_blockId, p_blockIndex);
} }
} }
@ -105,7 +105,7 @@ function playAllShow(p_showID, p_index) {
if ( _idToPostionLookUp !== undefined && viewsShowID == p_showID ) { if ( _idToPostionLookUp !== undefined && viewsShowID == p_showID ) {
play(p_index); play(p_index);
}else { }else {
buildplaylist("/audiopreview/get-show/showID/"+p_showID, p_index); buildplaylist(baseUrl+"/audiopreview/get-show/showID/"+p_showID, p_index);
} }
} }
@ -124,6 +124,7 @@ function buildplaylist(p_url, p_playIndex) {
var index; var index;
var total = 0; var total = 0;
var skipped = 0; var skipped = 0;
for(index in data) { for(index in data) {
if (data[index]['type'] == 0) { if (data[index]['type'] == 0) {
if (data[index]['element_mp3'] != undefined){ if (data[index]['element_mp3'] != undefined){
@ -208,7 +209,7 @@ function play(p_playlistIndex){
*/ */
function playOne(uri, mime) { function playOne(uri, mime) {
var playlist = new Array(); var playlist = new Array();
var media = null; var media = null;
var key = null; var key = null;
if (mime.search(/mp3/i) > 0 || mime.search(/mpeg/i) > 0) { if (mime.search(/mp3/i) > 0 || mime.search(/mpeg/i) > 0) {

View file

@ -53,12 +53,10 @@ function open_audio_preview(type, id, audioFileTitle, audioFileArtist) {
if(index != -1){ if(index != -1){
audioFileTitle = audioFileTitle.substring(0,index); audioFileTitle = audioFileTitle.substring(0,index);
} }
// The reason that we need to encode artist and title string is that // The reason that we need to encode artist and title string is that
// sometime they contain '/' or '\' and apache reject %2f or %5f // sometime they contain '/' or '\' and apache reject %2f or %5f
// so the work around is to encode it twice. // so the work around is to encode it twice.
openPreviewWindow('audiopreview/audio-preview/audioFileID/'+id+'/audioFileArtist/'+encodeURIComponent(encodeURIComponent(audioFileArtist))+'/audioFileTitle/'+encodeURIComponent(encodeURIComponent(audioFileTitle))+'/type/'+type); openPreviewWindow(baseUrl+'audiopreview/audio-preview/audioFileID/'+id+'/audioFileArtist/'+encodeURIComponent(encodeURIComponent(audioFileArtist))+'/audioFileTitle/'+encodeURIComponent(encodeURIComponent(audioFileTitle))+'/type/'+type);
_preview_window.focus(); _preview_window.focus();
} }
@ -76,7 +74,7 @@ function open_playlist_preview(p_playlistID, p_playlistIndex) {
if (_preview_window != null && !_preview_window.closed) if (_preview_window != null && !_preview_window.closed)
_preview_window.playAllPlaylist(p_playlistID, p_playlistIndex); _preview_window.playAllPlaylist(p_playlistID, p_playlistIndex);
else else
openPreviewWindow('audiopreview/playlist-preview/playlistIndex/'+p_playlistIndex+'/playlistID/'+p_playlistID); openPreviewWindow(baseUrl+'/audiopreview/playlist-preview/playlistIndex/'+p_playlistIndex+'/playlistID/'+p_playlistID);
_preview_window.focus(); _preview_window.focus();
} }
@ -87,7 +85,7 @@ function open_block_preview(p_blockId, p_blockIndex) {
if (_preview_window != null && !_preview_window.closed) if (_preview_window != null && !_preview_window.closed)
_preview_window.playBlock(p_blockId, p_blockIndex); _preview_window.playBlock(p_blockId, p_blockIndex);
else else
openPreviewWindow('audiopreview/block-preview/blockIndex/'+p_blockIndex+'/blockId/'+p_blockId); openPreviewWindow(baseUrl+'/audiopreview/block-preview/blockIndex/'+p_blockIndex+'/blockId/'+p_blockId);
_preview_window.focus(); _preview_window.focus();
} }
@ -101,7 +99,7 @@ function open_show_preview(p_showID, p_showIndex) {
if (_preview_window != null && !_preview_window.closed) if (_preview_window != null && !_preview_window.closed)
_preview_window.playAllShow(p_showID, p_showIndex); _preview_window.playAllShow(p_showID, p_showIndex);
else else
openPreviewWindow('audiopreview/show-preview/showID/'+p_showID+'/showIndex/'+p_showIndex); openPreviewWindow(baseUrl+'/audiopreview/show-preview/showID/'+p_showID+'/showIndex/'+p_showIndex);
_preview_window.focus(); _preview_window.focus();
} }
@ -113,3 +111,9 @@ function openPreviewWindow(url) {
function pad(number, length) { function pad(number, length) {
return sprintf("%'0"+length+"d", number); return sprintf("%'0"+length+"d", number);
} }
function removeSuccessMsg() {
var $status = $('.success');
$status.fadeOut("slow", function(){$status.empty()});
}

View file

@ -360,7 +360,7 @@ function controlSwitchLight(){
} }
function getScheduleFromServer(){ function getScheduleFromServer(){
$.ajax({ url: "/Schedule/get-current-playlist/format/json", dataType:"json", success:function(data){ $.ajax({ url: baseUrl+"/Schedule/get-current-playlist/format/json", dataType:"json", success:function(data){
parseItems(data.entries); parseItems(data.entries);
parseSourceStatus(data.source_status); parseSourceStatus(data.source_status);
parseSwitchStatus(data.switch_status); parseSwitchStatus(data.switch_status);
@ -398,7 +398,7 @@ function setSwitchListener(ele){
var sourcename = $(ele).attr('id'); var sourcename = $(ele).attr('id');
var status_span = $(ele).find("span"); var status_span = $(ele).find("span");
var status = status_span.html(); var status = status_span.html();
$.get("/Dashboard/switch-source/format/json/sourcename/"+sourcename+"/status/"+status, function(data){ $.get(baseUrl+"/Dashboard/switch-source/format/json/sourcename/"+sourcename+"/status/"+status, function(data){
if(data.error){ if(data.error){
alert(data.error); alert(data.error);
}else{ }else{
@ -415,7 +415,7 @@ function setSwitchListener(ele){
function kickSource(ele){ function kickSource(ele){
var sourcename = $(ele).attr('id'); var sourcename = $(ele).attr('id');
$.get("/Dashboard/disconnect-source/format/json/sourcename/"+sourcename, function(data){ $.get(baseUrl+"/Dashboard/disconnect-source/format/json/sourcename/"+sourcename, function(data){
if(data.error){ if(data.error){
alert(data.error); alert(data.error);
} }
@ -435,7 +435,7 @@ function init() {
$('.listen-control-button').click(function() { $('.listen-control-button').click(function() {
if (stream_window == null || stream_window.closed) if (stream_window == null || stream_window.closed)
stream_window=window.open(baseUrl+"Dashboard/stream-player", 'name', 'width=400,height=158'); stream_window=window.open(baseUrl+"/Dashboard/stream-player", 'name', 'width=400,height=158');
stream_window.focus(); stream_window.focus();
return false; return false;
}); });

View file

@ -310,7 +310,7 @@ var AIRTIME = (function(AIRTIME) {
mod.fnDeleteItems = function(aMedia) { mod.fnDeleteItems = function(aMedia) {
$.post("/library/delete", $.post(baseUrl+"/library/delete",
{"format": "json", "media": aMedia}, {"format": "json", "media": aMedia},
function(json){ function(json){
if (json.message !== undefined) { if (json.message !== undefined) {
@ -480,7 +480,7 @@ var AIRTIME = (function(AIRTIME) {
"fnStateSave": function (oSettings, oData) { "fnStateSave": function (oSettings, oData) {
localStorage.setItem('datatables-library', JSON.stringify(oData)); localStorage.setItem('datatables-library', JSON.stringify(oData));
$.ajax({ $.ajax({
url: "/usersettings/set-library-datatable", url: baseUrl+"/usersettings/set-library-datatable",
type: "POST", type: "POST",
data: {settings : oData, format: "json"}, data: {settings : oData, format: "json"},
dataType: "json" dataType: "json"
@ -521,7 +521,7 @@ var AIRTIME = (function(AIRTIME) {
oData.iCreate = parseInt(oData.iCreate, 10); oData.iCreate = parseInt(oData.iCreate, 10);
}, },
"sAjaxSource": "/Library/contents-feed", "sAjaxSource": baseUrl+"/Library/contents-feed",
"sAjaxDataProp": "files", "sAjaxDataProp": "files",
"fnServerData": function ( sSource, aoData, fnCallback ) { "fnServerData": function ( sSource, aoData, fnCallback ) {
@ -616,7 +616,7 @@ var AIRTIME = (function(AIRTIME) {
text: aData.track_title text: aData.track_title
}, },
ajax: { ajax: {
url: "/Library/get-file-metadata", url: baseUrl+"/Library/get-file-meta-data",
type: "get", type: "get",
data: ({format: "html", id : aData.id, type: aData.ftype}), data: ({format: "html", id : aData.id, type: aData.ftype}),
success: function(data, status) { success: function(data, status) {
@ -802,13 +802,13 @@ var AIRTIME = (function(AIRTIME) {
}; };
} else if (data.ftype === "playlist" || data.ftype === "block") { } else if (data.ftype === "playlist" || data.ftype === "block") {
callback = function() { callback = function() {
var url = '/Playlist/edit'; var url = baseUrl+'/Playlist/edit';
AIRTIME.playlist.fnEdit(data.id, data.ftype, url); AIRTIME.playlist.fnEdit(data.id, data.ftype, url);
AIRTIME.playlist.validatePlaylistElements(); AIRTIME.playlist.validatePlaylistElements();
}; };
} else if (data.ftype === "stream") { } else if (data.ftype === "stream") {
callback = function() { callback = function() {
var url = '/Webstream/edit'; var url = baseUrl+'/Webstream/edit';
AIRTIME.playlist.fnEdit(data.id, data.ftype, url); AIRTIME.playlist.fnEdit(data.id, data.ftype, url);
} }
} else { } else {
@ -920,7 +920,7 @@ var AIRTIME = (function(AIRTIME) {
} }
request = $.ajax({ request = $.ajax({
url: "/library/context-menu", url: baseUrl+"/library/context-menu",
type: "GET", type: "GET",
data: {id : data.id, type: data.ftype, format: "json", "screen": screen}, data: {id : data.id, type: data.ftype, format: "json", "screen": screen},
dataType: "json", dataType: "json",
@ -943,7 +943,7 @@ var AIRTIME = (function(AIRTIME) {
}(AIRTIME || {})); }(AIRTIME || {}));
function checkImportStatus() { function checkImportStatus() {
$.getJSON('/Preference/is-import-in-progress', function(data){ $.getJSON(baseUrl+'/Preference/is-import-in-progress', function(data){
var div = $('#import_status'); var div = $('#import_status');
var table = $('#library_display').dataTable(); var table = $('#library_display').dataTable();
if (data == true){ if (data == true){
@ -976,7 +976,7 @@ function addProgressIcon(id) {
function checkLibrarySCUploadStatus(){ function checkLibrarySCUploadStatus(){
var url = '/Library/get-upload-to-soundcloud-status', var url = baseUrl+'/Library/get-upload-to-soundcloud-status',
span, span,
id; id;
@ -1032,7 +1032,7 @@ function addQtipToSCIcons(){
content: { content: {
text: "Retrieving data from the server...", text: "Retrieving data from the server...",
ajax: { ajax: {
url: "/Library/get-upload-to-soundcloud-status", url: baseUrl+"/Library/get-upload-to-soundcloud-status",
type: "post", type: "post",
data: ({format: "json", id : id, type: "file"}), data: ({format: "json", id : id, type: "file"}),
success: function(json, status){ success: function(json, status){
@ -1059,7 +1059,7 @@ function addQtipToSCIcons(){
content: { content: {
text: "Retreiving data from the server...", text: "Retreiving data from the server...",
ajax: { ajax: {
url: "/Library/get-upload-to-soundcloud-status", url: baseUrl+"/Library/get-upload-to-soundcloud-status",
type: "post", type: "post",
data: ({format: "json", id : id, type: "file"}), data: ({format: "json", id : id, type: "file"}),
success: function(json, status){ success: function(json, status){

View file

@ -1,10 +1,11 @@
$(document).ready(function() { $(document).ready(function() {
var uploader; var uploader;
$("#plupload_files").pluploadQueue({ $("#plupload_files").pluploadQueue({
// General settings // General settings
runtimes : 'gears, html5, html4', runtimes : 'gears, html5, html4',
url : '/Plupload/upload/format/json', url : baseUrl+'/Plupload/upload/format/json',
chunk_size : '5mb', chunk_size : '5mb',
unique_names : 'true', unique_names : 'true',
multiple_queues : 'true', multiple_queues : 'true',
@ -27,9 +28,9 @@ $(document).ready(function() {
$("#plupload_error table").css("display", "inline-table"); $("#plupload_error table").css("display", "inline-table");
}else{ }else{
var tempFileName = j.tempfilepath; var tempFileName = j.tempfilepath;
$.get('/Plupload/copyfile/format/json/name/' + $.get(baseUrl+'/Plupload/copyfile/format/json/name/'+
encodeURIComponent(file.name)+'/tempname/' + encodeURIComponent(file.name)+'/tempname/' +
encodeURIComponent(tempFileName), function(json){ encodeURIComponent(tempFileName), function(json){
var jr = jQuery.parseJSON(json); var jr = jQuery.parseJSON(json);
if(jr.error !== undefined) { if(jr.error !== undefined) {
var row = $("<tr/>") var row = $("<tr/>")

View file

@ -66,121 +66,121 @@ var AIRTIME = (function(AIRTIME){
event.stopPropagation(); event.stopPropagation();
var span = $(this), var span = $(this),
id = span.parent().attr("id").split("_").pop(), id = span.parent().attr("id").split("_").pop(),
url = "/Playlist/set-cue", url = baseUrl+"/Playlist/set-cue",
cueIn = $.trim(span.text()), cueIn = $.trim(span.text()),
li = span.parents("li"), li = span.parents("li"),
unqid = li.attr("unqid"), unqid = li.attr("unqid"),
lastMod = getModified(), lastMod = getModified(),
type = $('#obj_type').val(); type = $('#obj_type').val();
if (!isTimeValid(cueIn)){ if (!isTimeValid(cueIn)){
showError(span, "please put in a time '00:00:00 (.0)'"); showError(span, "please put in a time '00:00:00 (.0)'");
return; return;
} }
$.post(url, $.post(url,
{format: "json", cueIn: cueIn, id: id, modified: lastMod, type: type}, {format: "json", cueIn: cueIn, id: id, modified: lastMod, type: type},
function(json){ function(json){
if (json.error !== undefined){ if (json.error !== undefined){
playlistError(json); playlistError(json);
return; return;
} }
if (json.cue_error !== undefined) { if (json.cue_error !== undefined) {
showError(span, json.cue_error); showError(span, json.cue_error);
return; return;
} }
setPlaylistContent(json); setPlaylistContent(json);
li = $('#side_playlist li[unqid='+unqid+']'); li = $('#side_playlist li[unqid='+unqid+']');
li.find(".cue-edit").toggle(); li.find(".cue-edit").toggle();
highlightActive(li); highlightActive(li);
highlightActive(li.find('.spl_cue')); highlightActive(li.find('.spl_cue'));
}); });
} }
function changeCueOut(event) { function changeCueOut(event) {
event.stopPropagation(); event.stopPropagation();
var span = $(this), var span = $(this),
id = span.parent().attr("id").split("_").pop(), id = span.parent().attr("id").split("_").pop(),
url = "/Playlist/set-cue", url = baseUrl+"/Playlist/set-cue",
cueOut = $.trim(span.text()), cueOut = $.trim(span.text()),
li = span.parents("li"), li = span.parents("li"),
unqid = li.attr("unqid"), unqid = li.attr("unqid"),
lastMod = getModified(), lastMod = getModified(),
type = $('#obj_type').val(); type = $('#obj_type').val();
if (!isTimeValid(cueOut)){ if (!isTimeValid(cueOut)){
showError(span, "please put in a time '00:00:00 (.0)'"); showError(span, "please put in a time '00:00:00 (.0)'");
return; return;
} }
$.post(url,
{format: "json", cueOut: cueOut, id: id, modified: lastMod, type: type},
function(json){
$.post(url, if (json.error !== undefined){
{format: "json", cueOut: cueOut, id: id, modified: lastMod, type: type}, playlistError(json);
function(json){ return;
}
if (json.error !== undefined){ if (json.cue_error !== undefined) {
playlistError(json); showError(span, json.cue_error);
return; return;
} }
if (json.cue_error !== undefined) {
showError(span, json.cue_error);
return;
}
setPlaylistContent(json);
li = $('#side_playlist li[unqid='+unqid+']');
li.find(".cue-edit").toggle();
highlightActive(li);
highlightActive(li.find('.spl_cue'));
});
}
function changeFadeIn(event) { setPlaylistContent(json);
event.preventDefault();
var span = $(this), li = $('#side_playlist li[unqid='+unqid+']');
id = span.parent().attr("id").split("_").pop(), li.find(".cue-edit").toggle();
url = "/Playlist/set-fade", highlightActive(li);
fadeIn = $.trim(span.text()), highlightActive(li.find('.spl_cue'));
li = span.parents("li"), });
unqid = li.attr("unqid"), }
lastMod = getModified(),
function changeFadeIn(event) {
event.preventDefault();
var span = $(this),
id = span.parent().attr("id").split("_").pop(),
url = baseUrl+"/Playlist/set-fade",
fadeIn = $.trim(span.text()),
li = span.parents("li"),
unqid = li.attr("unqid"),
lastMod = getModified(),
type = $('#obj_type').val(); type = $('#obj_type').val();
if (!isFadeValid(fadeIn)){ if (!isFadeValid(fadeIn)){
showError(span, "please put in a time in seconds '00 (.0)'"); showError(span, "please put in a time in seconds '00 (.0)'");
return; return;
} }
$.post(url, $.post(url,
{format: "json", fadeIn: fadeIn, id: id, modified: lastMod, type: type}, {format: "json", fadeIn: fadeIn, id: id, modified: lastMod, type: type},
function(json){ function(json){
if (json.error !== undefined){ if (json.error !== undefined){
playlistError(json); playlistError(json);
return; return;
} }
if (json.fade_error !== undefined) { if (json.fade_error !== undefined) {
showError(span, json.fade_error); showError(span, json.fade_error);
return; return;
} }
setPlaylistContent(json); setPlaylistContent(json);
li = $('#side_playlist li[unqid='+unqid+']'); li = $('#side_playlist li[unqid='+unqid+']');
li.find('.crossfade').toggle(); li.find('.crossfade').toggle();
highlightActive(li.find('.spl_fade_control')); highlightActive(li.find('.spl_fade_control'));
}); });
} }
function changeFadeOut(event) { function changeFadeOut(event) {
event.stopPropagation(); event.stopPropagation();
var span = $(this), var span = $(this),
id = span.parent().attr("id").split("_").pop(), id = span.parent().attr("id").split("_").pop(),
url = "/Playlist/set-fade", url = baseUrl+"/Playlist/set-fade",
fadeOut = $.trim(span.text()), fadeOut = $.trim(span.text()),
li = span.parents("li"), li = span.parents("li"),
unqid = li.attr("unqid"), unqid = li.attr("unqid"),
@ -264,7 +264,8 @@ var AIRTIME = (function(AIRTIME){
nameElement.text(nameElement.text().replace("\n", "")); nameElement.text(nameElement.text().replace("\n", ""));
/* --until we decide whether Playlist name should autosave or not /* --until we decide whether Playlist name should autosave or not
url = '/Playlist/set-playlist-name';
url = baseUrl+'/Playlist/set-playlist-name';
$.post(url, $.post(url,
{format: "json", name: nameElement.text(), modified: lastMod, type: type}, {format: "json", name: nameElement.text(), modified: lastMod, type: type},
@ -526,9 +527,9 @@ var AIRTIME = (function(AIRTIME){
else { else {
$(this).addClass("ui-state-active"); $(this).addClass("ui-state-active");
var url = '/Playlist/get-playlist-fades'; var url = baseUrl+'/Playlist/get-playlist-fades';
$.post(url, $.post(url,
{format: "json", modified: lastMod, type: type}, {format: "json", modified: lastMod, type: type},
function(json){ function(json){
if (json.error !== undefined){ if (json.error !== undefined){
playlistError(json); playlistError(json);
@ -563,7 +564,7 @@ var AIRTIME = (function(AIRTIME){
$pl.on("blur", "span.spl_main_fade_in", function(event){ $pl.on("blur", "span.spl_main_fade_in", function(event){
event.stopPropagation(); event.stopPropagation();
var url = "/Playlist/set-playlist-fades", var url = baseUrl+"/Playlist/set-playlist-fades",
span = $(this), span = $(this),
fadeIn = $.trim(span.text()), fadeIn = $.trim(span.text()),
lastMod = getModified(), lastMod = getModified(),
@ -587,7 +588,7 @@ var AIRTIME = (function(AIRTIME){
$pl.on("blur", "span.spl_main_fade_out", function(event){ $pl.on("blur", "span.spl_main_fade_out", function(event){
event.stopPropagation(); event.stopPropagation();
var url = "/Playlist/set-playlist-fades", var url = baseUrl+"/Playlist/set-playlist-fades",
span = $(this), span = $(this),
fadeOut = $.trim(span.text()), fadeOut = $.trim(span.text()),
lastMod = getModified(), lastMod = getModified(),
@ -648,7 +649,7 @@ var AIRTIME = (function(AIRTIME){
//hide any previous errors (if any) //hide any previous errors (if any)
$("#side_playlist .errors").empty().hide(); $("#side_playlist .errors").empty().hide();
var url = 'Webstream/save'; var url = baseUrl+'/Webstream/save';
$.post(url, $.post(url,
{format: "json", id:id, description: description, url:streamurl, length: length, name: name}, {format: "json", id:id, description: description, url:streamurl, length: length, name: name},
function(json){ function(json){
@ -693,7 +694,7 @@ var AIRTIME = (function(AIRTIME){
var criteria = $('form').serializeArray(), var criteria = $('form').serializeArray(),
block_name = $('#playlist_name_display').text(), block_name = $('#playlist_name_display').text(),
block_desc = $('textarea[name="description"]').val(), block_desc = $('textarea[name="description"]').val(),
save_action = 'Playlist/save', save_action = baseUrl+'/Playlist/save',
obj_id = $('input[id="obj_id"]').val(), obj_id = $('input[id="obj_id"]').val(),
obj_type = $('#obj_type').val(), obj_type = $('#obj_type').val(),
lastMod = getModified(), lastMod = getModified(),
@ -818,7 +819,7 @@ var AIRTIME = (function(AIRTIME){
} }
mod.fnNew = function() { mod.fnNew = function() {
var url = '/Playlist/new'; var url = baseUrl+'/Playlist/new';
stopAudioPreview(); stopAudioPreview();
@ -831,7 +832,7 @@ var AIRTIME = (function(AIRTIME){
}; };
mod.fnWsNew = function() { mod.fnWsNew = function() {
var url = '/Webstream/new'; var url = baseUrl+'/Webstream/new';
stopAudioPreview(); stopAudioPreview();
@ -843,8 +844,9 @@ var AIRTIME = (function(AIRTIME){
}); });
}; };
mod.fnNewBlock = function() { mod.fnNewBlock = function() {
var url = '/Playlist/new'; var url = baseUrl+'/Playlist/new';
stopAudioPreview(); stopAudioPreview();
@ -875,7 +877,7 @@ var AIRTIME = (function(AIRTIME){
id = (plid === undefined) ? getId() : plid; id = (plid === undefined) ? getId() : plid;
lastMod = getModified(); lastMod = getModified();
type = $('#obj_type').val(); type = $('#obj_type').val();
url = '/Playlist/delete'; url = baseUrl+'/Playlist/delete';
$.post(url, $.post(url,
{format: "json", ids: id, modified: lastMod, type: type}, {format: "json", ids: id, modified: lastMod, type: type},
@ -892,7 +894,7 @@ var AIRTIME = (function(AIRTIME){
id = (wsid === undefined) ? getId() : wsid; id = (wsid === undefined) ? getId() : wsid;
lastMod = getModified(); lastMod = getModified();
type = $('#obj_type').val(); type = $('#obj_type').val();
url = '/Webstream/delete'; url = baseUrl+'/Webstream/delete';
$.post(url, $.post(url,
{format: "json", ids: id, modified: lastMod, type: type}, {format: "json", ids: id, modified: lastMod, type: type},
@ -965,20 +967,20 @@ var AIRTIME = (function(AIRTIME){
} }
mod.fnAddItems = function(aItems, iAfter, sAddType) { mod.fnAddItems = function(aItems, iAfter, sAddType) {
var sUrl = "/playlist/add-items"; var sUrl = baseUrl+"/playlist/add-items";
oData = {"aItems": aItems, "afterItem": iAfter, "type": sAddType}; oData = {"aItems": aItems, "afterItem": iAfter, "type": sAddType};
playlistRequest(sUrl, oData); playlistRequest(sUrl, oData);
}; };
mod.fnMoveItems = function(aIds, iAfter) { mod.fnMoveItems = function(aIds, iAfter) {
var sUrl = "/playlist/move-items", var sUrl = baseUrl+"/playlist/move-items",
oData = {"ids": aIds, "afterItem": iAfter}; oData = {"ids": aIds, "afterItem": iAfter};
playlistRequest(sUrl, oData); playlistRequest(sUrl, oData);
}; };
mod.fnDeleteItems = function(aItems) { mod.fnDeleteItems = function(aItems) {
var sUrl = "/playlist/delete-items", var sUrl = baseUrl+"/playlist/delete-items",
oData = {"ids": aItems}; oData = {"ids": aItems};
playlistRequest(sUrl, oData); playlistRequest(sUrl, oData);

View file

@ -1,7 +1,7 @@
$(document).ready(function(){ $(document).ready(function(){
function doNotShowPopup(){ function doNotShowPopup(){
$.get("/Usersettings/donotshowregistrationpopup", {format:"json"}); $.get(baseUrl+"/Usersettings/donotshowregistrationpopup", {format:"json"});
} }
var dialog = $("#register_popup"); var dialog = $("#register_popup");
@ -19,7 +19,7 @@ $(document).ready(function(){
text: "Remind me in 1 week", text: "Remind me in 1 week",
"class": "btn", "class": "btn",
click: function() { click: function() {
var url = '/Usersettings/remindme'; var url = baseUrl+'/Usersettings/remindme';
$.ajax({ $.ajax({
url: url, url: url,
data: {format:"json"} data: {format:"json"}
@ -32,7 +32,7 @@ $(document).ready(function(){
text: "Remind me never", text: "Remind me never",
"class": "btn", "class": "btn",
click: function() { click: function() {
var url ='/Usersettings/remindme-never'; var url =baseUrl+'/Usersettings/remindme-never';
$.ajax({ $.ajax({
url: url, url: url,
data: {format:"json"} data: {format:"json"}

View file

@ -519,12 +519,6 @@ function callback(data, type) {
setTimeout(removeSuccessMsg, 5000); setTimeout(removeSuccessMsg, 5000);
} }
function removeSuccessMsg() {
var $status = $('.success');
$status.fadeOut("slow", function(){$status.empty()});
}
function appendAddButton() { function appendAddButton() {
var add_button = "<a class='btn btn-small' id='criteria_add'>" + var add_button = "<a class='btn btn-small' id='criteria_add'>" +
"<i class='icon-white icon-plus'></i></a>"; "<i class='icon-white icon-plus'></i></a>";

View file

@ -75,7 +75,7 @@ var AIRTIME = (function(AIRTIME) {
"bProcessing": true, "bProcessing": true,
"bServerSide": true, "bServerSide": true,
"sAjaxSource": "/Playouthistory/playout-history-feed", "sAjaxSource": baseUrl+"/Playouthistory/playout-history-feed",
"sAjaxDataProp": "history", "sAjaxDataProp": "history",
"fnServerData": fnServerData, "fnServerData": fnServerData,
@ -94,7 +94,7 @@ var AIRTIME = (function(AIRTIME) {
"sDom": 'lf<"dt-process-rel"r><"H"T><"dataTables_scrolling"t><"F"ip>', "sDom": 'lf<"dt-process-rel"r><"H"T><"dataTables_scrolling"t><"F"ip>',
"oTableTools": { "oTableTools": {
"sSwfPath": "/js/datatables/plugin/TableTools/swf/copy_cvs_xls_pdf.swf", "sSwfPath": baseUrl+"/js/datatables/plugin/TableTools/swf/copy_cvs_xls_pdf.swf",
"aButtons": [ "aButtons": [
"copy", "copy",
{ {
@ -183,4 +183,4 @@ $(document).ready(function(){
oTable.fnDraw(); oTable.fnDraw();
}); });
}); });

View file

@ -13,8 +13,8 @@ function setWatchedDirEvents() {
//knownPaths: [{text:'Desktop', image:'desktop.png', path:'/home'}], //knownPaths: [{text:'Desktop', image:'desktop.png', path:'/home'}],
knownPaths: [], knownPaths: [],
imageUrl: 'img/icons/', imageUrl: 'img/icons/',
systemImageUrl: '/css/img/', systemImageUrl: baseUrl+'/css/img/',
handlerUrl: '/Preference/server-browse/format/json', handlerUrl: baseUrl+'/Preference/server-browse/format/json',
title: 'Choose Storage Folder', title: 'Choose Storage Folder',
basePath: '', basePath: '',
requestMethod: 'POST', requestMethod: 'POST',
@ -33,8 +33,8 @@ function setWatchedDirEvents() {
//knownPaths: [{text:'Desktop', image:'desktop.png', path:'/home'}], //knownPaths: [{text:'Desktop', image:'desktop.png', path:'/home'}],
knownPaths: [], knownPaths: [],
imageUrl: 'img/icons/', imageUrl: 'img/icons/',
systemImageUrl: '/css/img/', systemImageUrl: baseUrl+'/css/img/',
handlerUrl: '/Preference/server-browse/format/json', handlerUrl: baseUrl+'/Preference/server-browse/format/json',
title: 'Choose Folder to Watch', title: 'Choose Folder to Watch',
basePath: '', basePath: '',
requestMethod: 'POST', requestMethod: 'POST',
@ -44,7 +44,7 @@ function setWatchedDirEvents() {
var url, chosen; var url, chosen;
if(confirm("Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!")){ if(confirm("Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!")){
url = "/Preference/change-stor-directory"; url = baseUrl+"/Preference/change-stor-directory";
chosen = $('#storageFolder').val(); chosen = $('#storageFolder').val();
$.post(url, $.post(url,
@ -64,7 +64,7 @@ function setWatchedDirEvents() {
$('#watchedFolder-ok').click(function(){ $('#watchedFolder-ok').click(function(){
var url, chosen; var url, chosen;
url = "/Preference/reload-watch-directory"; url = baseUrl+"/Preference/reload-watch-directory";
chosen = $('#watchedFolder').val(); chosen = $('#watchedFolder').val();
$.post(url, $.post(url,
@ -80,7 +80,7 @@ function setWatchedDirEvents() {
$('.selected-item').find('.ui-icon-refresh').click(function(){ $('.selected-item').find('.ui-icon-refresh').click(function(){
var folder = $(this).prev().text(); var folder = $(this).prev().text();
$.get("/Preference/rescan-watch-directory", {format: "json", dir: folder}); $.get(baseUrl+"/Preference/rescan-watch-directory", {format: "json", dir: folder});
}); });
$('.selected-item').find('.ui-icon-close').click(function(){ $('.selected-item').find('.ui-icon-close').click(function(){
@ -88,7 +88,7 @@ function setWatchedDirEvents() {
var row = $(this).parent(); var row = $(this).parent();
var folder = row.find('#folderPath').text(); var folder = row.find('#folderPath').text();
url = "/Preference/remove-watch-directory"; url = baseUrl+"/Preference/remove-watch-directory";
$.post(url, $.post(url,
{format: "json", dir: folder}, {format: "json", dir: folder},

View file

@ -88,6 +88,17 @@ $(document).ready(function() {
$(this).toggleClass("closed"); $(this).toggleClass("closed");
return false; return false;
}).next().hide(); }).next().hide();
$('#pref_save').live('click', function() {
var data = $('#pref_form').serialize();
var url = baseUrl+'/Preference/index';
$.post(url, {format: "json", data: data}, function(data){
var json = $.parseJSON(data);
$('#content').empty().append(json.html);
setTimeout(removeSuccessMsg, 5000);
});
});
showErrorSections(); showErrorSections();

View file

@ -75,7 +75,7 @@ function showForIcecast(ele){
} }
function checkLiquidsoapStatus(){ function checkLiquidsoapStatus(){
var url = '/Preference/get-liquidsoap-status/format/json'; var url = baseUrl+'/Preference/get-liquidsoap-status/format/json';
var id = $(this).attr("id"); var id = $(this).attr("id");
$.post(url, function(json){ $.post(url, function(json){
var json_obj = jQuery.parseJSON(json); var json_obj = jQuery.parseJSON(json);
@ -127,7 +127,7 @@ function setLiveSourceConnectionOverrideListener(){
live_dj_input.val(url) live_dj_input.val(url)
live_dj_input.attr("readonly", "readonly") live_dj_input.attr("readonly", "readonly")
live_dj_actions.hide() live_dj_actions.hide()
$.get("/Preference/set-source-connection-url/", {format: "json", type: "livedj", url:encodeURIComponent(url), override: 1}); $.get(baseUrl+"/Preference/set-source-connection-url/", {format: "json", type: "livedj", url:encodeURIComponent(url), override: 1});
event.preventDefault() event.preventDefault()
}) })
@ -142,7 +142,7 @@ function setLiveSourceConnectionOverrideListener(){
live_dj_input.val(url) live_dj_input.val(url)
live_dj_input.attr("readonly", "readonly") live_dj_input.attr("readonly", "readonly")
live_dj_actions.hide() live_dj_actions.hide()
$.get("/Preference/set-source-connection-url", {format: "json", type: "livedj", url:encodeURIComponent(url), override: 0}); $.get(baseUrl+"/Preference/set-source-connection-url", {format: "json", type: "livedj", url:encodeURIComponent(url), override: 0});
event.preventDefault() event.preventDefault()
}) })
@ -151,7 +151,7 @@ function setLiveSourceConnectionOverrideListener(){
master_dj_input.val(url) master_dj_input.val(url)
master_dj_input.attr("readonly", "readonly") master_dj_input.attr("readonly", "readonly")
master_dj_actions.hide() master_dj_actions.hide()
$.get("/Preference/set-source-connection-url", {format: "json", type: "masterdj", url:encodeURIComponent(url), override: 1}) $.get(baseUrl+"/Preference/set-source-connection-url", {format: "json", type: "masterdj", url:encodeURIComponent(url), override: 1})
event.preventDefault() event.preventDefault()
}) })
@ -165,7 +165,7 @@ function setLiveSourceConnectionOverrideListener(){
master_dj_input.val(url) master_dj_input.val(url)
master_dj_input.attr("readonly", "readonly") master_dj_input.attr("readonly", "readonly")
master_dj_actions.hide() master_dj_actions.hide()
$.get("/Preference/set-source-connection-url", {format: "json", type: "masterdj", url:encodeURIComponent(url), override: 0}) $.get(baseUrl+"/Preference/set-source-connection-url", {format: "json", type: "masterdj", url:encodeURIComponent(url), override: 0})
event.preventDefault() event.preventDefault()
}) })
} }
@ -373,4 +373,22 @@ $(document).ready(function() {
at: "right center" at: "right center"
}, },
}) })
$('#stream_save').live('click', function(){
var confirm_pypo_restart_text = "If you change the username or password values for an enabled stream the "
+ "playout engine will be rebooted and your listeners will hear silence for"
+ "5-10 seconds. Changing the following fields will NOT cause a reboot: "
+ "Stream Label (Global Settings), and Switch Transition Fade(s), Master "
+ "Username, and Master Password (Input Stream Settings). If Airtime is recording"
+ ", and if the change causes a playout engine restart, the recording will be interrupted.";
if (confirm(confirm_pypo_restart_text)) {
var data = $('#stream_form').serialize();
var url = baseUrl+'/Preference/stream-setting';
$.post(url, {format:"json", data: data}, function(data){
var json = $.parseJSON(data);
$('#content').empty().append(json.html);
});
}
});
}); });

View file

@ -47,7 +47,7 @@ function autoSelect(event, ui) {
function findHosts(request, callback) { function findHosts(request, callback) {
var search, url; var search, url;
url = "/User/get-hosts"; url = baseUrl+"/User/get-hosts";
search = request.term; search = request.term;
var noResult = new Array(); var noResult = new Array();
@ -397,7 +397,7 @@ function setAddShowEvents() {
.fullCalendar('render'); .fullCalendar('render');
$("#add-show-form").hide(); $("#add-show-form").hide();
$.get("/Schedule/get-form", {format:"json"}, function(json){ $.get(baseUrl+"/Schedule/get-form", {format:"json"}, function(json){
$("#add-show-form") $("#add-show-form")
.empty() .empty()
.append(json.form); .append(json.form);
@ -443,7 +443,7 @@ function setAddShowEvents() {
applyPlatformOpacityRules: false applyPlatformOpacityRules: false
}); });
var action = "/Schedule/"+String(addShowButton.attr("data-action")); var action = baseUrl+"/Schedule/"+String(addShowButton.attr("data-action"));
$.post(action, {format: "json", data: data, hosts: hosts, days: days}, function(json){ $.post(action, {format: "json", data: data, hosts: hosts, days: days}, function(json){
//addShowButton.removeClass("disabled"); //addShowButton.removeClass("disabled");
@ -463,7 +463,7 @@ function setAddShowEvents() {
.fullCalendar('render'); .fullCalendar('render');
$("#add-show-form").hide(); $("#add-show-form").hide();
$.get("/Schedule/get-form", {format:"json"}, function(json){ $.get(baseUrl+"/Schedule/get-form", {format:"json"}, function(json){
$("#add-show-form") $("#add-show-form")
.empty() .empty()
.append(json.form); .append(json.form);
@ -579,7 +579,7 @@ function setAddShowEvents() {
var loadingIcon = $('#icon-loader-small'); var loadingIcon = $('#icon-loader-small');
loadingIcon.show(); loadingIcon.show();
$.post("/Schedule/calculate-duration", {startTime: startDateTime, endTime: endDateTime}, function(data){ $.post(baseUrl+"/Schedule/calculate-duration", {startTime: startDateTime, endTime: endDateTime}, function(data){
$('#add_show_duration').val(JSON.parse(data)); $('#add_show_duration').val(JSON.parse(data));
loadingIcon.hide(); loadingIcon.hide();
}); });

View file

@ -176,7 +176,7 @@ function viewDisplay( view ) {
.fullCalendar( 'gotoDate', date ); .fullCalendar( 'gotoDate', date );
//save slotMin value to db //save slotMin value to db
var url = '/Schedule/set-time-interval/format/json'; var url = baseUrl+'/Schedule/set-time-interval/format/json';
$.post(url, {timeInterval: slotMin}); $.post(url, {timeInterval: slotMin});
}); });
@ -201,7 +201,7 @@ function viewDisplay( view ) {
} }
//save view name to db //save view name to db
var url = '/Schedule/set-time-scale/format/json'; var url = baseUrl+'/Schedule/set-time-scale/format/json';
$.post(url, {timeScale: view.name}); $.post(url, {timeScale: view.name});
} }
@ -305,9 +305,7 @@ function eventAfterRender( event, element, view ) {
} }
function eventDrop(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) { function eventDrop(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
var url; var url = baseUrl+'/Schedule/move-show/format/json';
url = '/Schedule/move-show/format/json';
$.post(url, $.post(url,
{day: dayDelta, min: minuteDelta, showInstanceId: event.id}, {day: dayDelta, min: minuteDelta, showInstanceId: event.id},
@ -323,9 +321,7 @@ function eventDrop(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui
} }
function eventResize( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) { function eventResize( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) {
var url; var url = baseUrl+'/Schedule/resize-show/format/json';
url = '/Schedule/resize-show/format/json';
$.post(url, $.post(url,
{day: dayDelta, min: minuteDelta, showId: event.showId}, {day: dayDelta, min: minuteDelta, showId: event.showId},
@ -348,7 +344,7 @@ function getFullCalendarEvents(start, end, callback) {
start_date = makeTimeStamp(start); start_date = makeTimeStamp(start);
end_date = makeTimeStamp(end); end_date = makeTimeStamp(end);
url = '/Schedule/event-feed'; url = baseUrl+'/Schedule/event-feed';
var d = new Date(); var d = new Date();
@ -358,7 +354,7 @@ function getFullCalendarEvents(start, end, callback) {
} }
function checkSCUploadStatus(){ function checkSCUploadStatus(){
var url = '/Library/get-upload-to-soundcloud-status/format/json'; var url = baseUrl+'/Library/get-upload-to-soundcloud-status/format/json';
$("span[class*=progress]").each(function(){ $("span[class*=progress]").each(function(){
var id = $(this).attr("id"); var id = $(this).attr("id");
$.post(url, {format: "json", id: id, type:"show"}, function(json){ $.post(url, {format: "json", id: id, type:"show"}, function(json){
@ -374,7 +370,7 @@ function checkSCUploadStatus(){
* show icon * show icon
*/ */
function getCurrentShow(){ function getCurrentShow(){
var url = '/Schedule/get-current-show/format/json', var url = baseUrl+'/Schedule/get-current-show/format/json',
id, id,
$el; $el;
$.post(url, {format: "json"}, function(json) { $.post(url, {format: "json"}, function(json) {
@ -448,7 +444,7 @@ function addQtipToSCIcons(ele){
content: { content: {
text: "Retreiving data from the server...", text: "Retreiving data from the server...",
ajax: { ajax: {
url: "/Library/get-upload-to-soundcloud-status", url: baseUrl+"/Library/get-upload-to-soundcloud-status",
type: "post", type: "post",
data: ({format: "json", id : id, type: "file"}), data: ({format: "json", id : id, type: "file"}),
success: function(json, status){ success: function(json, status){
@ -474,7 +470,7 @@ function addQtipToSCIcons(ele){
content: { content: {
text: "Retreiving data from the server...", text: "Retreiving data from the server...",
ajax: { ajax: {
url: "/Library/get-upload-to-soundcloud-status", url: baseUrl+"/Library/get-upload-to-soundcloud-status",
type: "post", type: "post",
data: ({format: "json", id : id, type: "show"}), data: ({format: "json", id : id, type: "show"}),
success: function(json, status){ success: function(json, status){

View file

@ -34,7 +34,7 @@ function checkShowLength(json) {
function confirmCancelShow(show_instance_id){ function confirmCancelShow(show_instance_id){
if (confirm('Cancel Current Show?')) { if (confirm('Cancel Current Show?')) {
var url = "/Schedule/cancel-current-show"; var url = baseUrl+"/Schedule/cancel-current-show";
$.ajax({ $.ajax({
url: url, url: url,
data: {format: "json", id: show_instance_id}, data: {format: "json", id: show_instance_id},
@ -47,7 +47,7 @@ function confirmCancelShow(show_instance_id){
function confirmCancelRecordedShow(show_instance_id){ function confirmCancelRecordedShow(show_instance_id){
if (confirm('Stop recording current show?')) { if (confirm('Stop recording current show?')) {
var url = "/Schedule/cancel-current-show"; var url = baseUrl+"/Schedule/cancel-current-show";
$.ajax({ $.ajax({
url: url, url: url,
data: {format: "json", id: show_instance_id}, data: {format: "json", id: show_instance_id},
@ -60,7 +60,7 @@ function confirmCancelRecordedShow(show_instance_id){
function uploadToSoundCloud(show_instance_id){ function uploadToSoundCloud(show_instance_id){
var url = "/Schedule/upload-to-sound-cloud"; var url = baseUrl+"/Schedule/upload-to-sound-cloud";
var span = $(window.triggerElement).find(".recording"); var span = $(window.triggerElement).find(".recording");
$.post(url, $.post(url,
@ -80,8 +80,7 @@ function uploadToSoundCloud(show_instance_id){
} }
function checkCalendarSCUploadStatus(){ function checkCalendarSCUploadStatus(){
var url = baseUrl+'/Library/get-upload-to-soundcloud-status',
var url = '/Library/get-upload-to-soundcloud-status',
span, span,
id; id;
@ -289,7 +288,7 @@ function alertShowErrorAndReload(){
} }
$(document).ready(function() { $(document).ready(function() {
$.ajax({ url: "/Api/calendar-init/format/json", dataType:"json", success:createFullCalendar $.ajax({ url: baseUrl+"/Api/calendar-init/format/json", dataType:"json", success:createFullCalendar
, error:function(jqXHR, textStatus, errorThrown){}}); , error:function(jqXHR, textStatus, errorThrown){}});
setInterval(checkCalendarSCUploadStatus, 5000); setInterval(checkCalendarSCUploadStatus, 5000);
@ -459,7 +458,7 @@ $(document).ready(function() {
} }
$.ajax({ $.ajax({
url: "/schedule/make-context-menu", url: baseUrl+"/schedule/make-context-menu",
type: "GET", type: "GET",
data: {id : data.id, format: "json"}, data: {id : data.id, format: "json"},
dataType: "json", dataType: "json",

View file

@ -264,7 +264,7 @@ var AIRTIME = (function(AIRTIME){
mod.disableUI(); mod.disableUI();
$.post("/showbuilder/schedule-add", $.post(baseUrl+"/showbuilder/schedule-add",
{"format": "json", "mediaIds": aMediaIds, "schedIds": aSchedIds}, {"format": "json", "mediaIds": aMediaIds, "schedIds": aSchedIds},
mod.fnItemCallback mod.fnItemCallback
); );
@ -274,7 +274,7 @@ var AIRTIME = (function(AIRTIME){
mod.disableUI(); mod.disableUI();
$.post("/showbuilder/schedule-move", $.post(baseUrl+"/showbuilder/schedule-move",
{"format": "json", "selectedItem": aSelect, "afterItem": aAfter}, {"format": "json", "selectedItem": aSelect, "afterItem": aAfter},
mod.fnItemCallback mod.fnItemCallback
); );
@ -283,8 +283,8 @@ var AIRTIME = (function(AIRTIME){
mod.fnRemove = function(aItems) { mod.fnRemove = function(aItems) {
mod.disableUI(); mod.disableUI();
if (confirm("Remove selected scheduled item(s)?")) { if (confirm("Delete selected item(s)?")) {
$.post( "/showbuilder/schedule-remove", $.post( baseUrl+"/showbuilder/schedule-remove",
{"items": aItems, "format": "json"}, {"items": aItems, "format": "json"},
mod.fnItemCallback mod.fnItemCallback
); );
@ -392,7 +392,7 @@ var AIRTIME = (function(AIRTIME){
localStorage.setItem('datatables-timeline', JSON.stringify(oData)); localStorage.setItem('datatables-timeline', JSON.stringify(oData));
$.ajax({ $.ajax({
url: "/usersettings/set-timeline-datatable", url: baseUrl+"/usersettings/set-timeline-datatable",
type: "POST", type: "POST",
data: {settings : oData, format: "json"}, data: {settings : oData, format: "json"},
dataType: "json" dataType: "json"
@ -554,7 +554,7 @@ var AIRTIME = (function(AIRTIME){
if (!isAudioSupported(aData.mime)) { if (!isAudioSupported(aData.mime)) {
$image.html('<span class="ui-icon ui-icon-locked"></span>'); $image.html('<span class="ui-icon ui-icon-locked"></span>');
} else { } else {
$image.html('<img title="Track preview" src="/css/images/icon_audioclip.png"></img>') $image.html('<img title="Track preview" src="'+baseUrl+'/css/images/icon_audioclip.png"></img>')
.click(function() { .click(function() {
open_show_preview(aData.instance, aData.pos); open_show_preview(aData.instance, aData.pos);
return false; return false;
@ -791,7 +791,7 @@ var AIRTIME = (function(AIRTIME){
"sDom": 'R<"dt-process-rel"r><"sb-padded"<"H"C>><"dataTables_scrolling sb-padded"t>', "sDom": 'R<"dt-process-rel"r><"sb-padded"<"H"C>><"dataTables_scrolling sb-padded"t>',
"sAjaxDataProp": "schedule", "sAjaxDataProp": "schedule",
"sAjaxSource": "/showbuilder/builder-feed" "sAjaxSource": baseUrl+"/showbuilder/builder-feed"
}); });
$sbTable.find("tbody").on("click", "input:checkbox", function(ev) { $sbTable.find("tbody").on("click", "input:checkbox", function(ev) {
@ -1035,7 +1035,7 @@ var AIRTIME = (function(AIRTIME){
} }
if (confirm(msg)) { if (confirm(msg)) {
var url = "/Schedule/cancel-current-show"; var url = baseUrl+"/Schedule/cancel-current-show";
$.ajax({ $.ajax({
url: url, url: url,
data: {format: "json", id: data.instance}, data: {format: "json", id: data.instance},
@ -1217,7 +1217,7 @@ var AIRTIME = (function(AIRTIME){
} }
request = $.ajax({ request = $.ajax({
url: "/showbuilder/context-menu", url: baseUrl+"/showbuilder/context-menu",
type: "GET", type: "GET",
data: {id : data.id, format: "json"}, data: {id : data.id, format: "json"},
dataType: "json", dataType: "json",

View file

@ -287,6 +287,138 @@ AIRTIME = (function(AIRTIME) {
return AIRTIME; return AIRTIME;
$builder.on("click","#sb_edit", function (ev){
var schedTable = $("#show_builder_table").dataTable();
//reset timestamp to redraw the cursors.
AIRTIME.showbuilder.resetTimestamp();
$lib.show()
.width(Math.floor(screenWidth * 0.48));
$builder.width(Math.floor(screenWidth * 0.48))
.find("#sb_edit")
.remove()
.end()
.find("#sb_date_start")
.css("margin-left", 0)
.end();
schedTable.fnDraw();
$.ajax({
url: baseUrl+"/usersettings/set-now-playing-screen-settings",
type: "POST",
data: {settings : {library : true}, format: "json"},
dataType: "json",
success: function(){}
});
});
$lib.on("click", "#sb_lib_close", function() {
var schedTable = $("#show_builder_table").dataTable();
$lib.hide();
$builder.width(screenWidth)
.find(".sb-timerange")
.prepend($toggleLib)
.find("#sb_date_start")
.css("margin-left", 30)
.end()
.end();
$toggleLib.removeClass("ui-state-hover");
schedTable.fnDraw();
$.ajax({
url: baseUrl+"/usersettings/set-now-playing-screen-settings",
type: "POST",
data: {settings : {library : false}, format: "json"},
dataType: "json",
success: function(){}
});
});
$builder.find('legend').click(function(ev, item){
if ($fs.hasClass("closed")) {
$fs.removeClass("closed");
$builder.find('.dataTables_scrolling').css("max-height", widgetHeight - 150);
}
else {
$fs.addClass("closed");
//set defaults for the options.
$fs.find('select').val(0);
$fs.find('input[type="checkbox"]').attr("checked", false);
$builder.find('.dataTables_scrolling').css("max-height", widgetHeight - 110);
}
});
//set click event for all my shows checkbox.
$builder.on("click", "#sb_my_shows", function(ev) {
if ($(this).is(':checked')) {
$(ev.delegateTarget).find('#sb_show_filter').val(0);
}
showSearchSubmit();
});
//set select event for choosing a show.
$builder.on("change", '#sb_show_filter', function(ev) {
if ($(this).val() !== 0) {
$(ev.delegateTarget).find('#sb_my_shows').attr("checked", false);
}
showSearchSubmit();
});
function checkScheduleUpdates(){
var data = {},
oTable = $('#show_builder_table').dataTable(),
fn = oTable.fnSettings().fnServerData,
start = fn.start,
end = fn.end;
data["format"] = "json";
data["start"] = start;
data["end"] = end;
data["timestamp"] = AIRTIME.showbuilder.getTimestamp();
data["instances"] = AIRTIME.showbuilder.getShowInstances();
if (fn.hasOwnProperty("ops")) {
data["myShows"] = fn.ops.myShows;
data["showFilter"] = fn.ops.showFilter;
}
$.ajax( {
"dataType": "json",
"type": "GET",
"url": baseUrl+"/showbuilder/check-builder-feed",
"data": data,
"success": function(json) {
if (json.update === true) {
oTable.fnDraw();
}
}
} );
}
//check if the timeline view needs updating.
setInterval(checkScheduleUpdates, 5 * 1000); //need refresh in milliseconds
};
mod.onResize = function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(setWidgetSize, 100);
};
return AIRTIME;
} (AIRTIME || {})); } (AIRTIME || {}));
$(document).ready(AIRTIME.builderMain.onReady); $(document).ready(AIRTIME.builderMain.onReady);

View file

@ -69,7 +69,7 @@ function success(data, textStatus, jqXHR){
} }
function updateStatus(getDiskInfo){ function updateStatus(getDiskInfo){
$.getJSON( "api/status/format/json/diskinfo/"+getDiskInfo, null, success); $.getJSON( baseUrl+"/api/status/format/json/diskinfo/"+getDiskInfo, null, success);
} }

View file

@ -24,13 +24,13 @@ function populateForm(entries){
} }
function rowClickCallback(row_id){ function rowClickCallback(row_id){
$.ajax({ url: '/User/get-user-data/id/'+ row_id +'/format/json', dataType:"json", success:function(data){ $.ajax({ url: baseUrl+'/User/get-user-data/id/'+ row_id +'/format/json', dataType:"json", success:function(data){
populateForm(data.entries); populateForm(data.entries);
}}); }});
} }
function removeUserCallback(row_id, nRow){ function removeUserCallback(row_id, nRow){
$.ajax({ url: '/User/remove-user/id/'+ row_id +'/format/json', dataType:"text", success:function(data){ $.ajax({ url: baseUrl+'/User/remove-user/id/'+ row_id +'/format/json', dataType:"text", success:function(data){
var o = $('#users_datatable').dataTable().fnDeleteRow(nRow); var o = $('#users_datatable').dataTable().fnDeleteRow(nRow);
}}); }});
} }
@ -60,11 +60,11 @@ function rowCallback( nRow, aData, iDisplayIndex ){
return nRow; return nRow;
} }
$(document).ready(function() { function populateUserTable() {
$('#users_datatable').dataTable( { $('#users_datatable').dataTable( {
"bProcessing": true, "bProcessing": true,
"bServerSide": true, "bServerSide": true,
"sAjaxSource": "/User/get-user-data-table-info/format/json", "sAjaxSource": baseUrl+"/User/get-user-data-table-info/format/json",
"fnServerData": function ( sSource, aoData, fnCallback ) { "fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( { $.ajax( {
"dataType": 'json', "dataType": 'json',
@ -92,11 +92,32 @@ $(document).ready(function() {
"sDom": '<"H"lf<"dt-process-rel"r>>t<"F"ip>', "sDom": '<"H"lf<"dt-process-rel"r>>t<"F"ip>',
}); });
}
$(document).ready(function() {
populateUserTable();
//$('#user_details').hide(); //$('#user_details').hide();
var newUser = {login:"", first_name:"", last_name:"", type:"G", id:""}; var newUser = {login:"", first_name:"", last_name:"", type:"G", id:""};
$('#add_user_button').click(function(){populateForm(newUser)}); $('#add_user_button').live('click', function(){populateForm(newUser)});
$('#save_user').live('click', function(){
var data = $('#user_form').serialize();
var url = baseUrl+'/User/add-user';
$.post(url, {format: "json", data: data}, function(data){
var json = $.parseJSON(data);
if (json.valid === "true") {
$('#content').empty().append(json.html);
populateUserTable();
} else {
//if form is invalid we only need to redraw the form
$('#user_form').empty().append($(json.html).find('#user_form').children());
}
setTimeout(removeSuccessMsg, 5000);
});
});
}); });

View file

@ -17,8 +17,9 @@ version_url = 'version/api_key/%%api_key%%'
register_component = 'register-component/format/json/api_key/%%api_key%%/component/%%component%%' register_component = 'register-component/format/json/api_key/%%api_key%%/component/%%component%%'
# Hostname # Hostname
base_url = 'localhost' host = 'localhost'
base_port = 80 base_port = 80
base_dir = ''
############################# #############################
## Config for Media Monitor ## Config for Media Monitor

View file

@ -12,11 +12,8 @@ import urllib
import urllib2 import urllib2
import logging import logging
import json import json
from urlparse import urlparse
import base64 import base64
from configobj import ConfigObj from configobj import ConfigObj
import string
import traceback
AIRTIME_VERSION = "2.2.0" AIRTIME_VERSION = "2.2.0"
@ -44,6 +41,91 @@ def convert_dict_value_to_utf8(md):
# Airtime API Client # Airtime API Client
################################################################################ ################################################################################
class UrlException(Exception): pass
class IncompleteUrl(UrlException):
def __init__(self, url): self.url = url
def __str__(self): return "Incomplete url: '%s'" % self.url
class UrlBadParam(UrlException):
def __init__(self, url, param):
self.url = url
self.param = param
def __str__(self):
return "Bad param '%s' passed into url: '%s'" % (self.param, self.url)
class ApcUrl(object):
""" A safe abstraction and testable for filling in parameters in
api_client.cfg"""
def __init__(self, base_url): self.base_url = base_url
def params(self, **params):
temp_url = self.base_url
for k, v in params.iteritems():
wrapped_param = "%%" + k + "%%"
if wrapped_param in temp_url:
temp_url = temp_url.replace(wrapped_param, str(v))
else: raise UrlBadParam(self.base_url, k)
return ApcUrl(temp_url)
def url(self):
if '%%' in self.base_url: raise IncompleteUrl(self.base_url)
else: return self.base_url
class ApiRequest(object):
def __init__(self, name, url):
self.name = name
self.url = url
self.__req = None
def __call__(self,_post_data=None, **kwargs):
# TODO : get rid of god damn urllib and replace everything with
# grequests or requests at least
final_url = self.url.params(**kwargs).url()
if _post_data is not None: _post_data = urllib.urlencode(_post_data)
req = urllib2.Request(final_url, _post_data)
response = urllib2.urlopen(req).read()
# Ghetto hack for now because we don't the content type we are getting
# (Pointless to look at mime since it's not being set correctly always)
try: return json.loads(response)
except ValueError: return response
def req(self, *args, **kwargs):
self.__req = lambda : self(*args, **kwargs)
return self
def retry(self, n, delay=5):
"""Try to send request n times. If after n times it fails then
we finally raise exception"""
for i in range(0,n-1):
try: return self.__req()
except Exception: time.sleep(delay)
return self.__req()
class RequestProvider(object):
""" Creates the available ApiRequest instance that can be read from
a config file """
def __init__(self, cfg):
self.config = cfg
self.requests = {}
self.url = ApcUrl("http://%s:%s/%s/%s/%s" \
% (self.config["host"], str(self.config["base_port"]),
self.config["base_dir"], self.config["api_base"],
'%%action%%'))
# Now we must discover the possible actions
actions = dict( (k,v) for k,v in cfg.iteritems() if '%%api_key%%' in v)
for action_name, action_value in actions.iteritems():
new_url = self.url.params(action=action_value).params(
api_key=self.config['api_key'])
self.requests[action_name] = ApiRequest(action_name, new_url)
def available_requests(self) : return self.requests.keys()
def __contains__(self, request) : return request in self.requests
def __getattr__(self, attr):
if attr in self: return self.requests[attr]
else: return super(RequestProvider, self).__getattribute__(attr)
class AirtimeApiClient(object): class AirtimeApiClient(object):
# This is a little hacky fix so that I don't have to pass the config object # This is a little hacky fix so that I don't have to pass the config object
@ -64,129 +146,21 @@ class AirtimeApiClient(object):
config_path=AirtimeApiClient.default_config ) config_path=AirtimeApiClient.default_config )
def __init__(self, logger=None,config_path='/etc/airtime/api_client.cfg'): def __init__(self, logger=None,config_path='/etc/airtime/api_client.cfg'):
if logger is None: if logger is None: self.logger = logging
self.logger = logging else: self.logger = logger
else:
self.logger = logger
# loading config file # loading config file
try: try:
self.config = ConfigObj(config_path) self.config = ConfigObj(config_path)
self.services = RequestProvider(self.config)
except Exception, e: except Exception, e:
self.logger.error('Error loading config file: %s', e) self.logger.error('Error loading config file: %s', e)
sys.exit(1) sys.exit(1)
def get_response_from_server(self, url, attempts=-1):
logger = self.logger
successful_response = False
while not successful_response:
try:
response = urllib2.urlopen(url).read()
successful_response = True
except IOError, e:
logger.error('Error Authenticating with remote server: %s', e)
if isinstance(url, urllib2.Request):
logger.debug(url.get_full_url())
else:
logger.debug(url)
except Exception, e:
logger.error('Couldn\'t connect to remote server. Is it running?')
logger.error("%s" % e)
if isinstance(url, urllib2.Request):
logger.debug(url.get_full_url())
else:
logger.debug(url)
#If the user passed in a positive attempts number then that means
#attempts will roll over 0 and we stop. If attempts was initially negative,
#then we have unlimited attempts
if attempts > 0:
attempts = attempts - 1
if attempts == 0:
successful_response = True
if not successful_response:
logger.error("Error connecting to server, waiting 5 seconds and trying again.")
time.sleep(5)
return response
def get_response_into_file(self, url, block=True):
"""
This function will query the server and download its response directly
into a temporary file. This is useful in the situation where the
response from the server can be huge and we don't want to store it into
memory (potentially causing Python to use hundreds of MB's of memory).
By writing into a file we can then open this file later, and read data
a little bit at a time and be very mem efficient.
The return value of this function is the path of the temporary file.
Unless specified using block = False, this function will block until a
successful HTTP 200 response is received.
"""
logger = self.logger
successful_response = False
while not successful_response:
try:
path = urllib.urlretrieve(url)[0]
successful_response = True
except IOError, e:
logger.error('Error Authenticating with remote server: %s', e)
if not block:
raise
except Exception, e:
logger.error('Couldn\'t connect to remote server. Is it running?')
logger.error("%s" % e)
if not block:
raise
if not successful_response:
logger.error("Error connecting to server, waiting 5 seconds and trying again.")
time.sleep(5)
return path
def __get_airtime_version(self): def __get_airtime_version(self):
logger = self.logger # TODO : maybe fix this function to drop an exception?
url = "http://%s:%s/%s/%s" % (self.config["base_url"], try: return self.services.version_url()
str(self.config["base_port"]), self.config["api_base"], except Exception: return -1
self.config["version_url"])
logger.debug("Trying to contact %s", url)
url = url.replace("%%api_key%%", self.config["api_key"])
version = -1
try:
data = self.get_response_from_server(url)
logger.debug("Data: %s", data)
response_json = json.loads(data)
version = response_json['version']
logger.debug("Airtime Version %s detected", version)
except Exception, e:
logger.error("Unable to detect Airtime Version - %s", e)
return -1
return version
def test(self):
logger = self.logger
items = self.get_schedule()[1]
schedule = items["playlists"]
logger.debug("Number of playlists found: %s", str(len(schedule)))
count = 1
for pkey in sorted(schedule.iterkeys()):
logger.debug("Playlist #%s", str(count))
count += 1
playlist = schedule[pkey]
for item in playlist["medias"]:
filename = urlparse(item["uri"])
filename = filename.query[5:]
self.get_media(item["uri"], filename)
def is_server_compatible(self, verbose=True): def is_server_compatible(self, verbose=True):
logger = self.logger logger = self.logger
@ -209,105 +183,30 @@ class AirtimeApiClient(object):
def get_schedule(self): def get_schedule(self):
logger = self.logger # TODO : properly refactor this routine
# For now thre return type is a little fucked for compatibility reasons
# Construct the URL try: return (True, self.services.export_url())
export_url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["export_url"]) except: (False, "")
logger.info("Fetching schedule from %s", export_url)
export_url = export_url.replace('%%api_key%%', self.config["api_key"])
response = ""
try:
response_json = self.get_response_from_server(export_url)
response = json.loads(response_json)
success = True
except Exception, e:
logger.error(e)
success = False
return success, response
def get_media(self, uri, dst):
logger = self.logger
try:
src = uri + "/api_key/%%api_key%%"
logger.info("try to download from %s to %s", src, dst)
src = src.replace("%%api_key%%", self.config["api_key"])
# check if file exists already before downloading again
headers = urllib.urlretrieve(src, dst)[1]
logger.info(headers)
except Exception, e:
logger.error("%s", e)
def notify_liquidsoap_started(self): def notify_liquidsoap_started(self):
logger = self.logger return self.services.notify_liquidsoap_started()
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], \
str(self.config["base_port"]), \
self.config["api_base"], \
self.config["notify_liquidsoap_started"])
url = url.replace("%%api_key%%", self.config["api_key"])
self.get_response_from_server(url, attempts=5)
except Exception, e:
logger.error("Exception: %s", str(e))
"""
This is a callback from liquidsoap, we use this to notify about the
currently playing *song*. We get passed a JSON string which we handed to
liquidsoap in get_liquidsoap_data().
"""
def notify_media_item_start_playing(self, media_id): def notify_media_item_start_playing(self, media_id):
logger = self.logger """ This is a callback from liquidsoap, we use this to notify
response = '' about the currently playing *song*. We get passed a JSON string
try: which we handed to liquidsoap in get_liquidsoap_data(). """
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["update_start_playing_url"]) return self.services.update_start_playing_url(media_id=media_id)
url = url.replace("%%media_id%%", str(media_id))
logger.debug(url)
url = url.replace("%%api_key%%", self.config["api_key"])
response = self.get_response_from_server(url, attempts = 5)
response = json.loads(response)
logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message'])
except Exception, e:
logger.error("Exception: %s", e)
return response
# TODO : get this routine out of here it doesn't belong at all here
def get_liquidsoap_data(self, pkey, schedule): def get_liquidsoap_data(self, pkey, schedule):
playlist = schedule[pkey] playlist = schedule[pkey]
data = dict() data = dict()
try: try: data["schedule_id"] = playlist['id']
data["schedule_id"] = playlist['id'] except Exception: data["schedule_id"] = 0
except Exception:
data["schedule_id"] = 0
return data return data
def get_shows_to_record(self): def get_shows_to_record(self):
logger = self.logger return self.services.show_schedule_url()
response = None
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["show_schedule_url"])
logger.debug(url)
url = url.replace("%%api_key%%", self.config["api_key"])
response = self.get_response_from_server(url)
response = json.loads(response)
logger.info("shows %s", response)
except Exception, e:
logger.error("Exception: %s", e)
response = None
return response
def upload_recorded_show(self, data, headers): def upload_recorded_show(self, data, headers):
logger = self.logger logger = self.logger
@ -316,10 +215,9 @@ class AirtimeApiClient(object):
retries = int(self.config["upload_retries"]) retries = int(self.config["upload_retries"])
retries_wait = int(self.config["upload_wait"]) retries_wait = int(self.config["upload_wait"])
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["upload_file_url"]) url = self.construct_url("upload_file_url")
logger.debug(url) logger.debug(url)
url = url.replace("%%api_key%%", self.config["api_key"])
for i in range(0, retries): for i in range(0, retries):
logger.debug("Upload attempt: %s", i + 1) logger.debug("Upload attempt: %s", i + 1)
@ -344,86 +242,21 @@ class AirtimeApiClient(object):
return response return response
def check_live_stream_auth(self, username, password, dj_type): def check_live_stream_auth(self, username, password, dj_type):
""" return self.services.check_live_stream_auth(
TODO: Why are we using print statements here? Possibly use logger that username=username, password=password, dj_type=dj_type)
is directed to stdout. -MK
"""
response = ''
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["check_live_stream_auth"])
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%username%%", username)
url = url.replace("%%djtype%%", dj_type)
url = url.replace("%%password%%", password)
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e:
print "Exception: %s", e
print "traceback: %s", traceback.format_exc()
response = None
return response
def construct_url(self,config_action_key): def construct_url(self,config_action_key):
"""Constructs the base url for every request""" """Constructs the base url for every request"""
# TODO : Make other methods in this class use this this method. # TODO : Make other methods in this class use this this method.
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config[config_action_key]) url = "http://%s:%s/%s/%s/%s" % \
(self.config["host"], str(self.config["base_port"]),
self.config["base_dir"], self.config["api_base"],
self.config[config_action_key])
url = url.replace("%%api_key%%", self.config["api_key"]) url = url.replace("%%api_key%%", self.config["api_key"])
return url return url
def setup_media_monitor(self): def setup_media_monitor(self):
logger = self.logger return self.services.media_setup_url()
response = None
try:
url = self.construct_url("media_setup_url")
response = self.get_response_from_server(url)
response = json.loads(response)
logger.info("Connected to Airtime Server. Json Media Storage Dir: %s", response)
except Exception, e:
response = None
logger.error("Exception: %s", e)
return response
def update_media_metadata(self, md, mode, is_record=False):
logger = self.logger
response = None
try:
url = self.construct_url("update_media_url")
url = url.replace("%%mode%%", mode)
self.logger.info("Requesting url %s" % url)
md = convert_dict_value_to_utf8(md)
data = urllib.urlencode(md)
req = urllib2.Request(url, data)
response = self.get_response_from_server(req)
logger.info("update media %s, filepath: %s, mode: %s", response, md['MDATA_KEY_FILEPATH'], mode)
self.logger.info("Received response:")
self.logger.info(response)
try: response = json.loads(response)
except ValueError:
logger.info("Could not parse json from response: '%s'" % response)
if("error" not in response and is_record):
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["upload_recorded"])
url = url.replace("%%fileid%%", str(response[u'id']))
url = url.replace("%%showinstanceid%%", str(md['MDATA_KEY_TRACKNUMBER']))
url = url.replace("%%api_key%%", self.config["api_key"])
response = self.get_response_from_server(url)
response = json.loads(response)
logger.info("associate recorded %s", response)
except Exception, e:
response = None
logger.error('Exception: %s', e)
logger.error("traceback: %s", traceback.format_exc())
return response
def send_media_monitor_requests(self, action_list, dry=False): def send_media_monitor_requests(self, action_list, dry=False):
""" """
@ -434,7 +267,6 @@ class AirtimeApiClient(object):
says whether the show was recorded or not. The value of this key says whether the show was recorded or not. The value of this key
does not matter, only if it's present or not. does not matter, only if it's present or not.
""" """
url = self.construct_url('reload_metadata_group')
# We are assuming that action_list is a list of dictionaries such # We are assuming that action_list is a list of dictionaries such
# that every dictionary represents the metadata of a file along # that every dictionary represents the metadata of a file along
# with a special mode key that is the action to be executed by the # with a special mode key that is the action to be executed by the
@ -462,11 +294,7 @@ class AirtimeApiClient(object):
# controller not to actually do any changes # controller not to actually do any changes
if dry: md_list['dry'] = 1 if dry: md_list['dry'] = 1
self.logger.info("Pumping out %d requests..." % len(valid_actions)) self.logger.info("Pumping out %d requests..." % len(valid_actions))
data = urllib.urlencode(md_list) return self.services.reload_metadata_group(_post_data=md_list)
req = urllib2.Request(url, data)
response = self.get_response_from_server(req)
response = json.loads(response)
return response
#returns a list of all db files for a given directory in JSON format: #returns a list of all db files for a given directory in JSON format:
#{"files":["path/to/file1", "path/to/file2"]} #{"files":["path/to/file1", "path/to/file2"]}
@ -476,15 +304,11 @@ class AirtimeApiClient(object):
logger = self.logger logger = self.logger
try: try:
all_files = u"1" if all_files else u"0" all_files = u"1" if all_files else u"0"
url = self.construct_url("list_all_db_files") response = self.services.list_all_db_files(dir_id=dir_id,
url = url.replace("%%dir_id%%", dir_id) all=all_files)
url = url.replace("%%all%%", all_files)
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e: except Exception, e:
response = {} response = {}
logger.error("Exception: %s", e) logger.error("Exception: %s", e)
try: try:
return response["files"] return response["files"]
except KeyError: except KeyError:
@ -493,188 +317,52 @@ class AirtimeApiClient(object):
return [] return []
def list_all_watched_dirs(self): def list_all_watched_dirs(self):
# Does this include the stor directory as well? return self.services.list_all_watched_dirs()
logger = self.logger
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["list_all_watched_dirs"])
url = url.replace("%%api_key%%", self.config["api_key"])
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e:
response = None
logger.error("Exception: %s", e)
self.logger.debug(traceback.format_exc())
return response
def add_watched_dir(self, path): def add_watched_dir(self, path):
logger = self.logger return self.services.add_watched_dir(path=base64.b64encode(path))
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["add_watched_dir"])
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%path%%", base64.b64encode(path))
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e:
response = None
logger.error("Exception: %s", e)
return response
def remove_watched_dir(self, path): def remove_watched_dir(self, path):
logger = self.logger return self.services.remove_watched_dir(path=base64.b64encode(path))
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["remove_watched_dir"])
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%path%%", base64.b64encode(path))
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e:
response = None
logger.error("Exception: %s", e)
return response
def set_storage_dir(self, path): def set_storage_dir(self, path):
logger = self.logger return self.services.set_storage_dir(path=base64.b64encode(path))
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["set_storage_dir"])
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%path%%", base64.b64encode(path))
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e:
response = None
logger.error("Exception: %s", e)
return response
def get_stream_setting(self): def get_stream_setting(self):
logger = self.logger logger = self.logger
try: try: return self.services.get_stream_setting()
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["get_stream_setting"])
url = url.replace("%%api_key%%", self.config["api_key"])
response = self.get_response_from_server(url)
response = json.loads(response)
except Exception, e: except Exception, e:
response = None
logger.error("Exception: %s", e) logger.error("Exception: %s", e)
return None
return response
"""
Purpose of this method is to contact the server with a "Hey its me!"
message. This will allow the server to register the component's (component
= media-monitor, pypo etc.) ip address, and later use it to query monit via
monit's http service, or download log files via a http server.
"""
def register_component(self, component): def register_component(self, component):
logger = self.logger """ Purpose of this method is to contact the server with a "Hey its
try: me!" message. This will allow the server to register the component's
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["register_component"]) (component = media-monitor, pypo etc.) ip address, and later use it
to query monit via monit's http service, or download log files via a
url = url.replace("%%api_key%%", self.config["api_key"]) http server. """
url = url.replace("%%component%%", component) return self.services.register_component(component=component)
self.get_response_from_server(url)
except Exception, e:
logger.error("Exception: %s", e)
def notify_liquidsoap_status(self, msg, stream_id, time): def notify_liquidsoap_status(self, msg, stream_id, time):
logger = self.logger logger = self.logger
try: try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["update_liquidsoap_status"])
url = url.replace("%%api_key%%", self.config["api_key"])
msg = msg.replace('/', ' ')
encoded_msg = urllib.quote(msg, '') encoded_msg = urllib.quote(msg, '')
url = url.replace("%%msg%%", encoded_msg) self.update_liquidsoap_status.req(msg=encoded_msg, stream_id=stream_id,
url = url.replace("%%stream_id%%", stream_id) boot_time=time).retry(5)
url = url.replace("%%boot_time%%", time)
self.get_response_from_server(url, attempts = 5)
except Exception, e: except Exception, e:
logger.error("Exception: %s", e) logger.error("Exception: %s", e)
def notify_source_status(self, sourcename, status): def notify_source_status(self, sourcename, status):
logger = self.logger
try: try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["update_source_status"]) logger = self.logger
return self.services.update_source_status.req(sourcename=sourcename,
url = url.replace("%%api_key%%", self.config["api_key"]) status=status).retry(5)
url = url.replace("%%sourcename%%", sourcename)
url = url.replace("%%status%%", status)
self.get_response_from_server(url, attempts = 5)
except Exception, e: except Exception, e:
logger.error("Exception: %s", e) logger.error("Exception: %s", e)
"""
This function updates status of mounted file system information on airtime
"""
def update_file_system_mount(self, added_dir, removed_dir):
logger = self.logger
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["update_fs_mount"])
url = url.replace("%%api_key%%", self.config["api_key"])
added_data_string = string.join(added_dir, ',')
removed_data_string = string.join(removed_dir, ',')
map = [("added_dir", added_data_string), ("removed_dir", removed_data_string)]
data = urllib.urlencode(map)
req = urllib2.Request(url, data)
response = self.get_response_from_server(req)
logger.info("update file system mount: %s", json.loads(response))
except Exception, e:
logger.error('Exception: %s', e)
logger.error("traceback: %s", traceback.format_exc())
"""
When watched dir is missing(unplugged or something) on boot up, this
function will get called and will call appropriate function on Airtime.
"""
def handle_watched_dir_missing(self, dir):
logger = self.logger
try:
url = "http://%s:%s/%s/%s" % (self.config["base_url"], str(self.config["base_port"]), self.config["api_base"], self.config["handle_watched_dir_missing"])
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%dir%%", base64.b64encode(dir))
response = self.get_response_from_server(url)
logger.info("update file system mount: %s", json.loads(response))
except Exception, e:
logger.error('Exception: %s', e)
logger.error("traceback: %s", traceback.format_exc())
def get_bootstrap_info(self): def get_bootstrap_info(self):
""" """ Retrive infomations needed on bootstrap time """
Retrive infomations needed on bootstrap time return self.services.get_bootstrap_info()
"""
logger = self.logger
try:
url = self.construct_url("get_bootstrap_info")
response = self.get_response_from_server(url)
response = json.loads(response)
logger.info("Bootstrap info retrieved %s", response)
except Exception, e:
response = None
logger.error('Exception: %s', e)
logger.error("traceback: %s", traceback.format_exc())
return response
def get_files_without_replay_gain_value(self, dir_id): def get_files_without_replay_gain_value(self, dir_id):
""" """
@ -682,43 +370,16 @@ class AirtimeApiClient(object):
calculated. This list of files is downloaded into a file and the path calculated. This list of files is downloaded into a file and the path
to this file is the return value. to this file is the return value.
""" """
#http://localhost/api/get-files-without-replay-gain/dir_id/1 #http://localhost/api/get-files-without-replay-gain/dir_id/1
return self.services.get_files_without_replay_gain(dir_id=dir_id)
logger = self.logger
try:
url = "http://%(base_url)s:%(base_port)s/%(api_base)s/%(get_files_without_replay_gain)s/" % (self.config)
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%dir_id%%", dir_id)
response = self.get_response_from_server(url)
logger.info("update file system mount: %s", response)
response = json.loads(response)
#file_path = self.get_response_into_file(url)
except Exception, e:
response = None
logger.error('Exception: %s', e)
logger.error("traceback: %s", traceback.format_exc())
return response
def update_replay_gain_values(self, pairs): def update_replay_gain_values(self, pairs):
""" """
'pairs' is a list of pairs in (x, y), where x is the file's database 'pairs' is a list of pairs in (x, y), where x is the file's database
row id and y is the file's replay_gain value in dB row id and y is the file's replay_gain value in dB
""" """
self.logger.debug(self.services.update_replay_gain_value(
#http://localhost/api/update-replay-gain-value/ _post_data={'data': json.dumps(pairs)}))
try:
url = "http://%(base_url)s:%(base_port)s/%(api_base)s/%(update_replay_gain_value)s/" % (self.config)
url = url.replace("%%api_key%%", self.config["api_key"])
data = urllib.urlencode({'data': json.dumps(pairs)})
request = urllib2.Request(url, data)
self.logger.debug(self.get_response_from_server(request))
except Exception, e:
self.logger.error("Exception: %s", e)
raise
def notify_webstream_data(self, data, media_id): def notify_webstream_data(self, data, media_id):
@ -726,14 +387,5 @@ class AirtimeApiClient(object):
Update the server with the latest metadata we've received from the Update the server with the latest metadata we've received from the
external webstream external webstream
""" """
try: self.logger.info( self.notify_webstream_data.req(
url = "http://%(base_url)s:%(base_port)s/%(api_base)s/%(notify_webstream_data)s/" % (self.config) _post_data={'data':data}, media_id=str(media_id)).retry(5))
url = url.replace("%%media_id%%", str(media_id))
url = url.replace("%%api_key%%", self.config["api_key"])
data = urllib.urlencode({'data': data})
self.logger.debug(url)
request = urllib2.Request(url, data)
self.logger.info(self.get_response_from_server(request, attempts = 5))
except Exception, e:
self.logger.error("Exception: %s", e)

View file

@ -0,0 +1,30 @@
import unittest
from .. api_client import ApcUrl, UrlBadParam, IncompleteUrl
class TestApcUrl(unittest.TestCase):
def test_init(self):
url = "/testing"
u = ApcUrl(url)
self.assertEquals( u.base_url, url)
def test_params_1(self):
u = ApcUrl("/testing/%%key%%")
self.assertEquals(u.params(key='val').url(), '/testing/val')
def test_params_2(self):
u = ApcUrl('/testing/%%key%%/%%api%%/more_testing')
full_url = u.params(key="AAA",api="BBB").url()
self.assertEquals(full_url, '/testing/AAA/BBB/more_testing')
def test_params_ex(self):
u = ApcUrl("/testing/%%key%%")
with self.assertRaises(UrlBadParam):
u.params(bad_key='testing')
def test_url(self):
u = "one/two/three"
self.assertEquals( ApcUrl(u).url(), u )
def test_url_ex(self):
u = ApcUrl('/%%one%%/%%two%%/three').params(two='testing')
with self.assertRaises(IncompleteUrl): u.url()

View file

@ -0,0 +1,21 @@
import unittest
import json
from mock import MagicMock, patch
from .. api_client import ApcUrl, ApiRequest
class TestApiRequest(unittest.TestCase):
def test_init(self):
u = ApiRequest('request_name', ApcUrl('/test/ing'))
self.assertEquals(u.name, "request_name")
def test_call(self):
ret = json.dumps( {u'ok':u'ok'} )
read = MagicMock()
read.read = MagicMock(return_value=ret)
u = '/testing'
with patch('urllib2.urlopen') as mock_method:
mock_method.return_value = read
request = ApiRequest('mm', ApcUrl(u))()
self.assertEquals(request, json.loads(ret))
if __name__ == '__main__': unittest.main()

View file

@ -0,0 +1,32 @@
import unittest
import json
from mock import patch, MagicMock
from configobj import ConfigObj
from .. api_client import RequestProvider
class TestRequestProvider(unittest.TestCase):
def setUp(self):
self.cfg = ConfigObj('api_client.cfg')
def test_test(self):
self.assertTrue('api_key' in self.cfg)
def test_init(self):
rp = RequestProvider(self.cfg)
self.assertTrue( len( rp.available_requests() ) > 0 )
def test_contains(self):
rp = RequestProvider(self.cfg)
methods = ['upload_recorded', 'update_media_url', 'list_all_db_files']
for meth in methods:
self.assertTrue( meth in rp )
def test_notify_webstream_data(self):
ret = json.dumps( {u'testing' : u'123' } )
rp = RequestProvider(self.cfg)
read = MagicMock()
read.read = MagicMock(return_value=ret)
with patch('urllib2.urlopen') as mock_method:
mock_method.return_value = read
response = rp.notify_webstream_data(media_id=123)
mock_method.called_once_with(media_id=123)
self.assertEquals(json.loads(ret), response)
if __name__ == '__main__': unittest.main()

View file

@ -256,3 +256,10 @@ class Manager(Loggable):
notifier = pyinotify.Notifier(self.wm) notifier = pyinotify.Notifier(self.wm)
notifier.coalesce_events() notifier.coalesce_events()
notifier.loop() notifier.loop()
#notifier = pyinotify.ThreadedNotifier(self.wm, read_freq=1)
#notifier.coalesce_events()
#notifier.start()
#return notifier
#import asyncore
#notifier = pyinotify.AsyncNotifier(self.wm)
#asyncore.loop()

View file

@ -56,7 +56,10 @@ class ReplayGainUpdater(Thread, Loggable):
full_path = os.path.join(dir_path, f['fp']) full_path = os.path.join(dir_path, f['fp'])
processed_data.append((f['id'], replaygain.calculate_replay_gain(full_path))) processed_data.append((f['id'], replaygain.calculate_replay_gain(full_path)))
self.api_client.update_replay_gain_values(processed_data) try:
self.api_client.update_replay_gain_values(processed_data)
except Exception as e: self.unexpected_exception(e)
if len(files) == 0: break if len(files) == 0: break
self.logger.info("Processed: %d songs" % total) self.logger.info("Processed: %d songs" % total)

View file

@ -24,6 +24,7 @@ import media.monitor.pure as mmp
from api_clients import api_client as apc from api_clients import api_client as apc
def main(global_config, api_client_config, log_config, def main(global_config, api_client_config, log_config,
index_create_attempt=False): index_create_attempt=False):
for cfg in [global_config, api_client_config]: for cfg in [global_config, api_client_config]:
@ -134,7 +135,7 @@ def main(global_config, api_client_config, log_config,
apiclient.register_component('media-monitor') apiclient.register_component('media-monitor')
manager.loop() return manager.loop()
__doc__ = """ __doc__ = """
Usage: Usage:
@ -147,6 +148,9 @@ Options:
--log=<path> log config at <path> --log=<path> log config at <path>
""" """
def main_loop():
while True: pass
if __name__ == '__main__': if __name__ == '__main__':
from docopt import docopt from docopt import docopt
args = docopt(__doc__,version="mm1.99") args = docopt(__doc__,version="mm1.99")
@ -156,3 +160,5 @@ if __name__ == '__main__':
sys.exit(0) sys.exit(0)
print("Running mm1.99") print("Running mm1.99")
main(args['--config'],args['--apiclient'],args['--log']) main(args['--config'],args['--apiclient'],args['--log'])
#gevent.joinall([ gevent.spawn(main_loop) ])

View file

@ -21,27 +21,26 @@ import inspect
from configobj import ConfigObj from configobj import ConfigObj
# custom imports # custom imports
from util import * #from util import *
from api_clients import * from api_client import AirtimeApiClient
import random
import unittest import unittest
# configure logging # configure logging
logging.config.fileConfig("logging-api-validator.cfg") #logging.config.fileConfig("logging-api-validator.cfg")
try: try:
config = ConfigObj('/etc/airtime/pypo.cfg') config = ConfigObj('/etc/airtime/pypo.cfg')
except Exception, e: except Exception, e:
print 'Error loading config file: ', e print 'Error loading config file: ', e
sys.exit() sys.exit()
class TestApiFunctions(unittest.TestCase): class TestApiFunctions(unittest.TestCase):
def setUp(self): def setUp(self):
self.api_client = api_client.api_client_factory(config) self.api_client = AirtimeApiClient()
def test_is_server_compatible(self): def test_is_server_compatible(self):
self.assertTrue(self.api_client.is_server_compatible(False)) self.assertTrue(self.api_client.is_server_compatible(False))
@ -59,16 +58,17 @@ class TestApiFunctions(unittest.TestCase):
arr = dict() arr = dict()
arr["x"] = dict() arr["x"] = dict()
arr["x"]["schedule_id"]=1 arr["x"]["schedule_id"]=1
response = self.api_client.notify_scheduled_item_start_playing("x", arr) response = self.api_client.notify_scheduled_item_start_playing("x", arr)
self.assertTrue(response.has_key("status")) self.assertTrue(response.has_key("status"))
self.assertTrue(response.has_key("message")) self.assertTrue(response.has_key("message"))
def test_notify_media_item_start_playing(self): def test_notify_media_item_start_playing(self):
response = self.api_client.notify_media_item_start_playing('{"schedule_id":1}', 5) response = self.api_client.notify_media_item_start_playing('{"schedule_id":1}', 5)
return response =
self.assertTrue(response.has_key("status")) self.assertTrue(response.has_key("status"))
self.assertTrue(response.has_key("message")) self.assertTrue(response.has_key("message"))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View file

@ -10,3 +10,4 @@ wsgiref==0.1.2
configobj==4.7.2 configobj==4.7.2
mutagen==1.20 mutagen==1.20
docopt==0.4.2 docopt==0.4.2
gevent==0.13.7

View file

@ -16,10 +16,11 @@ if (substr($sapi_type, 0, 3) == 'cli') {
$apiKey = $airtimeIni['general']['api_key']; $apiKey = $airtimeIni['general']['api_key'];
$baseUrl = $airtimeIni['general']['base_url']; $baseUrl = $airtimeIni['general']['base_url'];
$base_port = $airtimeIni['general']['base_port']; $base_port = $airtimeIni['general']['base_port'];
$base_dir = $airtimeIni['general']['base_dir'];
$status = AirtimeCheck::GetStatus($baseUrl, $base_port, $base_dir, $apiKey);
$status = AirtimeCheck::GetStatus($baseUrl, $base_port, $apiKey);
AirtimeCheck::PrintStatus($baseUrl, $base_port, $status); AirtimeCheck::PrintStatus($baseUrl, $base_port, $status);
//AirtimeCheck::PrintStatus($baseUrl, $status);
} }
class AirtimeCheck { class AirtimeCheck {
@ -104,9 +105,9 @@ class AirtimeCheck {
return $headerInfo['Server'][0]; return $headerInfo['Server'][0];
} }
public static function GetStatus($p_baseUrl, $p_basePort, $p_apiKey){ public static function GetStatus($p_baseUrl, $p_basePort, $p_baseDir, $p_apiKey){
$url = "http://$p_baseUrl:$p_basePort/api/status/format/json/api_key/%%api_key%%"; $url = "http://$p_baseUrl:$p_basePort/$p_baseDir/api/status/format/json/api_key/%%api_key%%";
self::output_status("AIRTIME_STATUS_URL", $url); self::output_status("AIRTIME_STATUS_URL", $url);
$url = str_replace("%%api_key%%", $p_apiKey, $url); $url = str_replace("%%api_key%%", $p_apiKey, $url);