CC-2518: Auto install script for manual install

- install dir is renamed to install_minimal
- virtualenv command is moved to install script.
- need more work on install_full part
This commit is contained in:
James 2011-07-19 17:30:23 -04:00
parent 65ea711792
commit 931fb4db62
31 changed files with 723 additions and 5 deletions

View file

@ -0,0 +1,19 @@
<?php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20110312121200 extends AbstractMigration
{
public function up(Schema $schema)
{
$schema->dropTable("cc_backup");
$schema->dropTable("cc_trans");
}
public function down(Schema $schema)
{
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema,
Doctrine\DBAL\Schema\Table,
Doctrine\DBAL\Schema\Column,
Doctrine\DBAL\Types\Type;
class Version20110331111708 extends AbstractMigration
{
public function up(Schema $schema)
{
//start cc_show_instances modifications
$show_instances_table = $schema->getTable('cc_show_instances');
$show_instances_table->addColumn('record', 'smallint', array('notnull' => 0, 'default' => 0));
$show_instances_table->addColumn('rebroadcast', 'smallint', array('notnull' => 0, 'default' => 0));
$show_instances_table->addColumn('instance_id', 'integer', array('notnull' => 0));
$show_instances_table->addColumn('file_id', 'integer', array('notnull' => 0));
$show_instances_table->addColumn('soundcloud_id', 'integer', array('notnull' => 0));
$show_instances_table->addNamedForeignKeyConstraint('cc_original_show_instance_fkey', $show_instances_table, array('instance_id'), array('id'), array('onDelete' => 'CASCADE'));
$files_table = $schema->getTable('cc_files');
$show_instances_table->addNamedForeignKeyConstraint('cc_recorded_file_fkey', $files_table, array('file_id'), array('id'), array('onDelete' => 'CASCADE'));
//end cc_show_instances modifications
//start cc_show_days modifications
$show_days_table = $schema->getTable('cc_show_days');
$show_days_table->addColumn('record', 'smallint', array( 'notnull' => 0, 'default' => 0));
//end cc_show_days modifications
//start cc_show modifications
$show_table = $schema->getTable('cc_show');
$show_table->addColumn('url', 'string', array('notnull' => 0, 'length' => 255));
//end cc_show modifications
//start cc_schedule modifications
$schedule_table = $schema->getTable('cc_schedule');
$playlist_id_col = $schedule_table->getColumn('playlist_id');
$playlist_id_col->setNotnull(false);
//end cc_schedule modifications
//create cc_show_rebroadcast table
$cc_show_rebroadcast_table = $schema->createTable('cc_show_rebroadcast');
$cc_show_rebroadcast_table->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$cc_show_rebroadcast_table->addColumn('day_offset', 'string', array('length' => 255));
$cc_show_rebroadcast_table->addColumn('start_time', 'datetime', array('notnull' => 1));
$cc_show_rebroadcast_table->addColumn('show_id', 'integer', array('notnull' => 1));
$cc_show_rebroadcast_table->setPrimaryKey(array('id'));
//end create cc_show_rebroadcast table
}
public function down(Schema $schema)
{
//start cc_show_instances modifications
$show_instances_table = $schema->getTable('cc_show_instances');
$show_instances_table->dropColumn('record');
$show_instances_table->dropColumn('rebroadcast');
$show_instances_table->dropColumn('instance_id');
$show_instances_table->dropColumn('file_id');
$show_instances_table->dropColumn('soundcloud_id');
//end cc_show_instances modifications
//start cc_show_days modifications
$show_days_table = $schema->getTable('cc_show_days');
$show_days_table->dropColumn('record');
//end cc_show_days modifications
//start cc_show modifications
$show_table = $schema->getTable('cc_show');
$show_table->dropColumn('url');
//end cc_show modifications
//start cc_schedule modifications
$schedule_table = $schema->getTable('cc_schedule');
$playlist_id_col = $schedule_table->getColumn('playlist_id');
$playlist_id_col->setNotnull(true);
//end cc_schedule modifications
//drop cc_show_rebroadcast table
$schema->dropTable('cc_show_rebroadcast');
//end drop cc_show_rebroadcast table
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20110402164819 extends AbstractMigration
{
public function up(Schema $schema)
{
//start cc_show modifications
$show_table = $schema->getTable('cc_show');
$show_table->addColumn('genre', 'string', array('notnull' => 0, 'length' => 255, 'default' => ""));
//end cc_show modifications
}
public function down(Schema $schema)
{
//start cc_show modifications
$show_table = $schema->getTable('cc_show');
$show_table->dropColumn('genre');
//end cc_show modifications
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20110406182005 extends AbstractMigration
{
public function up(Schema $schema)
{
//start cc_show_instances modifications
$cc_show_instances = $schema->getTable('cc_show_instances');
$cc_show_instances->addColumn('time_filled', 'time', array('notnull' => false));
//end cc_show_instances modifications
//start cc_show_rebroadcast modifications
$cc_show_rebroadcast = $schema->getTable('cc_show_rebroadcast');
$type = $cc_show_rebroadcast->getColumn('start_time')->getType()->getName();
if($type == 'datetime') {
$cc_show_rebroadcast->dropColumn('start_time');
$cc_show_rebroadcast->addColumn('start_time', 'time', array('notnull' => true));
}
//end cc_show_rebroadcast modifications
}
public function down(Schema $schema)
{
//start cc_show_instances modifications
$cc_show_instances = $schema->getTable('cc_show_instances');
$cc_show_instances->dropColumn('time_filled');
//end cc_show_instances modifications
//start cc_show_rebroadcast modifications
$cc_show_rebroadcast = $schema->getTable('cc_show_rebroadcast');
$type = $cc_show_rebroadcast->getColumn('start_time')->getType()->getName();
if($type == 'datetime') {
$cc_show_rebroadcast->dropColumn('start_time');
$cc_show_rebroadcast->addColumn('start_time', 'datetime', array('notnull' => 1));
}
//end cc_show_rebroadcast modifications
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace DoctrineMigrations;
//CC-2279 Upgrade script for creating the cc_music_dirs table.
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20110629143017 extends AbstractMigration
{
public function up(Schema $schema)
{
//create cc_music_dirs table
$cc_music_dirs = $schema->createTable('cc_music_dirs');
$cc_music_dirs->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$cc_music_dirs->addColumn('type', 'string', array('length' => 255));
$cc_music_dirs->addColumn('directory', 'text', array('unique' => true));
$cc_music_dirs->setPrimaryKey(array('id'));
//end create cc_music_dirs table
}
public function down(Schema $schema)
{
$schema->dropTable('cc_music_dirs');
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace DoctrineMigrations;
/*
1) update cc_files table to include to "directory" column
2) create a foreign key relationship from cc_files to cc_music_dirs
3) create a foreign key relationship from cc_schedule to cc_files
*/
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20110711161043 extends AbstractMigration
{
public function up(Schema $schema)
{
/* 1) update cc_files table to include to "directory" column */
$this->_addSql("INSERT INTO cc_music_dirs (type, directory) VALUES ('stor', '/srv/airtime/stor');");
$this->_addSql("INSERT INTO cc_music_dirs (type, directory) VALUES ('upgrade', '');");
$cc_music_dirs = $schema->getTable('cc_music_dirs');
/* 2) create a foreign key relationship from cc_files to cc_music_dirs */
$cc_files = $schema->getTable('cc_files');
$cc_files->addColumn('directory', 'integer', array('default'=> 2));
$cc_files->addNamedForeignKeyConstraint('cc_music_dirs_folder_fkey', $cc_music_dirs, array('directory'), array('id'), array('onDelete' => 'CASCADE'));
/* 3) create a foreign key relationship from cc_schedule to cc_files */
$cc_schedule = $schema->getTable('cc_schedule');
$cc_schedule->addNamedForeignKeyConstraint('cc_files_folder_fkey', $cc_files, array('file_id'), array('id'), array('onDelete' => 'CASCADE'));
}
public function down(Schema $schema)
{
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20110713161043 extends AbstractMigration
{
public function up(Schema $schema)
{
//create cc_country table
$cc_country = $schema->createTable('cc_country');
$cc_country->addColumn('isocode', 'string', array('length' => 3));
$cc_country->addColumn('name', 'string', array('length' => 255));
$cc_country->setPrimaryKey(array('isocode'));
//end create cc_country table
}
public function down(Schema $schema)
{
$schema->dropTable('cc_country');
}
}

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-migrations xmlns="http://doctrine-project.org/schemas/migrations/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/migrations/configuration
http://doctrine-project.org/schemas/migrations/configuration.xsd">
<name>Airtime 1.9.0 Database Upgrade</name>
<migrations-namespace>DoctrineMigrations</migrations-namespace>
<table name="doctrine_migration_versions" />
<migrations-directory>./</migrations-directory>
</doctrine-migrations>

View file

@ -0,0 +1,5 @@
<?php
require_once(dirname(__FILE__).'/include/AirtimeIni.php');
require_once(dirname(__FILE__).'/include/AirtimeInstall.php');
AirtimeInstall::DirCheck();

44
install_minimal/airtime-install Executable file
View file

@ -0,0 +1,44 @@
#!/bin/bash
echo -e "\n******************************** Install Begin *********************************"
echo -e "\n*** Creating Vitualenv for Airtime ***"
sudo virtualenv --no-site-package -p /usr/bin/python2.6 /usr/lib/airtime/airtime_virtualenv
echo -e "\n*** Installing Python Libraries ***"
sudo /usr/lib/airtime/airtime_virtualenv/bin/pip install kombu poster pyinotify==0.9.2 mutagen==1.20 configobj -E /usr/lib/airtime/airtime_virtualenv
virtualenv_bin="/usr/lib/airtime/airtime_virtualenv/bin/"
. ${virtualenv_bin}activate
#Cause bash script to exit if any of the installers
#return with a non-zero return value.
set -e
# Absolute path to this script
SCRIPT=`readlink -f $0`
# Absolute directory this script is in
SCRIPTPATH=`dirname $SCRIPT`
echo -e "\n*** Creating Pypo User ***"
python ${SCRIPTPATH}/../python_apps/create-pypo-user.py
php ${SCRIPTPATH}/include/airtime-install.php $@
echo -e "\n*** API Client Installation ***"
python ${SCRIPTPATH}/../python_apps/api_clients/install/api_client_install.py
echo -e "\n*** Pypo Installation ***"
python ${SCRIPTPATH}/../python_apps/pypo/install/pypo-install.py
echo -e "\n*** Recorder Installation ***"
python ${SCRIPTPATH}/../python_apps/show-recorder/install/recorder-install.py
echo -e "\n*** Media Monitor Installation ***"
python ${SCRIPTPATH}/../python_apps/media-monitor/install/media-monitor-install.py
sleep 4
echo -e "\n*** Verifying your system environment ***"
airtime-check-system
echo -e "\n******************************* Install Complete *******************************"

View file

@ -0,0 +1,38 @@
#!/bin/bash
virtualenv_bin="/usr/lib/airtime/airtime_virtualenv/bin/"
. ${virtualenv_bin}activate
#Cause bash script to exit if any of the installers
#return with a non-zero return value.
set -e
# Absolute path to this script
SCRIPT=`readlink -f $0`
# Absolute directory this script is in
SCRIPTPATH=`dirname $SCRIPT`
echo -e "\n******************************* Uninstall Begin ********************************"
echo -e "\n*** Uninstalling Pypo ***"
python ${SCRIPTPATH}/../python_apps/pypo/install/pypo-uninstall.py
echo -e "\n*** Uninstalling Show Recorder ***"
python ${SCRIPTPATH}/../python_apps/show-recorder/install/recorder-uninstall.py
echo -e "\n*** Uninstalling Media Monitor ***"
python ${SCRIPTPATH}/../python_apps/media-monitor/install/media-monitor-uninstall.py
echo -e "\n*** Uninstalling API Client ***"
python ${SCRIPTPATH}/../python_apps/api_clients/install/api_client_uninstall.py
echo -e "\n*** Removing Pypo User ***"
python ${SCRIPTPATH}/../python_apps/remove-pypo-user.py
php ${SCRIPTPATH}/include/airtime-uninstall.php
echo -e "\n****************************** Uninstall Complete ******************************\n"
echo "NOTE: To fully remove all Airtime files, you will also have to manually delete"
echo " the directories '/srv/airtime'(default storage location of media files)"
echo -e " and '/etc/airtime'(where the config files are stored).\n"

View file

@ -0,0 +1,11 @@
<VirtualHost *:80>
ServerAdmin foo@bar.org
DocumentRoot /var/www/airtime/public
<Directory /var/www/airtime/public>
DirectoryIndex index.php
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

View file

@ -0,0 +1,260 @@
<?php
/**
* @package Airtime
* @copyright 2011 Sourcefabric o.p.s.
* @license http://www.gnu.org/licenses/gpl-3.0.txt
*/
// Do not allow remote execution
$arr = array_diff_assoc($_SERVER, $_ENV);
if (isset($arr["DOCUMENT_ROOT"]) && ($arr["DOCUMENT_ROOT"] != "") ) {
header("HTTP/1.1 400");
header("Content-type: text/plain; charset=UTF-8");
echo "400 Not executable\r\n";
exit(1);
}
//make sure user has Postgresql PHP extension installed.
if (!function_exists('pg_connect')) {
trigger_error("PostgreSQL PHP extension required and not found.", E_USER_ERROR);
exit(2);
}
/* This class deals with the config files stored in /etc/airtime */
class AirtimeIni
{
const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf";
const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg";
const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg";
const CONF_FILE_API_CLIENT = "/etc/airtime/api_client.cfg";
const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg";
const CONF_FILE_MEDIAMONITOR = "/etc/airtime/media-monitor.cfg";
const CONF_FILE_MONIT = "/etc/monit/conf.d/airtime-monit.cfg";
public static function IniFilesExist()
{
$configFiles = array(AirtimeIni::CONF_FILE_AIRTIME,
AirtimeIni::CONF_FILE_PYPO,
AirtimeIni::CONF_FILE_RECORDER,
AirtimeIni::CONF_FILE_LIQUIDSOAP,
AirtimeIni::CONF_FILE_MEDIAMONITOR);
$exist = false;
foreach ($configFiles as $conf) {
if (file_exists($conf)) {
echo "Existing config file detected at $conf".PHP_EOL;
$exist = true;
}
}
return $exist;
}
/**
* This function creates the /etc/airtime configuration folder
* and copies the default config files to it.
*/
public static function CreateIniFiles()
{
if (!file_exists("/etc/airtime/")){
if (!mkdir("/etc/airtime/", 0755, true)){
echo "Could not create /etc/airtime/ directory. Exiting.";
exit(1);
}
}
if (!copy(AirtimeInstall::GetAirtimeSrcDir()."/build/airtime.conf", AirtimeIni::CONF_FILE_AIRTIME)){
echo "Could not copy airtime.conf to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy(__DIR__."/../../python_apps/api_clients/api_client.cfg", AirtimeIni::CONF_FILE_API_CLIENT)){
echo "Could not copy api_client.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy(__DIR__."/../../python_apps/pypo/pypo.cfg", AirtimeIni::CONF_FILE_PYPO)){
echo "Could not copy pypo.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy(__DIR__."/../../python_apps/show-recorder/recorder.cfg", AirtimeIni::CONF_FILE_RECORDER)){
echo "Could not copy recorder.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy(__DIR__."/../../python_apps/pypo/liquidsoap_scripts/liquidsoap.cfg", AirtimeIni::CONF_FILE_LIQUIDSOAP)){
echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy(__DIR__."/../../python_apps/media-monitor/media-monitor.cfg", AirtimeIni::CONF_FILE_MEDIAMONITOR)){
echo "Could not copy media-monitor.cfg to /etc/airtime/. Exiting.";
exit(1);
}
}
public static function CreateMonitFile(){
if (!copy(__DIR__."/../../python_apps/monit/airtime-monit.cfg", AirtimeIni::CONF_FILE_MONIT)){
echo "Could not copy airtime-monit.cfg to /etc/monit/conf.d/. Exiting.";
exit(1);
}
}
public static function RemoveMonitFile(){
@unlink("/etc/monit/conf.d/airtime-monit.cfg");
}
/**
* This function removes /etc/airtime and the configuration
* files present within it.
*/
public static function RemoveIniFiles()
{
if (file_exists(AirtimeIni::CONF_FILE_AIRTIME)){
unlink(AirtimeIni::CONF_FILE_AIRTIME);
}
if (file_exists(AirtimeIni::CONF_FILE_PYPO)){
unlink(AirtimeIni::CONF_FILE_PYPO);
}
if (file_exists(AirtimeIni::CONF_FILE_RECORDER)){
unlink(AirtimeIni::CONF_FILE_RECORDER);
}
if (file_exists(AirtimeIni::CONF_FILE_LIQUIDSOAP)){
unlink(AirtimeIni::CONF_FILE_LIQUIDSOAP);
}
//wait until Airtime 1.9.0
if (file_exists(AirtimeIni::CONF_FILE_MEDIAMONITOR)){
unlink(AirtimeIni::CONF_FILE_MEDIAMONITOR);
}
if (file_exists("etc/airtime")){
rmdir("/etc/airtime/");
}
}
/**
* This function generates a random string.
*
* The random string uses two parameters: $p_len and $p_chars. These
* parameters do not need to be provided, in which case defaults are
* used.
*
* @param string $p_len
* How long should the generated string be.
* @param string $p_chars
* String containing chars that should be used for generating.
* @return string
* The generated random string.
*/
public static function GenerateRandomString($p_len=20, $p_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
$string = '';
for ($i = 0; $i < $p_len; $i++)
{
$pos = mt_rand(0, strlen($p_chars)-1);
$string .= $p_chars{$pos};
}
return $string;
}
/**
* This function updates an INI style config file.
*
* A property and the value the property should be changed to are
* supplied. If the property is not found, then no changes are made.
*
* @param string $p_filename
* The path the to the file.
* @param string $p_property
* The property to look for in order to change its value.
* @param string $p_value
* The value the property should be changed to.
*
*/
public static function UpdateIniValue($p_filename, $p_property, $p_value)
{
$lines = file($p_filename);
$n=count($lines);
foreach ($lines as &$line) {
if ($line[0] != "#"){
$key_value = explode("=", $line);
$key = trim($key_value[0]);
if ($key == $p_property){
$line = "$p_property = $p_value".PHP_EOL;
}
}
}
$fp=fopen($p_filename, 'w');
for($i=0; $i<$n; $i++){
fwrite($fp, $lines[$i]);
}
fclose($fp);
}
/**
* After the configuration files have been copied to /etc/airtime,
* this function will update them to values unique to this
* particular installation.
*/
public static function UpdateIniFiles()
{
$api_key = AirtimeIni::GenerateRandomString();
AirtimeIni::UpdateIniValue(AirtimeIni::CONF_FILE_AIRTIME, 'api_key', $api_key);
AirtimeIni::UpdateIniValue(AirtimeIni::CONF_FILE_AIRTIME, 'airtime_dir', AirtimeInstall::CONF_DIR_WWW);
AirtimeIni::UpdateIniValue(AirtimeIni::CONF_FILE_PYPO, 'api_key', "'$api_key'");
AirtimeIni::UpdateIniValue(AirtimeIni::CONF_FILE_RECORDER, 'api_key', "'$api_key'");
AirtimeIni::UpdateIniValue(AirtimeIni::CONF_FILE_MEDIAMONITOR, 'api_key', "'$api_key'");
}
public static function ReadPythonConfig($p_filename)
{
$values = array();
$lines = file($p_filename);
$n=count($lines);
for ($i=0; $i<$n; $i++) {
if (strlen($lines[$i]) && !in_array(substr($lines[$i], 0, 1), array('#', PHP_EOL))){
$info = explode("=", $lines[$i]);
$values[trim($info[0])] = trim($info[1]);
}
}
return $values;
}
public static function MergeConfigFiles($configFiles, $suffix) {
foreach ($configFiles as $conf) {
if (file_exists("$conf$suffix.bak")) {
if($conf === CONF_FILE_AIRTIME) {
// Parse with sections
$newSettings = parse_ini_file($conf, true);
$oldSettings = parse_ini_file("$conf$suffix.bak", true);
}
else {
$newSettings = AirtimeIni::ReadPythonConfig($conf);
$oldSettings = AirtimeIni::ReadPythonConfig("$conf$suffix.bak");
}
$settings = array_keys($newSettings);
foreach($settings as $section) {
if(isset($oldSettings[$section])) {
if(is_array($oldSettings[$section])) {
$sectionKeys = array_keys($newSettings[$section]);
foreach($sectionKeys as $sectionKey) {
if(isset($oldSettings[$section][$sectionKey])) {
AirtimeIni::UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]);
}
}
}
else {
AirtimeIni::UpdateIniValue($conf, $section, $oldSettings[$section]);
}
}
}
}
}
}
}

View file

@ -0,0 +1,417 @@
<?php
//Pear classes.
set_include_path(__DIR__.'/../../airtime_mvc/library/pear' . PATH_SEPARATOR . get_include_path());
require_once('DB.php');
class AirtimeInstall
{
const CONF_DIR_BINARIES = "/usr/lib/airtime";
const CONF_DIR_WWW = "/var/www/airtime";
const CONF_DIR_LOG = "/var/log/airtime";
public static $databaseTablesCreated = false;
public static function GetAirtimeSrcDir()
{
return __DIR__."/../../airtime_mvc";
}
public static function GetUtilsSrcDir()
{
return __DIR__."/../../utils";
}
/**
* Ensures that the user is running this PHP script with root
* permissions. If not running with root permissions, causes the
* script to exit.
*/
public static function ExitIfNotRoot()
{
// Need to check that we are superuser before running this.
if(exec("whoami") != "root"){
echo "Must be root user.\n";
exit(1);
}
}
public static function GetVersionInstalled()
{
global $CC_DBC, $CC_CONFIG;
if(file_exists('/etc/airtime/airtime.conf')) {
$values = parse_ini_file('/etc/airtime/airtime.conf', true);
}
else {
echo "New Airtime Install.".PHP_EOL;
return null;
}
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
$CC_CONFIG['dsn']['hostspec'] = $values['database']['host'];
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE);
if (PEAR::isError($CC_DBC)) {
echo "New Airtime Install.".PHP_EOL;
return null;
}
else {
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
$sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version'";
$version = $CC_DBC->GetOne($sql);
if (PEAR::isError($version)) {
return null;
}
return $version;
}
}
public static function DbTableExists($p_name)
{
global $CC_DBC;
$sql = "SELECT * FROM ".$p_name;
$result = $CC_DBC->GetOne($sql);
if (PEAR::isError($result)) {
return false;
}
return true;
}
public static function InstallQuery($sql, $verbose = true)
{
global $CC_DBC;
$result = $CC_DBC->query($sql);
if (PEAR::isError($result)) {
echo "Error! ".$result->getMessage()."\n";
echo " SQL statement was:\n";
echo " ".$sql."\n\n";
} else {
if ($verbose) {
echo "done.\n";
}
}
}
public static function DbConnect($p_exitOnError = true)
{
global $CC_DBC, $CC_CONFIG;
$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE);
if (PEAR::isError($CC_DBC)) {
echo $CC_DBC->getMessage().PHP_EOL;
echo $CC_DBC->getUserInfo().PHP_EOL;
echo "Database connection problem.".PHP_EOL;
echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists".
" with corresponding permissions.".PHP_EOL;
if ($p_exitOnError) {
exit(1);
}
} else {
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
}
}
/* TODO: This function should be moved to the media-monitor
* install script. */
public static function InstallStorageDirectory()
{
global $CC_CONFIG, $CC_DBC;
echo "* Storage directory setup".PHP_EOL;
$ini = parse_ini_file(__DIR__."/airtime-install.ini");
$stor_dir = $ini["storage_dir"];
$dirs = array($stor_dir, $stor_dir."/organize");
foreach ($dirs as $dir){
if (!file_exists($dir)) {
@mkdir($dir, 02777, true);
if (file_exists($dir)) {
$rp = realpath($dir);
echo "* Directory $rp created".PHP_EOL;
} else {
echo "* Failed creating {$dir}".PHP_EOL;
exit(1);
}
}
else if (is_writable($dir)) {
$rp = realpath($dir);
echo "* Skipping directory already exists: $rp".PHP_EOL;
}
else {
$rp = realpath($dir);
echo "* Error: Directory already exists, but is not writable: $rp".PHP_EOL;
exit(1);
}
echo "* Giving Apache permission to access $rp".PHP_EOL;
$success = chgrp($rp, $CC_CONFIG["webServerUser"]);
$success = chown($rp, "pypo");
$success = chmod($rp, 02777);
}
}
public static function CreateDatabaseUser()
{
global $CC_CONFIG;
echo "* Creating Airtime database user".PHP_EOL;
$username = $CC_CONFIG['dsn']['username'];
$password = $CC_CONFIG['dsn']['password'];
$command = "echo \"CREATE USER $username ENCRYPTED PASSWORD '$password' LOGIN CREATEDB NOCREATEUSER;\" | su postgres -c psql 2>/dev/null";
@exec($command, $output, $results);
if ($results == 0) {
echo "* Database user '{$CC_CONFIG['dsn']['username']}' created.".PHP_EOL;
} else {
if (count($output) > 0) {
echo "* Could not create user '{$CC_CONFIG['dsn']['username']}': ".PHP_EOL;
echo implode(PHP_EOL, $output);
}
else {
echo "* Database user '{$CC_CONFIG['dsn']['username']}' already exists.".PHP_EOL;
}
}
}
public static function CreateDatabase()
{
global $CC_CONFIG;
echo "* Creating Airtime database".PHP_EOL;
$database = $CC_CONFIG['dsn']['database'];
$username = $CC_CONFIG['dsn']['username'];
#$command = "echo \"CREATE DATABASE $database OWNER $username\" | su postgres -c psql 2>/dev/null";
$command = "su postgres -c \"createdb $database --owner $username\"";
@exec($command, $output, $results);
if ($results == 0) {
echo "* Database '{$CC_CONFIG['dsn']['database']}' created.".PHP_EOL;
} else {
if (count($output) > 0) {
echo "* Could not create database '{$CC_CONFIG['dsn']['database']}': ".PHP_EOL;
echo implode(PHP_EOL, $output);
}
else {
echo "* Database '{$CC_CONFIG['dsn']['database']}' already exists.".PHP_EOL;
}
}
$databaseExisted = ($results != 0);
return $databaseExisted;
}
public static function InstallPostgresScriptingLanguage()
{
global $CC_DBC;
// Install postgres scripting language
$langIsInstalled = $CC_DBC->GetOne('SELECT COUNT(*) FROM pg_language WHERE lanname = \'plpgsql\'');
if ($langIsInstalled == '0') {
echo "* Installing Postgres scripting language".PHP_EOL;
$sql = "CREATE LANGUAGE 'plpgsql'";
AirtimeInstall::InstallQuery($sql, false);
} else {
echo "* Postgres scripting language already installed".PHP_EOL;
}
}
public static function CreateDatabaseTables()
{
echo "* Creating database tables".PHP_EOL;
// Put Propel sql files in Database
//$command = AirtimeInstall::CONF_DIR_WWW."/library/propel/generator/bin/propel-gen ".AirtimeInstall::CONF_DIR_WWW."/build/ insert-sql";
$command = AirtimeInstall::CONF_DIR_WWW."/library/propel/generator/bin/propel-gen ".AirtimeInstall::CONF_DIR_WWW."/build/ insert-sql 2>/dev/null";
@exec($command, $output, $results);
AirtimeInstall::$databaseTablesCreated = true;
}
public static function BypassMigrations($dir, $version)
{
$appDir = AirtimeInstall::GetAirtimeSrcDir();
$command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ".
"--configuration=$dir/../../DoctrineMigrations/migrations.xml ".
"--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ".
"--no-interaction --add migrations:version $version";
system($command);
}
public static function MigrateTablesToVersion($dir, $version)
{
$appDir = AirtimeInstall::GetAirtimeSrcDir();
$command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ".
"--configuration=$dir/../../DoctrineMigrations/migrations.xml ".
"--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ".
"--no-interaction migrations:migrate $version";
system($command);
}
public static function SetAirtimeVersion($p_version)
{
global $CC_DBC;
$sql = "DELETE FROM cc_pref WHERE keystr = 'system_version'";
$CC_DBC->query($sql);
$sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '$p_version')";
$result = $CC_DBC->query($sql);
if (PEAR::isError($result)) {
return false;
}
return true;
}
public static function SetUniqueId()
{
global $CC_DBC;
$uniqueId = md5(uniqid("", true));
$sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('uniqueId', '$uniqueId')";
$result = $CC_DBC->query($sql);
if (PEAR::isError($result)) {
return false;
}
return true;
}
public static function GetAirtimeVersion()
{
global $CC_DBC;
$sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version'";
$version = $CC_DBC->GetOne($sql);
if (PEAR::isError($version)) {
return false;
}
return $version;
}
public static function DeleteFilesRecursive($p_path)
{
$command = "rm -rf \"$p_path\"";
exec($command);
}
public static function CreateSymlinksToUtils()
{
echo "* Creating /usr/bin symlinks".PHP_EOL;
AirtimeInstall::RemoveSymlinks();
echo "* Installing airtime-import".PHP_EOL;
$dir = AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-import/airtime-import";
exec("ln -s $dir /usr/bin/airtime-import");
echo "* Installing airtime-update-db-settings".PHP_EOL;
$dir = AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-update-db-settings";
exec("ln -s $dir /usr/bin/airtime-update-db-settings");
echo "* Installing airtime-check-system".PHP_EOL;
$dir = AirtimeInstall::CONF_DIR_BINARIES."/utils/airtime-check-system";
exec("ln -s $dir /usr/bin/airtime-check-system");
}
public static function RemoveSymlinks()
{
exec("rm -f /usr/bin/airtime-import");
exec("rm -f /usr/bin/airtime-update-db-settings");
exec("rm -f /usr/bin/airtime-check-system");
}
public static function InstallPhpCode()
{
global $CC_CONFIG;
echo "* Installing PHP code to ".AirtimeInstall::CONF_DIR_WWW.PHP_EOL;
exec("mkdir -p ".AirtimeInstall::CONF_DIR_WWW);
exec("cp -R ".AirtimeInstall::GetAirtimeSrcDir()."/* ".AirtimeInstall::CONF_DIR_WWW);
}
public static function UninstallPhpCode()
{
echo "* Removing PHP code from ".AirtimeInstall::CONF_DIR_WWW.PHP_EOL;
exec('rm -rf "'.AirtimeInstall::CONF_DIR_WWW.'"');
}
public static function InstallBinaries()
{
echo "* Installing binaries to ".AirtimeInstall::CONF_DIR_BINARIES.PHP_EOL;
exec("mkdir -p ".AirtimeInstall::CONF_DIR_BINARIES);
exec("cp -R ".AirtimeInstall::GetUtilsSrcDir()." ".AirtimeInstall::CONF_DIR_BINARIES);
}
public static function UninstallBinaries()
{
echo "* Removing Airtime binaries from ".AirtimeInstall::CONF_DIR_BINARIES.PHP_EOL;
exec('rm -rf "'.AirtimeInstall::CONF_DIR_BINARIES.'"');
}
public static function DirCheck()
{
echo "Legend: \"+\" means the dir/file exists, \"-\" means that it does not.".PHP_EOL;
$dirs = array(AirtimeInstall::CONF_DIR_BINARIES,
AirtimeInstall::CONF_DIR_WWW,
AirtimeIni::CONF_FILE_AIRTIME,
AirtimeIni::CONF_FILE_LIQUIDSOAP,
AirtimeIni::CONF_FILE_PYPO,
AirtimeIni::CONF_FILE_RECORDER,
"/usr/lib/airtime/pypo",
"/usr/lib/airtime/show-recorder",
"/var/log/airtime",
"/var/log/airtime/pypo",
"/var/log/airtime/show-recorder",
"/var/tmp/airtime/pypo",
"/var/tmp/airtime/show-recorder");
foreach ($dirs as $f) {
if (file_exists($f)) {
echo "+ $f".PHP_EOL;
} else {
echo "- $f".PHP_EOL;
}
}
}
public static function CreateZendPhpLogFile(){
global $CC_CONFIG;
echo "* Creating logs directory ".AirtimeInstall::CONF_DIR_LOG.PHP_EOL;
$path = AirtimeInstall::CONF_DIR_LOG;
$file = $path.'/zendphp.log';
if (!file_exists($path)){
mkdir($path, 0755, true);
}
touch($file);
chmod($file, 0755);
chown($file, $CC_CONFIG['webServerUser']);
chgrp($file, $CC_CONFIG['webServerUser']);
}
public static function RemoveLogDirectories(){
$path = AirtimeInstall::CONF_DIR_LOG;
echo "* Removing logs directory ".$path.PHP_EOL;
exec("rm -rf \"$path\"");
}
public static function CreateCronFile(){
// Create CRON task to run every day. Time of day is initialized to a random time.
$hour = rand(0,23);
$minute = rand(0,59);
$fp = fopen('/etc/cron.d/airtime-crons','w');
fwrite($fp, "$minute $hour * * * root /usr/lib/airtime/utils/phone_home_stat\n");
fclose($fp);
}
}

View file

@ -0,0 +1,66 @@
<?php
/**
* This file is separated out so that it can be run separately for DEB package installation.
* When installing a DEB package, Postgresql may not be installed yet and thus the database
* cannot be created. So this script is run after all DEB packages have been installed.
*/
set_include_path(__DIR__.'/../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());
require_once(dirname(__FILE__).'/AirtimeIni.php');
require_once(dirname(__FILE__).'/AirtimeInstall.php');
require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/constants.php');
require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/conf.php');
echo PHP_EOL."*** Database Installation ***".PHP_EOL;
AirtimeInstall::CreateDatabaseUser();
$databaseExisted = AirtimeInstall::CreateDatabase();
AirtimeInstall::DbConnect(true);
AirtimeInstall::InstallPostgresScriptingLanguage();
if (isset($argv[1]) && $argv[1] == 'y') {
AirtimeInstall::CreateDatabaseTables();
} else if ($databaseExisted) {
//Database already exists. Ask the user how they want to
//proceed. Warn them that creating the database tables again
//will cause them to lose their old ones.
$userAnswer = "x";
while (!in_array($userAnswer, array("y", "Y", "n", "N", ""))) {
echo PHP_EOL."Database already exists. Do you want to delete all tables and recreate? (y/N)";
$userAnswer = trim(fgets(STDIN));
}
if (in_array($userAnswer, array("y", "Y"))) {
AirtimeInstall::CreateDatabaseTables();
}
} else {
//Database was just created, meaning the tables do not
//exist. Let's create them.
AirtimeInstall::CreateDatabaseTables();
}
echo "* Setting Airtime version".PHP_EOL;
AirtimeInstall::SetAirtimeVersion(AIRTIME_VERSION);
AirtimeInstall::SetUniqueId();
if (AirtimeInstall::$databaseTablesCreated) {
$ini = parse_ini_file(__DIR__."/airtime-install.ini");
$stor_dir = realpath($ini["storage_dir"])."/";
echo "* Inserting stor directory location $stor_dir into music_dirs table".PHP_EOL;
$sql = "INSERT INTO cc_music_dirs (directory, type) VALUES ('$stor_dir', 'stor')";
$result = $CC_DBC->query($sql);
if (PEAR::isError($result)) {
echo "* Failed inserting {$stor_dir} in cc_music_dirs".PHP_EOL;
echo "* Message {$result->getMessage()}".PHP_EOL;
exit(1);
}
}

View file

@ -0,0 +1 @@
storage_dir = /srv/airtime/stor/

View file

@ -0,0 +1,148 @@
<?php
/**
* @package Airtime
* @copyright 2011 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*
* Checks if a previous version of Airtime is currently installed and upgrades Airtime if so.
* Performs a new install (new configs, database install) if a version of Airtime is not found.
* If the current version is found to be installed the user is presented with the help menu and can
* choose -r to reinstall.
*/
set_include_path(__DIR__.'/../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());
require_once(dirname(__FILE__).'/AirtimeIni.php');
require_once(dirname(__FILE__).'/AirtimeInstall.php');
require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/constants.php');
AirtimeInstall::ExitIfNotRoot();
$newInstall = false;
$version = AirtimeInstall::GetVersionInstalled();
require_once('Zend/Loader/Autoloader.php');
$autoloader = Zend_Loader_Autoloader::getInstance();
function printUsage($opts)
{
$msg = $opts->getUsageMessage();
echo PHP_EOL."Usage: airtime-install [options]";
echo substr($msg, strpos($msg, "\n")).PHP_EOL;
}
try {
$opts = new Zend_Console_Getopt(
array(
'help|h' => 'Displays usage information.',
'overwrite|o' => 'Overwrite any existing config files.',
'preserve|p' => 'Keep any existing config files.',
'no-db|n' => 'Turn off database install.',
'reinstall|r' => 'Force a fresh install of this Airtime Version'
)
);
$opts->parse();
}
catch (Zend_Console_Getopt_Exception $e) {
print $e->getMessage() .PHP_EOL;
printUsage($opts);
exit(1);
}
if (isset($opts->h)) {
printUsage($opts);
exit(1);
}
// The current version is already installed.
if (isset($version) && ($version != false) && ($version == AIRTIME_VERSION) && !isset($opts->r)) {
echo "Airtime $version is already installed.".PHP_EOL;
printUsage($opts);
exit(1);
}
// A previous version exists - if so, upgrade.
if (isset($version) && ($version != false) && ($version < AIRTIME_VERSION) && !isset($opts->r)) {
echo "Airtime version $version found.".PHP_EOL;
require_once("airtime-upgrade.php");
//Make sure to exit with non-zero error code so that airtime-install
//shell script does not continue with installing pypo, show-recorder,
//media-monitor etc.
exit(2);
}
// -------------------------------------------------------------------------
// The only way we get here is if we are doing a new install or a reinstall.
// -------------------------------------------------------------------------
if(is_null($version)) {
$newInstall = true;
}
$db_install = true;
if (is_null($opts->r) && isset($opts->n)) {
$db_install = false;
}
$overwrite = false;
if (isset($opts->o) || $newInstall == true) {
$overwrite = true;
}
else if (!isset($opts->p) && !isset($opts->o) && isset($opts->r)) {
if (AirtimeIni::IniFilesExist()) {
$userAnswer = "x";
while (!in_array($userAnswer, array("o", "O", "p", "P", ""))) {
echo PHP_EOL."You have existing config files. Do you want to (O)verwrite them, or (P)reserve them? (o/P) ";
$userAnswer = trim(fgets(STDIN));
}
if (in_array($userAnswer, array("o", "O"))) {
$overwrite = true;
}
}
else {
$overwrite = true;
}
}
if ($overwrite) {
echo "* Creating INI files".PHP_EOL;
AirtimeIni::CreateIniFiles();
}
AirtimeIni::CreateMonitFile();
AirtimeInstall::InstallPhpCode();
AirtimeInstall::InstallBinaries();
if ($overwrite) {
echo "* Initializing INI files".PHP_EOL;
AirtimeIni::UpdateIniFiles();
}
// Update the build.properties file to point to the correct directory.
AirtimeIni::UpdateIniValue(AirtimeInstall::CONF_DIR_WWW.'/build/build.properties', 'project.home', AirtimeInstall::CONF_DIR_WWW);
require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/conf.php');
echo "* Airtime Version: ".AIRTIME_VERSION.PHP_EOL;
AirtimeInstall::InstallStorageDirectory();
if ($db_install) {
if($newInstall) {
// This is called with "system" so that we can pass in a parameter. See the file itself
// for why we need to do this.
system('php '.__DIR__.'/airtime-db-install.php y');
AirtimeInstall::DbConnect(true);
} else {
require_once('airtime-db-install.php');
}
}
AirtimeInstall::CreateSymlinksToUtils();
AirtimeInstall::CreateZendPhpLogFile();
AirtimeInstall::CreateCronFile();
/* FINISHED AIRTIME PHP INSTALLER */

View file

@ -0,0 +1,87 @@
<?php
/**
* @package Airtime
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
require_once(dirname(__FILE__).'/AirtimeIni.php');
require_once(dirname(__FILE__).'/AirtimeInstall.php');
// Need to check that we are superuser before running this.
AirtimeInstall::ExitIfNotRoot();
if (!file_exists(AirtimeIni::CONF_FILE_AIRTIME)) {
echo PHP_EOL."Airtime config file '".AirtimeIni::CONF_FILE_AIRTIME."' does not exist.".PHP_EOL;
echo "Most likely this means that Airtime is not installed, so there is nothing to do.".PHP_EOL.PHP_EOL;
exit();
}
require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/constants.php');
require_once(AirtimeInstall::GetAirtimeSrcDir().'/application/configs/conf.php');
echo PHP_EOL;
echo "* Uninstalling Airtime ".AIRTIME_VERSION.PHP_EOL;
AirtimeInstall::UninstallPhpCode();
//------------------------------------------------------------------------
// Delete the database
// Note: Do not put a call to AirtimeInstall::DbConnect()
// before this function, even if you called $CC_DBC->disconnect(), there will
// still be a connection to the database and you wont be able to delete it.
//------------------------------------------------------------------------
echo " * Dropping the database '".$CC_CONFIG['dsn']['database']."'...".PHP_EOL;
// check if DB exists
$command = "echo \"DROP DATABASE IF EXISTS ".$CC_CONFIG['dsn']['database']."\" | su postgres -c psql";
@exec($command, $output, $dbDeleteFailed);
//------------------------------------------------------------------------
// Delete DB tables
// We do this if dropping the database fails above.
//------------------------------------------------------------------------
if ($dbDeleteFailed) {
echo " * Couldn't delete the database, so deleting all the DB tables...".PHP_EOL;
AirtimeInstall::DbConnect(false);
if (!PEAR::isError($CC_DBC)) {
$sql = "select * from pg_tables where tableowner = 'airtime'";
$rows = $CC_DBC->GetAll($sql);
if (PEAR::isError($rows)) {
$rows = array();
}
foreach ($rows as $row) {
$tablename = $row["tablename"];
echo " * Removing database table $tablename...";
if (AirtimeInstall::DbTableExists($tablename)){
$sql = "DROP TABLE $tablename CASCADE";
AirtimeInstall::InstallQuery($sql, false);
$CC_DBC->dropSequence($tablename."_id");
}
echo "done.".PHP_EOL;
}
}
}
//------------------------------------------------------------------------
// Delete the user
//------------------------------------------------------------------------
echo " * Deleting database user '{$CC_CONFIG['dsn']['username']}'...".PHP_EOL;
$command = "echo \"DROP USER IF EXISTS {$CC_CONFIG['dsn']['username']}\" | su postgres -c psql >/dev/null 2>&1";
@exec($command, $output, $results);
if ($results == 0) {
echo " * User '{$CC_CONFIG['dsn']['username']}' deleted.".PHP_EOL;
} else {
echo " * Nothing to delete.".PHP_EOL;
}
AirtimeInstall::RemoveSymlinks();
AirtimeInstall::UninstallBinaries();
AirtimeInstall::RemoveLogDirectories();
AirtimeIni::RemoveMonitFile();
@unlink('/etc/cron.d/airtime-crons');
/* FINISHED AIRTIME PHP UNINSTALLER */

View file

@ -0,0 +1,114 @@
<?php
/**
* @package Airtime
* @subpackage StorageServer
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
//Pear classes.
set_include_path(__DIR__.'/../../airtime_mvc/library/pear' . PATH_SEPARATOR . get_include_path());
require_once('DB.php');
require_once(__DIR__.'/../../airtime_mvc/application/configs/constants.php');
require_once(dirname(__FILE__).'/AirtimeIni.php');
if(exec("whoami") != "root"){
echo "Must be root user.\n";
exit(1);
}
global $CC_DBC, $CC_CONFIG;
$values = parse_ini_file('/etc/airtime/airtime.conf', true);
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
$CC_CONFIG['dsn']['hostspec'] = $values['database']['host'];
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE);
if (PEAR::isError($CC_DBC)) {
echo $CC_DBC->getMessage().PHP_EOL;
echo $CC_DBC->getUserInfo().PHP_EOL;
echo "Database connection problem.".PHP_EOL;
echo "Check if database '{$CC_CONFIG['dsn']['database']}' exists".
" with corresponding permissions.".PHP_EOL;
exit(1);
} else {
echo "* Connected to database".PHP_EOL;
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
}
$sql = "SELECT valstr FROM cc_pref WHERE keystr = 'system_version'";
$version = $CC_DBC->GetOne($sql);
if (PEAR::isError($version)) {
$version = false;
}
if (!$version){
$sql = "SELECT * FROM ".$p_name;
$result = $CC_DBC->GetOne($sql);
if (!PEAR::isError($result)) {
$version = "1.7.0";
echo "Airtime Version: ".$version." ".PHP_EOL;
}
else {
$version = "1.6";
echo "Airtime Version: ".$version." ".PHP_EOL;
}
}
echo "******************************** Update Begin *********************************".PHP_EOL;
//convert strings like 1.9.0-devel to 1.9.0
$version = substr($version, 0, 5);
if (strcmp($version, "1.7.0") < 0){
system("php ".__DIR__."/../upgrades/airtime-1.7.0/airtime-upgrade.php");
}
if (strcmp($version, "1.8.0") < 0){
system("php ".__DIR__."/../upgrades/airtime-1.8.0/airtime-upgrade.php");
}
if (strcmp($version, "1.8.1") < 0){
system("php ".__DIR__."/../upgrades/airtime-1.8.1/airtime-upgrade.php");
}
if (strcmp($version, "1.8.2") < 0){
system("php ".__DIR__."/../upgrades/airtime-1.8.2/airtime-upgrade.php");
}
if (strcmp($version, "1.9.0") < 0){
system("php ".__DIR__."/../upgrades/airtime-1.9.0/airtime-upgrade.php");
}
//set the new version in the database.
$sql = "DELETE FROM cc_pref WHERE keystr = 'system_version'";
$CC_DBC->query($sql);
$newVersion = AIRTIME_VERSION;
$sql = "INSERT INTO cc_pref (keystr, valstr) VALUES ('system_version', '$newVersion')";
$CC_DBC->query($sql);
echo PHP_EOL."*** Updating Api Client ***".PHP_EOL;
passthru("python ".__DIR__."/../../python_apps/api_clients/install/api_client_install.py");
echo PHP_EOL."*** Updating Pypo ***".PHP_EOL;
passthru("python ".__DIR__."/../../python_apps/pypo/install/pypo-install.py");
echo PHP_EOL."*** Updating Recorder ***".PHP_EOL;
passthru("python ".__DIR__."/../../python_apps/show-recorder/install/recorder-install.py");
echo PHP_EOL."*** Updating Media Monitor ***".PHP_EOL;
passthru("python ".__DIR__."/../../python_apps/media-monitor/install/media-monitor-install.py");
AirtimeIni::CreateMonitFile();
sleep(4);
passthru("airtime-check-system");
echo "******************************* Update Complete *******************************".PHP_EOL;

View file

@ -0,0 +1,23 @@
<?php
/**
* @package Airtime
* @subpackage StorageServer
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
require_once(dirname(__FILE__).'/../../include/AirtimeIni.php');
require_once(dirname(__FILE__).'/../../include/AirtimeInstall.php');
AirtimeIni::CreateIniFiles();
AirtimeIni::UpdateIniFiles();
echo PHP_EOL."*** Updating Database Tables ***".PHP_EOL;
AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110402164819');
echo PHP_EOL."*** Updating Pypo ***".PHP_EOL;
system("python ".__DIR__."/../../../python_apps/pypo/install/pypo-install.py");
echo PHP_EOL."*** Recorder Installation ***".PHP_EOL;
system("python ".__DIR__."/../../../python_apps/show-recorder/install/recorder-install.py");

View file

@ -0,0 +1,74 @@
<?php
/**
* @package Airtime
* @subpackage StorageServer
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
set_include_path(__DIR__.'/../../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());
require_once __DIR__.'/../../../airtime_mvc/application/configs/conf.php';
require_once(dirname(__FILE__).'/../../include/AirtimeInstall.php');
require_once(dirname(__FILE__).'/../../include/AirtimeIni.php');
AirtimeInstall::DbConnect(true);
echo PHP_EOL."*** Updating Database Tables ***".PHP_EOL;
if(AirtimeInstall::DbTableExists('doctrine_migration_versions') === false) {
$migrations = array('20110312121200', '20110331111708', '20110402164819');
foreach($migrations as $migration) {
AirtimeInstall::BypassMigrations(__DIR__, $migration);
}
}
AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110406182005');
//setting data for new aggregate show length column.
$sql = "SELECT id FROM cc_show_instances";
$show_instances = $CC_DBC->GetAll($sql);
foreach ($show_instances as $show_instance) {
$sql = "UPDATE cc_show_instances SET time_filled = (SELECT SUM(clip_length) FROM cc_schedule WHERE instance_id = {$show_instance["id"]}) WHERE id = {$show_instance["id"]}";
$CC_DBC->query($sql);
}
//end setting data for new aggregate show length column.
exec("rm -fr /opt/pypo");
exec("rm -fr /opt/recorder");
const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf";
const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg";
const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg";
const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg";
$configFiles = array(AirtimeIni::CONF_FILE_AIRTIME,
AirtimeIni::CONF_FILE_PYPO,
AirtimeIni::CONF_FILE_RECORDER,
AirtimeIni::CONF_FILE_LIQUIDSOAP);
foreach ($configFiles as $conf) {
if (file_exists($conf)) {
echo "Backing up $conf to $conf.bak".PHP_EOL;
exec("cp $conf $conf.bak");
}
}
echo "* Creating INI files".PHP_EOL;
AirtimeIni::CreateIniFiles();
AirtimeInstall::InstallPhpCode();
AirtimeInstall::InstallBinaries();
echo "* Initializing INI files".PHP_EOL;
AirtimeIni::UpdateIniFiles();
global $CC_CONFIG;
$CC_CONFIG = Config::loadConfig($CC_CONFIG);
echo "* Creating default storage directory".PHP_EOL;
AirtimeInstall::InstallStorageDirectory();
$ini = parse_ini_file(__DIR__."/../../include/airtime-install.ini");
$stor_dir = $ini["storage_dir"];
AirtimeInstall::ChangeDirOwnerToWebserver($stor_dir);
AirtimeInstall::CreateSymlinksToUtils();

View file

@ -0,0 +1,251 @@
<?php
/**
* @package Airtime
* @subpackage StorageServer
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
set_include_path(__DIR__.'/../../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());
const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf";
const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg";
const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg";
const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg";
const CONF_DIR_BINARIES = "/usr/lib/airtime";
const CONF_DIR_STORAGE = "/srv/airtime";
const CONF_DIR_WWW = "/var/www/airtime";
const CONF_DIR_LOG = "/var/log/airtime";
global $AIRTIME_SRC;
global $AIRTIME_UTILS;
global $AIRTIME_PYTHON_APPS;
global $CC_CONFIG;
$AIRTIME_SRC = __DIR__.'/../../../airtime_mvc';
$AIRTIME_UTILS = __DIR__.'/../../../utils';
$AIRTIME_PYTHON_APPS = __DIR__.'/../../../python_apps';
$configFiles = array(CONF_FILE_AIRTIME,
CONF_FILE_PYPO,
CONF_FILE_RECORDER,
CONF_FILE_LIQUIDSOAP);
$CC_CONFIG = array(
// prefix for table names in the database
'tblNamePrefix' => 'cc_',
/* ================================================ storage configuration */
'soundcloud-client-id' => '2CLCxcSXYzx7QhhPVHN4A',
'soundcloud-client-secret' => 'pZ7beWmF06epXLHVUP1ufOg2oEnIt9XhE8l8xt0bBs',
"rootDir" => __DIR__."/../..",
'pearPath' => dirname(__FILE__).'/../../library/pear',
'zendPath' => dirname(__FILE__).'/../../library/Zend',
'phingPath' => dirname(__FILE__).'/../../library/phing'
);
//$CC_CONFIG = Config::loadConfig($CC_CONFIG);
// Add database table names
$CC_CONFIG['playListTable'] = $CC_CONFIG['tblNamePrefix'].'playlist';
$CC_CONFIG['playListContentsTable'] = $CC_CONFIG['tblNamePrefix'].'playlistcontents';
$CC_CONFIG['filesTable'] = $CC_CONFIG['tblNamePrefix'].'files';
$CC_CONFIG['accessTable'] = $CC_CONFIG['tblNamePrefix'].'access';
$CC_CONFIG['permTable'] = $CC_CONFIG['tblNamePrefix'].'perms';
$CC_CONFIG['sessTable'] = $CC_CONFIG['tblNamePrefix'].'sess';
$CC_CONFIG['subjTable'] = $CC_CONFIG['tblNamePrefix'].'subjs';
$CC_CONFIG['smembTable'] = $CC_CONFIG['tblNamePrefix'].'smemb';
$CC_CONFIG['prefTable'] = $CC_CONFIG['tblNamePrefix'].'pref';
$CC_CONFIG['scheduleTable'] = $CC_CONFIG['tblNamePrefix'].'schedule';
$CC_CONFIG['playListTimeView'] = $CC_CONFIG['tblNamePrefix'].'playlisttimes';
$CC_CONFIG['showSchedule'] = $CC_CONFIG['tblNamePrefix'].'show_schedule';
$CC_CONFIG['showDays'] = $CC_CONFIG['tblNamePrefix'].'show_days';
$CC_CONFIG['showTable'] = $CC_CONFIG['tblNamePrefix'].'show';
$CC_CONFIG['showInstances'] = $CC_CONFIG['tblNamePrefix'].'show_instances';
$CC_CONFIG['playListSequence'] = $CC_CONFIG['playListTable'].'_id';
$CC_CONFIG['filesSequence'] = $CC_CONFIG['filesTable'].'_id';
$CC_CONFIG['prefSequence'] = $CC_CONFIG['prefTable'].'_id';
$CC_CONFIG['permSequence'] = $CC_CONFIG['permTable'].'_id';
$CC_CONFIG['subjSequence'] = $CC_CONFIG['subjTable'].'_id';
$CC_CONFIG['smembSequence'] = $CC_CONFIG['smembTable'].'_id';
// Add libs to the PHP path
$old_include_path = get_include_path();
set_include_path('.'.PATH_SEPARATOR.$CC_CONFIG['pearPath']
.PATH_SEPARATOR.$CC_CONFIG['zendPath']
.PATH_SEPARATOR.$old_include_path);
function LoadConfig($CC_CONFIG) {
$values = parse_ini_file(CONF_FILE_AIRTIME, true);
// Name of the web server user
$CC_CONFIG['webServerUser'] = $values['general']['web_server_user'];
$CC_CONFIG['phpDir'] = $values['general']['airtime_dir'];
$CC_CONFIG['rabbitmq'] = $values['rabbitmq'];
//$CC_CONFIG['baseUrl'] = $values['general']['base_url'];
//$CC_CONFIG['basePort'] = $values['general']['base_port'];
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
$CC_CONFIG['dsn']['hostspec'] = $values['database']['host'];
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_CONFIG['apiKey'] = array($values['general']['api_key']);
$CC_CONFIG['soundcloud-connection-retries'] = $values['soundcloud']['connection_retries'];
$CC_CONFIG['soundcloud-connection-wait'] = $values['soundcloud']['time_between_retries'];
return $CC_CONFIG;
}
/**
* This function creates the /etc/airtime configuration folder
* and copies the default config files to it.
*/
function CreateIniFiles()
{
global $AIRTIME_SRC;
global $AIRTIME_PYTHON_APPS;
if (!file_exists("/etc/airtime/")){
if (!mkdir("/etc/airtime/", 0755, true)){
echo "Could not create /etc/airtime/ directory. Exiting.";
exit(1);
}
}
if (!copy($AIRTIME_SRC."/build/airtime.conf", CONF_FILE_AIRTIME)){
echo "Could not copy airtime.conf to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/pypo/pypo.cfg", CONF_FILE_PYPO)){
echo "Could not copy pypo.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/show-recorder/recorder.cfg", CONF_FILE_RECORDER)){
echo "Could not copy recorder.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/pypo/liquidsoap_scripts/liquidsoap.cfg", CONF_FILE_LIQUIDSOAP)){
echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting.";
exit(1);
}
}
function ReadPythonConfig($p_filename)
{
$values = array();
$lines = file($p_filename);
$n=count($lines);
for ($i=0; $i<$n; $i++) {
if (strlen($lines[$i]) && !in_array(substr($lines[$i], 0, 1), array('#', PHP_EOL))){
$info = explode("=", $lines[$i]);
$values[trim($info[0])] = trim($info[1]);
}
}
return $values;
}
function UpdateIniValue($p_filename, $p_property, $p_value)
{
$lines = file($p_filename);
$n=count($lines);
foreach ($lines as &$line) {
if ($line[0] != "#"){
$key_value = split("=", $line);
$key = trim($key_value[0]);
if ($key == $p_property){
$line = "$p_property = $p_value".PHP_EOL;
}
}
}
$fp=fopen($p_filename, 'w');
for($i=0; $i<$n; $i++){
fwrite($fp, $lines[$i]);
}
fclose($fp);
}
function MergeConfigFiles($configFiles, $suffix)
{
foreach ($configFiles as $conf) {
if (file_exists("$conf$suffix.bak")) {
if($conf === CONF_FILE_AIRTIME) {
// Parse with sections
$newSettings = parse_ini_file($conf, true);
$oldSettings = parse_ini_file("$conf$suffix.bak", true);
}
else {
$newSettings = ReadPythonConfig($conf);
$oldSettings = ReadPythonConfig("$conf$suffix.bak");
}
$settings = array_keys($newSettings);
foreach($settings as $section) {
if(isset($oldSettings[$section])) {
if(is_array($oldSettings[$section])) {
$sectionKeys = array_keys($newSettings[$section]);
foreach($sectionKeys as $sectionKey) {
if(isset($oldSettings[$section][$sectionKey])) {
UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]);
}
}
}
else {
UpdateIniValue($conf, $section, $oldSettings[$section]);
}
}
}
}
}
}
function InstallPhpCode()
{
global $CC_CONFIG;
global $AIRTIME_SRC;
echo "* Installing PHP code to ".$CC_CONFIG['phpDir'].PHP_EOL;
exec("mkdir -p ".$CC_CONFIG['phpDir']);
exec("cp -R ".$AIRTIME_SRC."/* ".$CC_CONFIG['phpDir']);
}
function InstallBinaries()
{
global $AIRTIME_UTILS;
echo "* Installing binaries to ".CONF_DIR_BINARIES.PHP_EOL;
exec("mkdir -p ".CONF_DIR_BINARIES);
exec("cp -R ".$AIRTIME_UTILS." ".CONF_DIR_BINARIES);
}
// Backup the config files
$suffix = date("Ymdhis")."-1.8.1";
foreach ($configFiles as $conf) {
if (file_exists($conf)) {
echo "Backing up $conf to $conf$suffix.bak".PHP_EOL;
exec("cp $conf $conf$suffix.bak");
}
}
CreateIniFiles();
echo "* Initializing INI files".PHP_EOL;
MergeConfigFiles($configFiles, $suffix);
$CC_CONFIG = LoadConfig($CC_CONFIG);
InstallPhpCode();
InstallBinaries();

View file

@ -0,0 +1,249 @@
<?php
/**
* @package Airtime
* @subpackage StorageServer
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
set_include_path(__DIR__.'/../../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());
const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf";
const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg";
const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg";
const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg";
const CONF_DIR_BINARIES = "/usr/lib/airtime";
const CONF_DIR_STORAGE = "/srv/airtime";
const CONF_DIR_WWW = "/var/www/airtime";
const CONF_DIR_LOG = "/var/log/airtime";
global $AIRTIME_SRC;
global $AIRTIME_UTILS;
global $AIRTIME_PYTHON_APPS;
global $CC_CONFIG;
$AIRTIME_SRC = __DIR__.'/../../../airtime_mvc';
$AIRTIME_UTILS = __DIR__.'/../../../utils';
$AIRTIME_PYTHON_APPS = __DIR__.'/../../../python_apps';
$configFiles = array(CONF_FILE_AIRTIME,
CONF_FILE_PYPO,
CONF_FILE_RECORDER,
CONF_FILE_LIQUIDSOAP);
$CC_CONFIG = array(
// prefix for table names in the database
'tblNamePrefix' => 'cc_',
/* ================================================ storage configuration */
'soundcloud-client-id' => '2CLCxcSXYzx7QhhPVHN4A',
'soundcloud-client-secret' => 'pZ7beWmF06epXLHVUP1ufOg2oEnIt9XhE8l8xt0bBs',
"rootDir" => __DIR__."/../..",
'pearPath' => dirname(__FILE__).'/../../library/pear',
'zendPath' => dirname(__FILE__).'/../../library/Zend',
'phingPath' => dirname(__FILE__).'/../../library/phing'
);
//$CC_CONFIG = Config::loadConfig($CC_CONFIG);
// Add database table names
$CC_CONFIG['playListTable'] = $CC_CONFIG['tblNamePrefix'].'playlist';
$CC_CONFIG['playListContentsTable'] = $CC_CONFIG['tblNamePrefix'].'playlistcontents';
$CC_CONFIG['filesTable'] = $CC_CONFIG['tblNamePrefix'].'files';
$CC_CONFIG['accessTable'] = $CC_CONFIG['tblNamePrefix'].'access';
$CC_CONFIG['permTable'] = $CC_CONFIG['tblNamePrefix'].'perms';
$CC_CONFIG['sessTable'] = $CC_CONFIG['tblNamePrefix'].'sess';
$CC_CONFIG['subjTable'] = $CC_CONFIG['tblNamePrefix'].'subjs';
$CC_CONFIG['smembTable'] = $CC_CONFIG['tblNamePrefix'].'smemb';
$CC_CONFIG['prefTable'] = $CC_CONFIG['tblNamePrefix'].'pref';
$CC_CONFIG['scheduleTable'] = $CC_CONFIG['tblNamePrefix'].'schedule';
$CC_CONFIG['playListTimeView'] = $CC_CONFIG['tblNamePrefix'].'playlisttimes';
$CC_CONFIG['showSchedule'] = $CC_CONFIG['tblNamePrefix'].'show_schedule';
$CC_CONFIG['showDays'] = $CC_CONFIG['tblNamePrefix'].'show_days';
$CC_CONFIG['showTable'] = $CC_CONFIG['tblNamePrefix'].'show';
$CC_CONFIG['showInstances'] = $CC_CONFIG['tblNamePrefix'].'show_instances';
$CC_CONFIG['playListSequence'] = $CC_CONFIG['playListTable'].'_id';
$CC_CONFIG['filesSequence'] = $CC_CONFIG['filesTable'].'_id';
$CC_CONFIG['prefSequence'] = $CC_CONFIG['prefTable'].'_id';
$CC_CONFIG['permSequence'] = $CC_CONFIG['permTable'].'_id';
$CC_CONFIG['subjSequence'] = $CC_CONFIG['subjTable'].'_id';
$CC_CONFIG['smembSequence'] = $CC_CONFIG['smembTable'].'_id';
// Add libs to the PHP path
$old_include_path = get_include_path();
set_include_path('.'.PATH_SEPARATOR.$CC_CONFIG['pearPath']
.PATH_SEPARATOR.$CC_CONFIG['zendPath']
.PATH_SEPARATOR.$old_include_path);
function LoadConfig($CC_CONFIG) {
$values = parse_ini_file(CONF_FILE_AIRTIME, true);
// Name of the web server user
$CC_CONFIG['webServerUser'] = $values['general']['web_server_user'];
$CC_CONFIG['phpDir'] = $values['general']['airtime_dir'];
$CC_CONFIG['rabbitmq'] = $values['rabbitmq'];
$CC_CONFIG['baseUrl'] = $values['general']['base_url'];
$CC_CONFIG['basePort'] = $values['general']['base_port'];
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
$CC_CONFIG['dsn']['hostspec'] = $values['database']['host'];
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_CONFIG['apiKey'] = array($values['general']['api_key']);
$CC_CONFIG['soundcloud-connection-retries'] = $values['soundcloud']['connection_retries'];
$CC_CONFIG['soundcloud-connection-wait'] = $values['soundcloud']['time_between_retries'];
return $CC_CONFIG;
}
/**
* This function creates the /etc/airtime configuration folder
* and copies the default config files to it.
*/
function CreateIniFiles()
{
global $AIRTIME_SRC;
global $AIRTIME_PYTHON_APPS;
if (!file_exists("/etc/airtime/")){
if (!mkdir("/etc/airtime/", 0755, true)){
echo "Could not create /etc/airtime/ directory. Exiting.";
exit(1);
}
}
if (!copy($AIRTIME_SRC."/build/airtime.conf", CONF_FILE_AIRTIME)){
echo "Could not copy airtime.conf to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/pypo/pypo.cfg", CONF_FILE_PYPO)){
echo "Could not copy pypo.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/show-recorder/recorder.cfg", CONF_FILE_RECORDER)){
echo "Could not copy recorder.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/pypo/liquidsoap_scripts/liquidsoap.cfg", CONF_FILE_LIQUIDSOAP)){
echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting.";
exit(1);
}
}
function ReadPythonConfig($p_filename)
{
$values = array();
$lines = file($p_filename);
$n=count($lines);
for ($i=0; $i<$n; $i++) {
if (strlen($lines[$i]) && !in_array(substr($lines[$i], 0, 1), array('#', PHP_EOL))){
$info = explode("=", $lines[$i]);
$values[trim($info[0])] = trim($info[1]);
}
}
return $values;
}
function UpdateIniValue($p_filename, $p_property, $p_value)
{
$lines = file($p_filename);
$n=count($lines);
foreach ($lines as &$line) {
if ($line[0] != "#"){
$key_value = split("=", $line);
$key = trim($key_value[0]);
if ($key == $p_property){
$line = "$p_property = $p_value".PHP_EOL;
}
}
}
$fp=fopen($p_filename, 'w');
for($i=0; $i<$n; $i++){
fwrite($fp, $lines[$i]);
}
fclose($fp);
}
function MergeConfigFiles($configFiles, $suffix)
{
foreach ($configFiles as $conf) {
if (file_exists("$conf$suffix.bak")) {
if($conf === CONF_FILE_AIRTIME) {
// Parse with sections
$newSettings = parse_ini_file($conf, true);
$oldSettings = parse_ini_file("$conf$suffix.bak", true);
}
else {
$newSettings = ReadPythonConfig($conf);
$oldSettings = ReadPythonConfig("$conf$suffix.bak");
}
$settings = array_keys($newSettings);
foreach($settings as $section) {
if(isset($oldSettings[$section])) {
if(is_array($oldSettings[$section])) {
$sectionKeys = array_keys($newSettings[$section]);
foreach($sectionKeys as $sectionKey) {
if(isset($oldSettings[$section][$sectionKey])) {
UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]);
}
}
}
else {
UpdateIniValue($conf, $section, $oldSettings[$section]);
}
}
}
}
}
}
function InstallPhpCode()
{
global $CC_CONFIG;
global $AIRTIME_SRC;
echo "* Installing PHP code to ".$CC_CONFIG['phpDir'].PHP_EOL;
exec("mkdir -p ".$CC_CONFIG['phpDir']);
exec("cp -R ".$AIRTIME_SRC."/* ".$CC_CONFIG['phpDir']);
}
function InstallBinaries()
{
global $AIRTIME_UTILS;
echo "* Installing binaries to ".CONF_DIR_BINARIES.PHP_EOL;
exec("mkdir -p ".CONF_DIR_BINARIES);
exec("cp -R ".$AIRTIME_UTILS." ".CONF_DIR_BINARIES);
}
$suffix = date("Ymdhis")."-1.8.2";
foreach ($configFiles as $conf) {
if (file_exists($conf)) {
echo "Backing up $conf to $conf$suffix.bak".PHP_EOL;
exec("cp $conf $conf$suffix.bak");
}
}
CreateIniFiles();
echo "* Initializing INI files".PHP_EOL;
MergeConfigFiles($configFiles, $suffix);
$CC_CONFIG = LoadConfig($CC_CONFIG);
InstallPhpCode();
InstallBinaries();

View file

@ -0,0 +1,668 @@
<?php
/**
* @package Airtime
* @subpackage StorageServer
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
set_include_path(__DIR__.'/../../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());
set_include_path(__DIR__.'/../../../airtime_mvc/library/pear' . PATH_SEPARATOR . get_include_path());
require_once 'conf.php';
require_once 'DB.php';
const CONF_DIR_BINARIES = "/usr/lib/airtime";
class AirtimeInstall{
const CONF_DIR_LOG = "/var/log/airtime";
public static function CreateZendPhpLogFile(){
global $CC_CONFIG;
echo "* Creating logs directory ".AirtimeInstall::CONF_DIR_LOG.PHP_EOL;
$path = AirtimeInstall::CONF_DIR_LOG;
$file = $path.'/zendphp.log';
if (!file_exists($path)){
mkdir($path, 0755, true);
}
touch($file);
chmod($file, 0755);
chown($file, $CC_CONFIG['webServerUser']);
chgrp($file, $CC_CONFIG['webServerUser']);
}
public static function DbTableExists($p_name)
{
global $CC_DBC;
$sql = "SELECT * FROM ".$p_name;
$result = $CC_DBC->GetOne($sql);
if (PEAR::isError($result)) {
return false;
}
return true;
}
public static function BypassMigrations($dir, $version)
{
$appDir = AirtimeInstall::GetAirtimeSrcDir();
$command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ".
"--configuration=$dir/../../DoctrineMigrations/migrations.xml ".
"--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ".
"--no-interaction --add migrations:version $version";
system($command);
}
public static function MigrateTablesToVersion($dir, $version)
{
$appDir = AirtimeInstall::GetAirtimeSrcDir();
$command = "php $appDir/library/doctrine/migrations/doctrine-migrations.phar ".
"--configuration=$dir/../../DoctrineMigrations/migrations.xml ".
"--db-configuration=$appDir/library/doctrine/migrations/migrations-db.php ".
"--no-interaction migrations:migrate $version";
system($command);
}
public static function CreateCronFile(){
// Create CRON task to run every day. Time of day is initialized to a random time.
$hour = rand(0,23);
$minute = rand(0,59);
$fp = fopen('/etc/cron.d/airtime-crons','w');
fwrite($fp, "$minute $hour * * * root /usr/lib/airtime/utils/phone_home_stat\n");
fclose($fp);
}
public static function GetAirtimeSrcDir()
{
return __DIR__."/../../../airtime_mvc";
}
public static function InsertCountryDataIntoDatabase(){
$sql = "INSERT INTO cc_country (isocode, name) VALUES ('AFG', 'Afghanistan ');
INSERT INTO cc_country (isocode, name) VALUES ('ALA', 'Åland Islands');
INSERT INTO cc_country (isocode, name) VALUES ('ALB', 'Albania ');
INSERT INTO cc_country (isocode, name) VALUES ('DZA', 'Algeria ');
INSERT INTO cc_country (isocode, name) VALUES ('ASM', 'American Samoa ');
INSERT INTO cc_country (isocode, name) VALUES ('AND', 'Andorra ');
INSERT INTO cc_country (isocode, name) VALUES ('AGO', 'Angola ');
INSERT INTO cc_country (isocode, name) VALUES ('AIA', 'Anguilla ');
INSERT INTO cc_country (isocode, name) VALUES ('ATG', 'Antigua and Barbuda ');
INSERT INTO cc_country (isocode, name) VALUES ('ARG', 'Argentina ');
INSERT INTO cc_country (isocode, name) VALUES ('ARM', 'Armenia ');
INSERT INTO cc_country (isocode, name) VALUES ('ABW', 'Aruba ');
INSERT INTO cc_country (isocode, name) VALUES ('AUS', 'Australia ');
INSERT INTO cc_country (isocode, name) VALUES ('AUT', 'Austria ');
INSERT INTO cc_country (isocode, name) VALUES ('AZE', 'Azerbaijan ');
INSERT INTO cc_country (isocode, name) VALUES ('BHS', 'Bahamas ');
INSERT INTO cc_country (isocode, name) VALUES ('BHR', 'Bahrain ');
INSERT INTO cc_country (isocode, name) VALUES ('BGD', 'Bangladesh ');
INSERT INTO cc_country (isocode, name) VALUES ('BRB', 'Barbados ');
INSERT INTO cc_country (isocode, name) VALUES ('BLR', 'Belarus ');
INSERT INTO cc_country (isocode, name) VALUES ('BEL', 'Belgium ');
INSERT INTO cc_country (isocode, name) VALUES ('BLZ', 'Belize ');
INSERT INTO cc_country (isocode, name) VALUES ('BEN', 'Benin ');
INSERT INTO cc_country (isocode, name) VALUES ('BMU', 'Bermuda ');
INSERT INTO cc_country (isocode, name) VALUES ('BTN', 'Bhutan ');
INSERT INTO cc_country (isocode, name) VALUES ('BOL', 'Bolivia (Plurinational State of) ');
INSERT INTO cc_country (isocode, name) VALUES ('BES', 'Bonaire, Saint Eustatius and Saba');
INSERT INTO cc_country (isocode, name) VALUES ('BIH', 'Bosnia and Herzegovina ');
INSERT INTO cc_country (isocode, name) VALUES ('BWA', 'Botswana ');
INSERT INTO cc_country (isocode, name) VALUES ('BRA', 'Brazil ');
INSERT INTO cc_country (isocode, name) VALUES ('VGB', 'British Virgin Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('BRN', 'Brunei Darussalam ');
INSERT INTO cc_country (isocode, name) VALUES ('BGR', 'Bulgaria ');
INSERT INTO cc_country (isocode, name) VALUES ('BFA', 'Burkina Faso ');
INSERT INTO cc_country (isocode, name) VALUES ('BDI', 'Burundi ');
INSERT INTO cc_country (isocode, name) VALUES ('KHM', 'Cambodia ');
INSERT INTO cc_country (isocode, name) VALUES ('CMR', 'Cameroon ');
INSERT INTO cc_country (isocode, name) VALUES ('CAN', 'Canada ');
INSERT INTO cc_country (isocode, name) VALUES ('CPV', 'Cape Verde ');
INSERT INTO cc_country (isocode, name) VALUES ('CYM', 'Cayman Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('CAF', 'Central African Republic ');
INSERT INTO cc_country (isocode, name) VALUES ('TCD', 'Chad ');
INSERT INTO cc_country (isocode, name) VALUES ('CHL', 'Chile ');
INSERT INTO cc_country (isocode, name) VALUES ('CHN', 'China ');
INSERT INTO cc_country (isocode, name) VALUES ('HKG', 'China, Hong Kong Special Administrative Region');
INSERT INTO cc_country (isocode, name) VALUES ('MAC', 'China, Macao Special Administrative Region');
INSERT INTO cc_country (isocode, name) VALUES ('COL', 'Colombia ');
INSERT INTO cc_country (isocode, name) VALUES ('COM', 'Comoros ');
INSERT INTO cc_country (isocode, name) VALUES ('COG', 'Congo ');
INSERT INTO cc_country (isocode, name) VALUES ('COK', 'Cook Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('CRI', 'Costa Rica ');
INSERT INTO cc_country (isocode, name) VALUES ('CIV', 'Côte d''Ivoire ');
INSERT INTO cc_country (isocode, name) VALUES ('HRV', 'Croatia ');
INSERT INTO cc_country (isocode, name) VALUES ('CUB', 'Cuba ');
INSERT INTO cc_country (isocode, name) VALUES ('CUW', 'Curaçao');
INSERT INTO cc_country (isocode, name) VALUES ('CYP', 'Cyprus ');
INSERT INTO cc_country (isocode, name) VALUES ('CZE', 'Czech Republic ');
INSERT INTO cc_country (isocode, name) VALUES ('PRK', 'Democratic People''s Republic of Korea ');
INSERT INTO cc_country (isocode, name) VALUES ('COD', 'Democratic Republic of the Congo ');
INSERT INTO cc_country (isocode, name) VALUES ('DNK', 'Denmark ');
INSERT INTO cc_country (isocode, name) VALUES ('DJI', 'Djibouti ');
INSERT INTO cc_country (isocode, name) VALUES ('DMA', 'Dominica ');
INSERT INTO cc_country (isocode, name) VALUES ('DOM', 'Dominican Republic ');
INSERT INTO cc_country (isocode, name) VALUES ('ECU', 'Ecuador ');
INSERT INTO cc_country (isocode, name) VALUES ('EGY', 'Egypt ');
INSERT INTO cc_country (isocode, name) VALUES ('SLV', 'El Salvador ');
INSERT INTO cc_country (isocode, name) VALUES ('GNQ', 'Equatorial Guinea ');
INSERT INTO cc_country (isocode, name) VALUES ('ERI', 'Eritrea ');
INSERT INTO cc_country (isocode, name) VALUES ('EST', 'Estonia ');
INSERT INTO cc_country (isocode, name) VALUES ('ETH', 'Ethiopia ');
INSERT INTO cc_country (isocode, name) VALUES ('FRO', 'Faeroe Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('FLK', 'Falkland Islands (Malvinas) ');
INSERT INTO cc_country (isocode, name) VALUES ('FJI', 'Fiji ');
INSERT INTO cc_country (isocode, name) VALUES ('FIN', 'Finland ');
INSERT INTO cc_country (isocode, name) VALUES ('FRA', 'France ');
INSERT INTO cc_country (isocode, name) VALUES ('GUF', 'French Guiana ');
INSERT INTO cc_country (isocode, name) VALUES ('PYF', 'French Polynesia ');
INSERT INTO cc_country (isocode, name) VALUES ('GAB', 'Gabon ');
INSERT INTO cc_country (isocode, name) VALUES ('GMB', 'Gambia ');
INSERT INTO cc_country (isocode, name) VALUES ('GEO', 'Georgia ');
INSERT INTO cc_country (isocode, name) VALUES ('DEU', 'Germany ');
INSERT INTO cc_country (isocode, name) VALUES ('GHA', 'Ghana ');
INSERT INTO cc_country (isocode, name) VALUES ('GIB', 'Gibraltar ');
INSERT INTO cc_country (isocode, name) VALUES ('GRC', 'Greece ');
INSERT INTO cc_country (isocode, name) VALUES ('GRL', 'Greenland ');
INSERT INTO cc_country (isocode, name) VALUES ('GRD', 'Grenada ');
INSERT INTO cc_country (isocode, name) VALUES ('GLP', 'Guadeloupe ');
INSERT INTO cc_country (isocode, name) VALUES ('GUM', 'Guam ');
INSERT INTO cc_country (isocode, name) VALUES ('GTM', 'Guatemala ');
INSERT INTO cc_country (isocode, name) VALUES ('GGY', 'Guernsey');
INSERT INTO cc_country (isocode, name) VALUES ('GIN', 'Guinea ');
INSERT INTO cc_country (isocode, name) VALUES ('GNB', 'Guinea-Bissau ');
INSERT INTO cc_country (isocode, name) VALUES ('GUY', 'Guyana ');
INSERT INTO cc_country (isocode, name) VALUES ('HTI', 'Haiti ');
INSERT INTO cc_country (isocode, name) VALUES ('VAT', 'Holy See ');
INSERT INTO cc_country (isocode, name) VALUES ('HND', 'Honduras ');
INSERT INTO cc_country (isocode, name) VALUES ('HUN', 'Hungary ');
INSERT INTO cc_country (isocode, name) VALUES ('ISL', 'Iceland ');
INSERT INTO cc_country (isocode, name) VALUES ('IND', 'India ');
INSERT INTO cc_country (isocode, name) VALUES ('IDN', 'Indonesia ');
INSERT INTO cc_country (isocode, name) VALUES ('IRN', 'Iran (Islamic Republic of)');
INSERT INTO cc_country (isocode, name) VALUES ('IRQ', 'Iraq ');
INSERT INTO cc_country (isocode, name) VALUES ('IRL', 'Ireland ');
INSERT INTO cc_country (isocode, name) VALUES ('IMN', 'Isle of Man ');
INSERT INTO cc_country (isocode, name) VALUES ('ISR', 'Israel ');
INSERT INTO cc_country (isocode, name) VALUES ('ITA', 'Italy ');
INSERT INTO cc_country (isocode, name) VALUES ('JAM', 'Jamaica ');
INSERT INTO cc_country (isocode, name) VALUES ('JPN', 'Japan ');
INSERT INTO cc_country (isocode, name) VALUES ('JEY', 'Jersey');
INSERT INTO cc_country (isocode, name) VALUES ('JOR', 'Jordan ');
INSERT INTO cc_country (isocode, name) VALUES ('KAZ', 'Kazakhstan ');
INSERT INTO cc_country (isocode, name) VALUES ('KEN', 'Kenya ');
INSERT INTO cc_country (isocode, name) VALUES ('KIR', 'Kiribati ');
INSERT INTO cc_country (isocode, name) VALUES ('KWT', 'Kuwait ');
INSERT INTO cc_country (isocode, name) VALUES ('KGZ', 'Kyrgyzstan ');
INSERT INTO cc_country (isocode, name) VALUES ('LAO', 'Lao People''s Democratic Republic ');
INSERT INTO cc_country (isocode, name) VALUES ('LVA', 'Latvia ');
INSERT INTO cc_country (isocode, name) VALUES ('LBN', 'Lebanon ');
INSERT INTO cc_country (isocode, name) VALUES ('LSO', 'Lesotho ');
INSERT INTO cc_country (isocode, name) VALUES ('LBR', 'Liberia ');
INSERT INTO cc_country (isocode, name) VALUES ('LBY', 'Libyan Arab Jamahiriya ');
INSERT INTO cc_country (isocode, name) VALUES ('LIE', 'Liechtenstein ');
INSERT INTO cc_country (isocode, name) VALUES ('LTU', 'Lithuania ');
INSERT INTO cc_country (isocode, name) VALUES ('LUX', 'Luxembourg ');
INSERT INTO cc_country (isocode, name) VALUES ('MDG', 'Madagascar ');
INSERT INTO cc_country (isocode, name) VALUES ('MWI', 'Malawi ');
INSERT INTO cc_country (isocode, name) VALUES ('MYS', 'Malaysia ');
INSERT INTO cc_country (isocode, name) VALUES ('MDV', 'Maldives ');
INSERT INTO cc_country (isocode, name) VALUES ('MLI', 'Mali ');
INSERT INTO cc_country (isocode, name) VALUES ('MLT', 'Malta ');
INSERT INTO cc_country (isocode, name) VALUES ('MHL', 'Marshall Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('MTQ', 'Martinique ');
INSERT INTO cc_country (isocode, name) VALUES ('MRT', 'Mauritania ');
INSERT INTO cc_country (isocode, name) VALUES ('MUS', 'Mauritius ');
INSERT INTO cc_country (isocode, name) VALUES ('MYT', 'Mayotte');
INSERT INTO cc_country (isocode, name) VALUES ('MEX', 'Mexico ');
INSERT INTO cc_country (isocode, name) VALUES ('FSM', 'Micronesia (Federated States of)');
INSERT INTO cc_country (isocode, name) VALUES ('MCO', 'Monaco ');
INSERT INTO cc_country (isocode, name) VALUES ('MNG', 'Mongolia ');
INSERT INTO cc_country (isocode, name) VALUES ('MNE', 'Montenegro');
INSERT INTO cc_country (isocode, name) VALUES ('MSR', 'Montserrat ');
INSERT INTO cc_country (isocode, name) VALUES ('MAR', 'Morocco ');
INSERT INTO cc_country (isocode, name) VALUES ('MOZ', 'Mozambique ');
INSERT INTO cc_country (isocode, name) VALUES ('MMR', 'Myanmar ');
INSERT INTO cc_country (isocode, name) VALUES ('NAM', 'Namibia ');
INSERT INTO cc_country (isocode, name) VALUES ('NRU', 'Nauru ');
INSERT INTO cc_country (isocode, name) VALUES ('NPL', 'Nepal ');
INSERT INTO cc_country (isocode, name) VALUES ('NLD', 'Netherlands ');
INSERT INTO cc_country (isocode, name) VALUES ('NCL', 'New Caledonia ');
INSERT INTO cc_country (isocode, name) VALUES ('NZL', 'New Zealand ');
INSERT INTO cc_country (isocode, name) VALUES ('NIC', 'Nicaragua ');
INSERT INTO cc_country (isocode, name) VALUES ('NER', 'Niger ');
INSERT INTO cc_country (isocode, name) VALUES ('NGA', 'Nigeria ');
INSERT INTO cc_country (isocode, name) VALUES ('NIU', 'Niue ');
INSERT INTO cc_country (isocode, name) VALUES ('NFK', 'Norfolk Island ');
INSERT INTO cc_country (isocode, name) VALUES ('MNP', 'Northern Mariana Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('NOR', 'Norway ');
INSERT INTO cc_country (isocode, name) VALUES ('PSE', 'Occupied Palestinian Territory ');
INSERT INTO cc_country (isocode, name) VALUES ('OMN', 'Oman ');
INSERT INTO cc_country (isocode, name) VALUES ('PAK', 'Pakistan ');
INSERT INTO cc_country (isocode, name) VALUES ('PLW', 'Palau ');
INSERT INTO cc_country (isocode, name) VALUES ('PAN', 'Panama ');
INSERT INTO cc_country (isocode, name) VALUES ('PNG', 'Papua New Guinea ');
INSERT INTO cc_country (isocode, name) VALUES ('PRY', 'Paraguay ');
INSERT INTO cc_country (isocode, name) VALUES ('PER', 'Peru ');
INSERT INTO cc_country (isocode, name) VALUES ('PHL', 'Philippines ');
INSERT INTO cc_country (isocode, name) VALUES ('PCN', 'Pitcairn ');
INSERT INTO cc_country (isocode, name) VALUES ('POL', 'Poland ');
INSERT INTO cc_country (isocode, name) VALUES ('PRT', 'Portugal ');
INSERT INTO cc_country (isocode, name) VALUES ('PRI', 'Puerto Rico ');
INSERT INTO cc_country (isocode, name) VALUES ('QAT', 'Qatar ');
INSERT INTO cc_country (isocode, name) VALUES ('KOR', 'Republic of Korea ');
INSERT INTO cc_country (isocode, name) VALUES ('MDA', 'Republic of Moldova');
INSERT INTO cc_country (isocode, name) VALUES ('REU', 'Réunion ');
INSERT INTO cc_country (isocode, name) VALUES ('ROU', 'Romania ');
INSERT INTO cc_country (isocode, name) VALUES ('RUS', 'Russian Federation ');
INSERT INTO cc_country (isocode, name) VALUES ('RWA', 'Rwanda ');
INSERT INTO cc_country (isocode, name) VALUES ('BLM', 'Saint-Barthélemy');
INSERT INTO cc_country (isocode, name) VALUES ('SHN', 'Saint Helena ');
INSERT INTO cc_country (isocode, name) VALUES ('KNA', 'Saint Kitts and Nevis ');
INSERT INTO cc_country (isocode, name) VALUES ('LCA', 'Saint Lucia ');
INSERT INTO cc_country (isocode, name) VALUES ('MAF', 'Saint-Martin (French part)');
INSERT INTO cc_country (isocode, name) VALUES ('SPM', 'Saint Pierre and Miquelon ');
INSERT INTO cc_country (isocode, name) VALUES ('VCT', 'Saint Vincent and the Grenadines ');
INSERT INTO cc_country (isocode, name) VALUES ('WSM', 'Samoa ');
INSERT INTO cc_country (isocode, name) VALUES ('SMR', 'San Marino ');
INSERT INTO cc_country (isocode, name) VALUES ('STP', 'Sao Tome and Principe ');
INSERT INTO cc_country (isocode, name) VALUES ('SAU', 'Saudi Arabia ');
INSERT INTO cc_country (isocode, name) VALUES ('SEN', 'Senegal ');
INSERT INTO cc_country (isocode, name) VALUES ('SRB', 'Serbia ');
INSERT INTO cc_country (isocode, name) VALUES ('SYC', 'Seychelles ');
INSERT INTO cc_country (isocode, name) VALUES ('SLE', 'Sierra Leone ');
INSERT INTO cc_country (isocode, name) VALUES ('SGP', 'Singapore ');
INSERT INTO cc_country (isocode, name) VALUES ('SXM', 'Sint Maarten (Dutch part)');
INSERT INTO cc_country (isocode, name) VALUES ('SVK', 'Slovakia ');
INSERT INTO cc_country (isocode, name) VALUES ('SVN', 'Slovenia ');
INSERT INTO cc_country (isocode, name) VALUES ('SLB', 'Solomon Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('SOM', 'Somalia ');
INSERT INTO cc_country (isocode, name) VALUES ('ZAF', 'South Africa ');
INSERT INTO cc_country (isocode, name) VALUES ('ESP', 'Spain ');
INSERT INTO cc_country (isocode, name) VALUES ('LKA', 'Sri Lanka ');
INSERT INTO cc_country (isocode, name) VALUES ('SDN', 'Sudan ');
INSERT INTO cc_country (isocode, name) VALUES ('SUR', 'Suriname ');
INSERT INTO cc_country (isocode, name) VALUES ('SJM', 'Svalbard and Jan Mayen Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('SWZ', 'Swaziland ');
INSERT INTO cc_country (isocode, name) VALUES ('SWE', 'Sweden ');
INSERT INTO cc_country (isocode, name) VALUES ('CHE', 'Switzerland ');
INSERT INTO cc_country (isocode, name) VALUES ('SYR', 'Syrian Arab Republic ');
INSERT INTO cc_country (isocode, name) VALUES ('TJK', 'Tajikistan ');
INSERT INTO cc_country (isocode, name) VALUES ('THA', 'Thailand ');
INSERT INTO cc_country (isocode, name) VALUES ('MKD', 'The former Yugoslav Republic of Macedonia ');
INSERT INTO cc_country (isocode, name) VALUES ('TLS', 'Timor-Leste');
INSERT INTO cc_country (isocode, name) VALUES ('TGO', 'Togo ');
INSERT INTO cc_country (isocode, name) VALUES ('TKL', 'Tokelau ');
INSERT INTO cc_country (isocode, name) VALUES ('TON', 'Tonga ');
INSERT INTO cc_country (isocode, name) VALUES ('TTO', 'Trinidad and Tobago ');
INSERT INTO cc_country (isocode, name) VALUES ('TUN', 'Tunisia ');
INSERT INTO cc_country (isocode, name) VALUES ('TUR', 'Turkey ');
INSERT INTO cc_country (isocode, name) VALUES ('TKM', 'Turkmenistan ');
INSERT INTO cc_country (isocode, name) VALUES ('TCA', 'Turks and Caicos Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('TUV', 'Tuvalu ');
INSERT INTO cc_country (isocode, name) VALUES ('UGA', 'Uganda ');
INSERT INTO cc_country (isocode, name) VALUES ('UKR', 'Ukraine ');
INSERT INTO cc_country (isocode, name) VALUES ('ARE', 'United Arab Emirates ');
INSERT INTO cc_country (isocode, name) VALUES ('GBR', 'United Kingdom of Great Britain and Northern Ireland');
INSERT INTO cc_country (isocode, name) VALUES ('TZA', 'United Republic of Tanzania ');
INSERT INTO cc_country (isocode, name) VALUES ('USA', 'United States of America');
INSERT INTO cc_country (isocode, name) VALUES ('VIR', 'United States Virgin Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('URY', 'Uruguay ');
INSERT INTO cc_country (isocode, name) VALUES ('UZB', 'Uzbekistan ');
INSERT INTO cc_country (isocode, name) VALUES ('VUT', 'Vanuatu ');
INSERT INTO cc_country (isocode, name) VALUES ('VEN', 'Venezuela (Bolivarian Republic of)');
INSERT INTO cc_country (isocode, name) VALUES ('VNM', 'Viet Nam ');
INSERT INTO cc_country (isocode, name) VALUES ('WLF', 'Wallis and Futuna Islands ');
INSERT INTO cc_country (isocode, name) VALUES ('ESH', 'Western Sahara ');
INSERT INTO cc_country (isocode, name) VALUES ('YEM', 'Yemen ');
INSERT INTO cc_country (isocode, name) VALUES ('ZMB', 'Zambia ');
INSERT INTO cc_country (isocode, name) VALUES ('ZWE', 'Zimbabwe ');";
echo "* Inserting data into country table".PHP_EOL;
Airtime190Upgrade::execSqlQuery($sql);
}
}
class AirtimeIni{
const CONF_FILE_AIRTIME = "/etc/airtime/airtime.conf";
const CONF_FILE_PYPO = "/etc/airtime/pypo.cfg";
const CONF_FILE_RECORDER = "/etc/airtime/recorder.cfg";
const CONF_FILE_LIQUIDSOAP = "/etc/airtime/liquidsoap.cfg";
const CONF_FILE_MEDIAMONITOR = "/etc/airtime/media-monitor.cfg";
/**
* This function updates an INI style config file.
*
* A property and the value the property should be changed to are
* supplied. If the property is not found, then no changes are made.
*
* @param string $p_filename
* The path the to the file.
* @param string $p_property
* The property to look for in order to change its value.
* @param string $p_value
* The value the property should be changed to.
*
*/
public static function UpdateIniValue($p_filename, $p_property, $p_value)
{
$lines = file($p_filename);
$n=count($lines);
foreach ($lines as &$line) {
if ($line[0] != "#"){
$key_value = explode("=", $line);
$key = trim($key_value[0]);
if ($key == $p_property){
$line = "$p_property = $p_value".PHP_EOL;
}
}
}
$fp=fopen($p_filename, 'w');
for($i=0; $i<$n; $i++){
fwrite($fp, $lines[$i]);
}
fclose($fp);
}
public static function ReadPythonConfig($p_filename)
{
$values = array();
$lines = file($p_filename);
$n=count($lines);
for ($i=0; $i<$n; $i++) {
if (strlen($lines[$i]) && !in_array(substr($lines[$i], 0, 1), array('#', PHP_EOL))){
$info = explode("=", $lines[$i]);
$values[trim($info[0])] = trim($info[1]);
}
}
return $values;
}
public static function MergeConfigFiles($configFiles, $suffix) {
foreach ($configFiles as $conf) {
if (file_exists("$conf$suffix.bak")) {
if($conf === AirtimeIni::CONF_FILE_AIRTIME) {
// Parse with sections
$newSettings = parse_ini_file($conf, true);
$oldSettings = parse_ini_file("$conf$suffix.bak", true);
}
else {
$newSettings = AirtimeIni::ReadPythonConfig($conf);
$oldSettings = AirtimeIni::ReadPythonConfig("$conf$suffix.bak");
}
$settings = array_keys($newSettings);
foreach($settings as $section) {
if(isset($oldSettings[$section])) {
if(is_array($oldSettings[$section])) {
$sectionKeys = array_keys($newSettings[$section]);
foreach($sectionKeys as $sectionKey) {
if(isset($oldSettings[$section][$sectionKey])) {
AirtimeIni::UpdateIniValue($conf, $sectionKey, $oldSettings[$section][$sectionKey]);
}
}
}
else {
AirtimeIni::UpdateIniValue($conf, $section, $oldSettings[$section]);
}
}
}
}
}
}
public static function upgradeConfigFiles(){
$configFiles = array(AirtimeIni::CONF_FILE_AIRTIME,
AirtimeIni::CONF_FILE_PYPO,
AirtimeIni::CONF_FILE_RECORDER,
AirtimeIni::CONF_FILE_LIQUIDSOAP);
// Backup the config files
$suffix = date("Ymdhis")."-1.8.1";
foreach ($configFiles as $conf) {
if (file_exists($conf)) {
echo "Backing up $conf to $conf$suffix.bak".PHP_EOL;
copy($conf, $conf.$suffix.".bak");
}
}
AirtimeIni::CreateIniFiles();
AirtimeIni::MergeConfigFiles($configFiles, $suffix);
}
/**
* This function creates the /etc/airtime configuration folder
* and copies the default config files to it.
*/
public static function CreateIniFiles()
{
if (!file_exists("/etc/airtime/")){
if (!mkdir("/etc/airtime/", 0755, true)){
echo "Could not create /etc/airtime/ directory. Exiting.";
exit(1);
}
}
$AIRTIME_SRC = realpath(__DIR__.'/../../../airtime_mvc');
$AIRTIME_PYTHON_APPS = realpath(__DIR__.'/../../../python_apps');
if (!copy($AIRTIME_SRC."/build/airtime.conf", AirtimeIni::CONF_FILE_AIRTIME)){
echo "Could not copy airtime.conf to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/pypo/pypo.cfg", AirtimeIni::CONF_FILE_PYPO)){
echo "Could not copy pypo.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/show-recorder/recorder.cfg", AirtimeIni::CONF_FILE_RECORDER)){
echo "Could not copy recorder.cfg to /etc/airtime/. Exiting.";
exit(1);
}
if (!copy($AIRTIME_PYTHON_APPS."/pypo/liquidsoap_scripts/liquidsoap.cfg", AirtimeIni::CONF_FILE_LIQUIDSOAP)){
echo "Could not copy liquidsoap.cfg to /etc/airtime/. Exiting.";
exit(1);
}
}
}
class Airtime190Upgrade{
public static function InstallAirtimePhpServerCode($phpDir)
{
$AIRTIME_SRC = realpath(__DIR__.'/../../../airtime_mvc');
echo "* Installing PHP code to ".$phpDir.PHP_EOL;
exec("mkdir -p ".$phpDir);
exec("cp -R ".$AIRTIME_SRC."/* ".$phpDir);
}
public static function CopyUtils()
{
$utilsSrc = __DIR__."/../../../utils";
echo "* Installing binaries to ".CONF_DIR_BINARIES.PHP_EOL;
exec("mkdir -p ".CONF_DIR_BINARIES);
exec("cp -R ".$utilsSrc." ".CONF_DIR_BINARIES);
}
/* Removes pypo, media-monitor, show-recorder and utils from system. These will
* be reinstalled by the main airtime-upgrade script.
*/
public static function UninstallBinaries()
{
echo "* Removing Airtime binaries from ".CONF_DIR_BINARIES.PHP_EOL;
exec('rm -rf "'.CONF_DIR_BINARIES.'"');
}
public static function removeOldAirtimeImport(){
exec('rm -f "/usr/bin/airtime-import"');
exec('rm -f "/usr/lib/airtime/utils/airtime-import.php"');
exec('rm -rf "/usr/lib/airtime/utils/airtime-import"');
}
public static function updateAirtimeImportSymLink(){
$dir = "/usr/lib/airtime/utils/airtime-import/airtime-import";
exec("ln -s $dir /usr/bin/airtime-import");
}
public static function execSqlQuery($sql){
global $CC_DBC;
$result = $CC_DBC->query($sql);
if (PEAR::isError($result)) {
echo "* Failed sql query: $sql".PHP_EOL;
echo "* Message {$result->getMessage()}".PHP_EOL;
}
return $result;
}
public static function connectToDatabase(){
global $CC_DBC, $CC_CONFIG;
$values = parse_ini_file('/etc/airtime/airtime.conf', true);
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
$CC_CONFIG['dsn']['hostspec'] = $values['database']['host'];
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_DBC = DB::connect($CC_CONFIG['dsn'], FALSE);
}
/* Old database had a "fullpath" column that stored the absolute path of each track. We have to
* change it so that the "fullpath" column has path relative to the "directory" column.
*/
public static function installMediaMonitor($values){
/* Handle Database Changes. */
$stor_dir = realpath($values['general']['base_files_dir']."/stor")."/";
echo "* Inserting stor directory location $stor_dir into music_dirs table".PHP_EOL;
$sql = "UPDATE cc_music_dirs SET directory='$stor_dir' WHERE type='stor'";
echo $sql.PHP_EOL;
Airtime190Upgrade::execSqlQuery($sql);
$sql = "SELECT id FROM cc_music_dirs WHERE type='stor'";
echo $sql.PHP_EOL;
$rows = Airtime190Upgrade::execSqlQuery($sql);
echo "Creating media-monitor log file";
mkdir("/var/log/airtime/media-monitor/", 755, true);
touch("/var/log/airtime/media-monitor/media-monitor.log");
/* create media monitor config: */
if (!copy(__DIR__."/../../../python_apps/media-monitor/media-monitor.cfg", AirtimeIni::CONF_FILE_MEDIAMONITOR)){
echo "Could not copy media-monitor.cfg to /etc/airtime/. Exiting.";
}
AirtimeIni::UpdateIniValue(AirtimeIni::CONF_FILE_MEDIAMONITOR, "api_key", $values["general"]["api_key"]);
echo "Reorganizing files in stor directory";
$mediaMonitorUpgradePath = realpath(__DIR__."/../../../python_apps/media-monitor/media-monitor-upgrade.py");
exec("su -c \"python $mediaMonitorUpgradePath\"", $output);
print_r($output);
$oldAndNewFileNames = json_decode($output[0]);
foreach ($oldAndNewFileNames as $pair){
$relPathNew = pg_escape_string(substr($pair[1], strlen($stor_dir)));
$absPathOld = pg_escape_string($pair[0]);
$sql = "UPDATE cc_files SET filepath = '$relPathNew', directory=1 WHERE filepath = '$absPathOld'";
echo $sql.PHP_EOL;
Airtime190Upgrade::execSqlQuery($sql);
}
}
}
AirtimeInstall::CreateZendPhpLogFile();
/* In version 1.9.0 we have have switched from daemontools to more traditional
* init.d daemon system. Let's remove all the daemontools files
*/
exec("/usr/bin/airtime-pypo-stop");
exec("/usr/bin/airtime-show-recorder-stop");
exec("svc -d /etc/service/pypo");
exec("svc -d /etc/service/pypo/log");
exec("svc -d /etc/service/pypo-liquidsoap");
exec("svc -d /etc/service/pypo-liquidsoap/log");
exec("svc -d /etc/service/recorder");
exec("svc -d /etc/service/recorder/log");
$pathnames = array("/usr/bin/airtime-pypo-start",
"/usr/bin/airtime-pypo-stop",
"/usr/bin/airtime-show-recorder-start",
"/usr/bin/airtime-show-recorder-stop",
"/usr/bin/airtime-media-monitor-start",
"/usr/bin/airtime-media-monitor-stop",
"/etc/service/pypo",
"/etc/service/pypo-liquidsoap",
"/etc/service/media-monitor",
"/etc/service/recorder",
"/var/log/airtime/pypo/main",
"/var/log/airtime/pypo-liquidsoap/main",
"/var/log/airtime/show-recorder/main"
);
foreach ($pathnames as $pn){
echo "Removing $pn\n";
exec("rm -rf \"$pn\"");
}
/* update Airtime Server PHP files */
$values = parse_ini_file(AirtimeIni::CONF_FILE_AIRTIME, true);
$phpDir = $values['general']['airtime_dir'];
Airtime190Upgrade::InstallAirtimePhpServerCode($phpDir);
/* update utils (/usr/lib/airtime) folder */
Airtime190Upgrade::UninstallBinaries();
Airtime190Upgrade::CopyUtils();
/* James made a new airtime-import script, lets remove the old airtime-import php script,
*install the new airtime-import.py script and update the /usr/bin/symlink.
*/
Airtime190Upgrade::removeOldAirtimeImport();
Airtime190Upgrade::updateAirtimeImportSymLink();
Airtime190Upgrade::connectToDatabase();
if(AirtimeInstall::DbTableExists('doctrine_migration_versions') === false) {
$migrations = array('20110312121200', '20110331111708', '20110402164819', '20110406182005');
foreach($migrations as $migration) {
AirtimeInstall::BypassMigrations(__DIR__, $migration);
}
}
/* adding music_dir and country table. 20110629143017 and 20110713161043 respetivly */
AirtimeInstall::MigrateTablesToVersion(__DIR__, '20110713161043');
AirtimeInstall::InsertCountryDataIntoDatabase();
/* create cron file for phone home stat */
AirtimeInstall::CreateCronFile();
Airtime190Upgrade::installMediaMonitor($values);
AirtimeIni::upgradeConfigFiles();

View file

@ -0,0 +1,24 @@
import sys
from configobj import ConfigObj
class AirtimeMediaConfig:
MODE_CREATE = "create"
MODE_MODIFY = "modify"
MODE_MOVED = "moved"
MODE_DELETE = "delete"
def __init__(self, logger):
# loading config file
try:
config = ConfigObj('/etc/airtime/media-monitor.cfg')
self.cfg = config
except Exception, e:
logger.info('Error loading config: ', e)
sys.exit()
self.storage_directory = None

View file

@ -0,0 +1,243 @@
import os
import grp
import pwd
import logging
from subprocess import Popen, PIPE
from airtimemetadata import AirtimeMetadata
class MediaMonitorCommon:
timestamp_file = "/var/tmp/airtime/last_index"
def __init__(self, airtime_config):
self.supported_file_formats = ['mp3', 'ogg']
self.logger = logging.getLogger()
self.config = airtime_config
self.md_manager = AirtimeMetadata()
def is_parent_directory(self, filepath, directory):
filepath = os.path.normpath(filepath)
directory = os.path.normpath(directory)
return (directory == filepath[0:len(directory)])
def is_temp_file(self, filename):
info = filename.split(".")
if(info[-2] in self.supported_file_formats):
return True
else:
return False
def is_audio_file(self, filename):
info = filename.split(".")
if(info[-1] in self.supported_file_formats):
return True
else:
return False
#check if file is readable by "nobody"
def has_correct_permissions(self, filepath):
#drop root permissions and become "nobody"
os.seteuid(65534)
try:
open(filepath)
readable = True
except IOError:
self.logger.warn("File does not have correct permissions: '%s'", filepath)
readable = False
except Exception, e:
self.logger.error("Unexpected exception thrown: %s", e)
readable = False
finally:
#reset effective user to root
os.seteuid(0)
return readable
def set_needed_file_permissions(self, item, is_dir):
try:
omask = os.umask(0)
uid = pwd.getpwnam('www-data')[2]
gid = grp.getgrnam('www-data')[2]
os.chown(item, uid, gid)
if is_dir is True:
os.chmod(item, 02777)
else:
os.chmod(item, 0666)
except Exception, e:
self.logger.error("Failed to change file's owner/group/permissions. %s", e)
finally:
os.umask(omask)
#checks if path is a directory, and if it doesnt exist, then creates it.
#Otherwise prints error to log file.
def ensure_is_dir(self, directory):
try:
omask = os.umask(0)
if not os.path.exists(directory):
os.makedirs(directory, 02777)
elif not os.path.isdir(directory):
#path exists but it is a file not a directory!
self.logger.error("path %s exists, but it is not a directory!!!")
finally:
os.umask(omask)
#moves file from source to dest but also recursively removes the
#the source file's parent directories if they are now empty.
def move_file(self, source, dest):
try:
omask = os.umask(0)
os.rename(source, dest)
except Exception, e:
self.logger.error("failed to move file. %s", e)
finally:
os.umask(omask)
dir = os.path.dirname(source)
self.cleanup_empty_dirs(dir)
#keep moving up the file hierarchy and deleting parent
#directories until we hit a non-empty directory, or we
#hit the organize dir.
def cleanup_empty_dirs(self, dir):
if os.path.normpath(dir) != self.config.organize_directory:
if len(os.listdir(dir)) == 0:
os.rmdir(dir)
pdir = os.path.dirname(dir)
self.cleanup_empty_dirs(pdir)
#checks if path exists already in stor. If the path exists and the md5s are the
#same just overwrite.
def create_unique_filename(self, filepath, old_filepath):
try:
if(os.path.exists(filepath)):
self.logger.info("Path %s exists", filepath)
self.logger.info("Checking if md5s are the same.")
md5_fp = self.md_manager.get_md5(filepath)
md5_ofp = self.md_manager.get_md5(old_filepath)
if(md5_fp == md5_ofp):
self.logger.info("Md5s are the same, moving to same filepath.")
return filepath
self.logger.info("Md5s aren't the same, appending to filepath.")
file_dir = os.path.dirname(filepath)
filename = os.path.basename(filepath).split(".")[0]
#will be in the format .ext
file_ext = os.path.splitext(filepath)[1]
i = 1;
while(True):
new_filepath = '%s/%s(%s)%s' % (file_dir, filename, i, file_ext)
self.logger.error("Trying %s", new_filepath)
if(os.path.exists(new_filepath)):
i = i+1;
else:
filepath = new_filepath
break
except Exception, e:
self.logger.error("Exception %s", e)
return filepath
#create path in /srv/airtime/stor/imported/[song-metadata]
def create_file_path(self, original_path, orig_md):
storage_directory = self.config.storage_directory
is_recorded_show = False
try:
#will be in the format .ext
file_ext = os.path.splitext(original_path)[1]
file_ext = file_ext.encode('utf-8')
path_md = ['MDATA_KEY_TITLE', 'MDATA_KEY_CREATOR', 'MDATA_KEY_SOURCE', 'MDATA_KEY_TRACKNUMBER', 'MDATA_KEY_BITRATE']
md = {}
for m in path_md:
if m not in orig_md:
md[m] = u'unknown'.encode('utf-8')
else:
#get rid of any "/" which will interfere with the filepath.
if isinstance(orig_md[m], basestring):
md[m] = orig_md[m].replace("/", "-")
else:
md[m] = orig_md[m]
if 'MDATA_KEY_TRACKNUMBER' in orig_md:
#make sure all track numbers are at least 2 digits long in the filepath.
md['MDATA_KEY_TRACKNUMBER'] = "%02d" % (int(md['MDATA_KEY_TRACKNUMBER']))
#format bitrate as 128kbps
md['MDATA_KEY_BITRATE'] = str(md['MDATA_KEY_BITRATE']/1000)+"kbps"
filepath = None
#file is recorded by Airtime
#/srv/airtime/stor/recorded/year/month/year-month-day-time-showname-bitrate.ext
if(md['MDATA_KEY_CREATOR'] == "AIRTIMERECORDERSOURCEFABRIC".encode('utf-8')):
#yyyy-mm-dd-hh-MM-ss
y = orig_md['MDATA_KEY_YEAR'].split("-")
filepath = '%s/%s/%s/%s/%s-%s-%s%s' % (storage_directory, "recorded".encode('utf-8'), y[0], y[1], orig_md['MDATA_KEY_YEAR'], md['MDATA_KEY_TITLE'], md['MDATA_KEY_BITRATE'], file_ext)
elif(md['MDATA_KEY_TRACKNUMBER'] == u'unknown'.encode('utf-8')):
filepath = '%s/%s/%s/%s/%s-%s%s' % (storage_directory, "imported".encode('utf-8'), md['MDATA_KEY_CREATOR'], md['MDATA_KEY_SOURCE'], md['MDATA_KEY_TITLE'], md['MDATA_KEY_BITRATE'], file_ext)
else:
filepath = '%s/%s/%s/%s/%s-%s-%s%s' % (storage_directory, "imported".encode('utf-8'), md['MDATA_KEY_CREATOR'], md['MDATA_KEY_SOURCE'], md['MDATA_KEY_TRACKNUMBER'], md['MDATA_KEY_TITLE'], md['MDATA_KEY_BITRATE'], file_ext)
filepath = self.create_unique_filename(filepath, original_path)
self.logger.info('Unique filepath: %s', filepath)
self.ensure_is_dir(os.path.dirname(filepath))
except Exception, e:
self.logger.error('Exception: %s', e)
return filepath
def execCommandAndReturnStdOut(self, command):
p = Popen(command, shell=True, stdout=PIPE)
stdout = p.communicate()[0]
if p.returncode != 0:
self.logger.warn("command \n%s\n return with a non-zero return value", command)
return stdout
def scan_dir_for_new_files(self, dir):
command = 'find "%s" -type f -iname "*.ogg" -o -iname "*.mp3" -readable' % dir.replace('"', '\\"')
self.logger.debug(command)
stdout = self.execCommandAndReturnStdOut(command)
stdout = unicode(stdout, "utf_8")
return stdout.splitlines()
def touch_index_file(self):
open(self.timestamp_file, "w")
def organize_new_file(self, pathname):
self.logger.info("Organizing new file: %s", pathname)
file_md = self.md_manager.get_md_from_file(pathname)
if file_md is not None:
#is_recorded_show = 'MDATA_KEY_CREATOR' in file_md and \
# file_md['MDATA_KEY_CREATOR'] == "AIRTIMERECORDERSOURCEFABRIC".encode('utf-8')
filepath = self.create_file_path(pathname, file_md)
self.logger.debug("Moving from %s to %s", pathname, filepath)
self.move_file(pathname, filepath)
else:
filepath = None
self.logger.warn("File %s, has invalid metadata", pathname)
return filepath

View file

@ -0,0 +1,83 @@
<?php
/* THIS FILE IS NOT MEANT FOR CUSTOMIZING.
* PLEASE EDIT THE FOLLOWING TO CHANGE YOUR CONFIG:
* /etc/airtime/airtime.conf
* /etc/airtime/pypo.cfg
* /etc/airtime/recorder.cfg
*/
global $CC_CONFIG;
$CC_CONFIG = array(
// prefix for table names in the database
'tblNamePrefix' => 'cc_',
/* ================================================ storage configuration */
'soundcloud-client-id' => '2CLCxcSXYzx7QhhPVHN4A',
'soundcloud-client-secret' => 'pZ7beWmF06epXLHVUP1ufOg2oEnIt9XhE8l8xt0bBs',
"rootDir" => __DIR__."/../..",
'pearPath' => dirname(__FILE__).'/../../../airtime_mvc/library/pear',
'zendPath' => dirname(__FILE__).'/../../../airtime_mvc/library/Zend',
'phingPath' => dirname(__FILE__).'/../../../airtime_mvc/library/phing'
);
$CC_CONFIG = Config::loadConfig($CC_CONFIG);
// Add database table names
$CC_CONFIG['playListTable'] = $CC_CONFIG['tblNamePrefix'].'playlist';
$CC_CONFIG['playListContentsTable'] = $CC_CONFIG['tblNamePrefix'].'playlistcontents';
$CC_CONFIG['filesTable'] = $CC_CONFIG['tblNamePrefix'].'files';
$CC_CONFIG['accessTable'] = $CC_CONFIG['tblNamePrefix'].'access';
$CC_CONFIG['permTable'] = $CC_CONFIG['tblNamePrefix'].'perms';
$CC_CONFIG['sessTable'] = $CC_CONFIG['tblNamePrefix'].'sess';
$CC_CONFIG['subjTable'] = $CC_CONFIG['tblNamePrefix'].'subjs';
$CC_CONFIG['smembTable'] = $CC_CONFIG['tblNamePrefix'].'smemb';
$CC_CONFIG['prefTable'] = $CC_CONFIG['tblNamePrefix'].'pref';
$CC_CONFIG['scheduleTable'] = $CC_CONFIG['tblNamePrefix'].'schedule';
$CC_CONFIG['playListTimeView'] = $CC_CONFIG['tblNamePrefix'].'playlisttimes';
$CC_CONFIG['showSchedule'] = $CC_CONFIG['tblNamePrefix'].'show_schedule';
$CC_CONFIG['showDays'] = $CC_CONFIG['tblNamePrefix'].'show_days';
$CC_CONFIG['showTable'] = $CC_CONFIG['tblNamePrefix'].'show';
$CC_CONFIG['showInstances'] = $CC_CONFIG['tblNamePrefix'].'show_instances';
$CC_CONFIG['playListSequence'] = $CC_CONFIG['playListTable'].'_id';
$CC_CONFIG['filesSequence'] = $CC_CONFIG['filesTable'].'_id';
$CC_CONFIG['prefSequence'] = $CC_CONFIG['prefTable'].'_id';
$CC_CONFIG['permSequence'] = $CC_CONFIG['permTable'].'_id';
$CC_CONFIG['subjSequence'] = $CC_CONFIG['subjTable'].'_id';
$CC_CONFIG['smembSequence'] = $CC_CONFIG['smembTable'].'_id';
// Add libs to the PHP path
$old_include_path = get_include_path();
set_include_path('.'.PATH_SEPARATOR.$CC_CONFIG['pearPath']
.PATH_SEPARATOR.$CC_CONFIG['zendPath']
.PATH_SEPARATOR.$old_include_path);
class Config {
public static function loadConfig($CC_CONFIG) {
$values = parse_ini_file('/etc/airtime/airtime.conf', true);
// Name of the web server user
$CC_CONFIG['webServerUser'] = $values['general']['web_server_user'];
$CC_CONFIG['rabbitmq'] = $values['rabbitmq'];
$CC_CONFIG['baseUrl'] = $values['general']['base_url'];
$CC_CONFIG['basePort'] = $values['general']['base_port'];
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
$CC_CONFIG['dsn']['hostspec'] = $values['database']['host'];
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_CONFIG['apiKey'] = array($values['general']['api_key']);
$CC_CONFIG['soundcloud-connection-retries'] = $values['soundcloud']['connection_retries'];
$CC_CONFIG['soundcloud-connection-wait'] = $values['soundcloud']['time_between_retries'];
return $CC_CONFIG;
}
}

View file

@ -0,0 +1,22 @@
[loggers]
keys=root
[handlers]
keys=fileOutHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=fileOutHandler
[handler_fileOutHandler]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("/var/log/airtime/media-monitor/media-monitor.log", 'a', 1000000, 5,)
[formatter_simpleFormatter]
format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s
datefmt=

View file

@ -0,0 +1,44 @@
from airtimefilemonitor.mediamonitorcommon import MediaMonitorCommon
from airtimefilemonitor.mediaconfig import AirtimeMediaConfig
import logging
import logging.config
import sys
import os
import json
import ConfigParser
import os.path
# configure logging
try:
logging.config.fileConfig("%s/logging.cfg"%os.path.dirname(__file__))
except Exception, e:
print 'Error configuring logging: ', e
sys.exit(1)
logger = logging.getLogger()
mmconfig = AirtimeMediaConfig(logger)
#get stor folder location from /etc/airtime/airtime.conf
config = ConfigParser.RawConfigParser()
config.read('/etc/airtime/airtime.conf')
stor_dir = config.get('general', 'base_files_dir') + "/stor"
mmconfig.storage_directory = os.path.normpath(stor_dir)
mmconfig.imported_directory = os.path.normpath(stor_dir + '/imported')
mmconfig.organize_directory = os.path.normpath(stor_dir + '/organize')
mmc = MediaMonitorCommon(mmconfig)
#read list of all files in stor location.....and one-by-one pass this through to
#mmc.organize_files. print out json encoding of before and after
pairs = []
for root, dirs, files in os.walk(mmconfig.storage_directory):
for f in files:
#print os.path.join(root, f)
#print mmc.organize_new_file(os.path.join(root, f))
pair = os.path.join(root, f), mmc.organize_new_file(os.path.join(root, f))
pairs.append(pair)
print json.dumps(pairs)