feat(legacy): read stream config from file

- We don't delete the stream preferences from the database to prevent data loss. This will be handled in a future release.
This commit is contained in:
jo 2022-09-06 12:00:50 +02:00 committed by Kyle Robbertze
parent ba73866e47
commit 5bf62dd9cb
14 changed files with 498 additions and 1237 deletions

View file

@ -58,29 +58,6 @@ SQL;
}
return $out;
$enabledStreamIds = Application_Model_StreamSetting::getEnabledStreamIds();
$enabledOut = [];
foreach ($enabledStreamIds as $sId) {
$sql = 'SELECT value FROM cc_stream_setting'
. ' WHERE keyname = :key';
$result = Application_Common_Database::prepareAndExecute($sql, ['key' => $sId . '_mount'], 'single');
$enabledMountPoint = $result['value'];
if (isset($out[$enabledMountPoint])) {
$enabledOut[$enabledMountPoint] = $out[$enabledMountPoint];
} else {
// TODO fix this hack (here for CC-5254)
// all shoutcast streams are automatically put under "shoutcast" mount point.
if (isset($out['shoutcast'])) {
$enabledOut['shoutcast'] = $out['shoutcast'];
}
}
}
return $enabledOut;
}
// this will currently log the average number of listeners to a specific show during a certain range

View file

@ -795,20 +795,6 @@ class Application_Model_Preference
return (int) self::getValue('import_timestamp');
}
public static function GetStreamType()
{
$st = self::getValue('stream_type');
return explode(',', $st);
}
public static function GetStreamBitrate()
{
$sb = self::getValue('stream_bitrate');
return explode(',', $sb);
}
public static function SetPrivacyPolicyCheck($flag)
{
self::setValue('privacy_policy', $flag);
@ -819,36 +805,9 @@ class Application_Model_Preference
return self::getValue('privacy_policy');
}
public static function SetNumOfStreams($num)
{
self::setValue('num_of_streams', intval($num));
// Enable or disable each stream according to whatever was just changed.
for ($streamIdx = 1; $streamIdx <= MAX_NUM_STREAMS; ++$streamIdx) {
$prefix = 's' . $streamIdx . '_';
$enable = 'false';
if ($streamIdx <= intval($num)) {
$enable = 'true';
}
// Enable or disable the stream in the Stream Settings DB table.
Application_Model_StreamSetting::setIndividualStreamSetting([$prefix . 'enable' => $enable]);
}
}
public static function GetNumOfStreams()
{
return self::getValue('num_of_streams');
}
public static function SetMaxBitrate($bitrate)
{
self::setValue('max_bitrate', intval($bitrate));
}
public static function GetMaxBitrate()
{
return self::getValue('max_bitrate');
return count(Config::get('stream.outputs.merged'));
}
public static function SetEnableStreamConf($bool)
@ -1128,58 +1087,32 @@ class Application_Model_Preference
return ($value == null || $value == 'off') ? 'off' : 'on';
}
public static function SetMasterDJSourceConnectionURL($value)
{
self::setValue('master_dj_source_connection_url', $value, false);
}
public static function GetMasterDJSourceConnectionURL()
{
$master_connection_url = self::getValue('master_dj_source_connection_url');
if ($master_connection_url == '') {
$master_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . Application_Model_StreamSetting::getMasterLiveStreamPort() . Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
if (Config::has('stream.inputs.main.public_url') && Config::get('stream.inputs.main.public_url')) {
return Config::get('stream.inputs.main.public_url');
}
return $master_connection_url;
}
$host = Config::get('general.public_url_raw')->getHost();
$port = Application_Model_StreamSetting::getMasterLiveStreamPort();
$mount = Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
public static function SetLiveDJSourceConnectionURL($value)
{
self::setValue('live_dj_source_connection_url', $value, false);
return "http://{$host}:{$port}/{$mount}";
}
public static function GetLiveDJSourceConnectionURL()
{
$livedj_connection_url = self::getValue('live_dj_source_connection_url');
if ($livedj_connection_url == '') {
$livedj_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . Application_Model_StreamSetting::getDjLiveStreamPort() . Application_Model_StreamSetting::getDjLiveStreamMountPoint();
if (Config::has('stream.inputs.show.public_url') && Config::get('stream.inputs.show.public_url')) {
return Config::get('stream.inputs.show.public_url');
}
return $livedj_connection_url;
}
$host = Config::get('general.public_url_raw')->getHost();
$port = Application_Model_StreamSetting::getDjLiveStreamPort();
$mount = Application_Model_StreamSetting::getDjLiveStreamMountPoint();
// Source Connection URL override status starts
public static function GetLiveDjConnectionUrlOverride()
{
return self::getValue('live_dj_connection_url_override');
return "http://{$host}:{$port}/{$mount}";
}
public static function SetLiveDjConnectionUrlOverride($value)
{
self::setValue('live_dj_connection_url_override', $value, false);
}
public static function GetMasterDjConnectionUrlOverride()
{
return self::getValue('master_dj_connection_url_override');
}
public static function SetMasterDjConnectionUrlOverride($value)
{
self::setValue('master_dj_connection_url_override', $value, false);
}
// Source Connection URL override status ends
public static function SetAutoTransition($value)
{
self::setValue('auto_transition', $value, false);
@ -1454,28 +1387,6 @@ class Application_Model_Preference
// SAAS-876 - Store the default Icecast password to restore when switching
// back to Airtime Pro streaming settings
public static function getDefaultIcecastPassword()
{
$val = self::getValue('default_icecast_password');
return empty($val) ? DEFAULT_ICECAST_PASS : $val;
}
public static function setDefaultIcecastPassword($value)
{
self::setValue('default_icecast_password', $value);
}
public static function getDefaultStreamMountPoint()
{
return self::getValue('default_stream_mount_point');
}
public static function setDefaultStreamMountPoint($value)
{
self::setValue('default_stream_mount_point', $value);
}
public static function getRadioPageDisplayLoginButton()
{
return self::getValue('radio_page_display_login_button');

View file

@ -2,72 +2,106 @@
define('MAX_NUM_STREAMS', 4);
class Application_Model_StreamConfig
{
private static function toOutputKey($id)
{
return 's' . ($id);
}
private static function toOutputId($key)
{
return intval(trim($key, 's'));
}
public static function getOutput($key, $add_prefix = false)
{
$id = self::toOutputId($key);
$config_id = $id - 1;
$prefix = $add_prefix ? "s{$id}_" : '';
if (!Config::has("stream.outputs.merged.{$config_id}")) {
$result = [
$prefix . 'enable' => 'false',
$prefix . 'public_url' => '',
$prefix . 'output' => 'icecast',
$prefix . 'host' => 'localhost',
$prefix . 'port' => 8000,
$prefix . 'mount' => '',
$prefix . 'user' => 'source',
$prefix . 'pass' => '',
$prefix . 'admin_user' => 'admin',
$prefix . 'admin_pass' => '',
$prefix . 'channels' => 'stereo',
$prefix . 'bitrate' => 128,
$prefix . 'type' => '',
$prefix . 'name' => '',
$prefix . 'description' => '',
$prefix . 'genre' => '',
$prefix . 'url' => '',
$prefix . 'mobile' => 'false',
];
} else {
$output = Config::get("stream.outputs.merged.{$config_id}");
$result = [
$prefix . 'enable' => $output['enabled'] ?? 'false',
$prefix . 'output' => $output['kind'] ?? 'icecast',
$prefix . 'public_url' => $output['public_url'] ?? '',
$prefix . 'host' => $output['host'] ?? 'localhost',
$prefix . 'port' => $output['port'] ?? 8000,
$prefix . 'mount' => $output['mount'] ?? '',
$prefix . 'user' => $output['source_user'] ?? 'source',
$prefix . 'pass' => $output['source_password'] ?? '',
$prefix . 'admin_user' => $output['admin_user'] ?? 'admin',
$prefix . 'admin_pass' => $output['admin_password'] ?? '',
$prefix . 'channels' => $output['audio']['channels'] ?? 'stereo',
$prefix . 'bitrate' => $output['audio']['bitrate'] ?? 128,
$prefix . 'type' => $output['audio']['format'],
$prefix . 'name' => $output['name'] ?? '',
$prefix . 'description' => $output['description'] ?? '',
$prefix . 'genre' => $output['genre'] ?? '',
$prefix . 'url' => $output['website'] ?? '',
$prefix . 'mobile' => 'false',
// $prefix . 'liquidsoap_error' => 'waiting',
];
}
if (!$result[$prefix . 'public_url']) {
$host = $result[$prefix . 'host'];
if ($host == 'localhost') {
$host = Config::get('general.public_url_raw')->getHost();
}
$port = $result[$prefix . 'port'];
$mount = $result[$prefix . 'mount'];
$result[$prefix . 'public_url'] = "http://{$host}:{$port}/{$mount}";
if ($result[$prefix . 'output'] == 'shoutcast') {
// The semi-colon is important to make Shoutcast stream URLs play instead turn into a page.
$result[$prefix . 'public_url'] .= ';';
}
}
return $result;
}
public static function getOutputEnabledKeys()
{
$keys = [];
foreach (Config::get('stream.outputs.merged') as $id => $output) {
if ($output['enabled'] ?? false) {
$keys[] = self::toOutputKey($id + 1);
}
}
return $keys;
}
}
class Application_Model_StreamSetting
{
public static function setValue($key, $value, $type)
{
$con = Propel::getConnection();
// Check if key already exists
$sql = 'SELECT COUNT(*) FROM cc_stream_setting'
. ' WHERE keyname = :key';
$stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: {$msg}");
}
if ($result == 1) {
$sql = 'UPDATE cc_stream_setting'
. ' SET value = :value, type = :type'
. ' WHERE keyname = :key';
} else {
$sql = 'INSERT INTO cc_stream_setting (keyname, value, type)'
. ' VALUES (:key, :value, :type)';
}
$stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':value', $value);
$stmt->bindParam(':type', $type);
if ($stmt->execute()) {
// do nothing
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: {$msg}");
}
}
public static function getValue($key, $default = '')
{
$con = Propel::getConnection();
// Check if key already exists
$sql = 'SELECT value FROM cc_stream_setting'
. ' WHERE keyname = :key';
$stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: {$msg}");
}
return $result ? $result : $default;
}
public static function getEnabledStreamData()
{
$streams = [];
@ -75,16 +109,8 @@ class Application_Model_StreamSetting
foreach ($streamIds as $id) {
$streamData = self::getStreamData($id);
$prefix = $id . '_';
$host = $streamData[$prefix . 'host'];
$port = $streamData[$prefix . 'port'];
$mount = $streamData[$prefix . 'mount'];
if ($streamData[$prefix . 'output'] == 'shoutcast') {
$url = "http://{$host}:{$port}/;"; // The semi-colon is important to make Shoutcast stream URLs play instead turn into a page.
} else { // Icecast
$url = "http://{$host}:{$port}/{$mount}";
}
$streams[$id] = [
'url' => $url,
'url' => $streamData[$prefix . 'public_url'],
'codec' => $streamData[$prefix . 'type'],
'bitrate' => $streamData[$prefix . 'bitrate'],
'mobile' => $streamData[$prefix . 'mobile'],
@ -98,102 +124,21 @@ class Application_Model_StreamSetting
* example of the array returned in JSON notation is ["s1", "s2", "s3"] */
public static function getEnabledStreamIds()
{
$con = Propel::getConnection();
$sql = 'SELECT * '
. 'FROM cc_stream_setting '
. "WHERE keyname LIKE '%_enable' "
. "AND value='true'";
$ids = [];
$rows = Application_Common_Database::prepareAndExecute($sql, [], 'all');
foreach ($rows as $row) {
$ids[] = substr($row['keyname'], 0, strpos($row['keyname'], '_'));
}
return $ids;
return Application_Model_StreamConfig::getOutputEnabledKeys();
}
/* Returns all information related to a specific stream. An example
* of a stream id is 's1' or 's2'. */
public static function getStreamData($p_streamId)
{
$rows = CcStreamSettingQuery::create()
->filterByDbKeyName("{$p_streamId}_%")
->find();
// This is way too much code because someone made only stupid decisions about how
// the layout of this table worked. The git history doesn't lie.
$data = [];
foreach ($rows as $row) {
$key = $row->getDbKeyName();
$value = $row->getDbValue();
$type = $row->getDbType();
// Fix stupid defaults so we end up with proper typing in our JSON
if ($row->getDbType() == 'boolean') {
if (empty($value)) {
// In Python, there is no way to tell the difference between ints and booleans,
// which we need to differentiate between for when we're generating the Liquidsoap
// config file. Returning booleans as a string is a workaround that lets us do that.
$value = 'false';
}
$data[$key] = $value;
} elseif ($row->getDbType() == 'integer') {
if (empty($value)) {
$value = 0;
}
$data[$key] = intval($value);
} else {
$data[$key] = $value;
}
}
// Add in defaults in case they don't exist in the database.
$keyPrefix = $p_streamId . '_';
self::ensureKeyExists($keyPrefix . 'admin_pass', $data);
self::ensureKeyExists($keyPrefix . 'admin_user', $data);
self::ensureKeyExists($keyPrefix . 'bitrate', $data, 128);
self::ensureKeyExists($keyPrefix . 'channels', $data, 'stereo');
self::ensureKeyExists($keyPrefix . 'description', $data);
self::ensureKeyExists($keyPrefix . 'enable', $data, 'false');
self::ensureKeyExists($keyPrefix . 'genre', $data);
self::ensureKeyExists($keyPrefix . 'host', $data);
self::ensureKeyExists($keyPrefix . 'liquidsoap_error', $data, 'waiting');
self::ensureKeyExists($keyPrefix . 'mount', $data);
self::ensureKeyExists($keyPrefix . 'name', $data);
self::ensureKeyExists($keyPrefix . 'output', $data);
self::ensureKeyExists($keyPrefix . 'pass', $data);
self::ensureKeyExists($keyPrefix . 'port', $data, 8000);
self::ensureKeyExists($keyPrefix . 'type', $data);
self::ensureKeyExists($keyPrefix . 'url', $data);
self::ensureKeyExists($keyPrefix . 'user', $data);
self::ensureKeyExists($keyPrefix . 'mobile', $data);
return $data;
return Application_Model_StreamConfig::getOutput($p_streamId, true);
}
/* Similar to getStreamData, but removes all sX prefixes to
* make data easier to iterate over */
public static function getStreamDataNormalized($p_streamId)
{
$settings = self::getStreamData($p_streamId);
foreach ($settings as $key => $value) {
unset($settings[$key]);
$newKey = substr($key, strlen($p_streamId) + 1); // $p_streamId is assumed to be the key prefix.
$settings[$newKey] = $value;
}
return $settings;
}
private static function ensureKeyExists($key, &$array, $default = '')
{
if (!array_key_exists($key, $array)) {
$array[$key] = $default;
}
return $array;
return Application_Model_StreamConfig::getOutput($p_streamId, false);
}
public static function getStreamSetting()
@ -215,125 +160,9 @@ class Application_Model_StreamSetting
return $settings;
}
private static function saveStreamSetting($key, $value)
{
$stream_setting = CcStreamSettingQuery::create()->filterByDbKeyName($key)->findOne();
if (is_null($stream_setting)) {
// throw new Exception("Keyname $key does not exist!");
$stream_setting = new CcStreamSetting();
$stream_setting->setDbKeyName($key);
$stream_setting->setDbType('');
}
$stream_setting->setDbValue($value);
$stream_setting->save();
}
/*
* function that take all the information of stream and sets them.
* This is used by stream setting via UI.
*
* @param $data - array that contains all the data. $data is [][] which
* contains multiple stream information
*/
public static function setStreamSetting($data)
{
foreach ($data as $key => $d) {
if ($key == 'output_sound_device' || $key == 'icecast_vorbis_metadata') {
$v = ($d == 1) ? 'true' : 'false';
self::saveStreamSetting($key, $v);
} elseif ($key == 'output_sound_device_type') {
self::saveStreamSetting($key, $d);
} elseif (is_array($d)) {
$temp = explode('_', $key);
$prefix = $temp[0];
// SAAS-876 - If we're using Airtime Pro streaming, set the stream to use the default settings
if (!Application_Model_Preference::getUsingCustomStreamSettings()) {
$d = array_merge($d, static::getDefaults($prefix));
}
foreach ($d as $k => $v) {
$keyname = $prefix . '_' . $k;
if ($k == 'enable') {
$v = $d['enable'] == 1 ? 'true' : 'false';
}
$v = trim($v);
if ($k != 'admin_pass') {
self::saveStreamSetting($keyname, $v);
} elseif ($v != 'xxxxxx') {
// We use 'xxxxxx' as the admin password placeholder so we
// only want to save it when it is a different string
self::saveStreamSetting($keyname, $v);
}
}
}
}
}
/**
* SAAS-876 - Get the default stream settings values for Airtime Pro streaming.
*
* @param int $prefix
*
* @return array array of default stream setting values
*/
public static function getDefaults($prefix)
{
$config = Config::getConfig();
return [
'host' => $config['public_url_raw']->getHost(),
'port' => DEFAULT_ICECAST_PORT,
'output' => 'icecast',
'user' => $config['stationId'],
'pass' => Application_Model_Preference::getDefaultIcecastPassword(),
// Manually setting default mountpoint
'mount' => Application_Model_Preference::getDefaultStreamMountpoint(),
];
}
/*
* Sets individual stream setting.
*
* $data - data array. $data is [].
* TODO: Make this SQL a prepared statement!
*
* Do not remove this function. It is called by airtime-system.php
*/
public static function setIndividualStreamSetting($data)
{
foreach ($data as $keyname => $v) {
$sql = 'UPDATE cc_stream_setting SET value=:v WHERE keyname=:keyname';
$map = [':v' => $v, ':keyname' => $keyname];
$res = Application_Common_Database::prepareAndExecute(
$sql,
$map,
Application_Common_Database::EXECUTE
);
}
}
public static function getStreamEnabled($stream_id)
{
$con = Propel::getConnection();
$keyname = 's' . $stream_id . '_enable';
$sql = 'SELECT value FROM cc_stream_setting'
. ' WHERE keyname = :keyname';
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: {$msg}");
}
return $result != 'false';
return in_array('s' . $stream_id, self::getEnabledStreamIds());
}
/*
@ -342,112 +171,66 @@ class Application_Model_StreamSetting
*/
public static function getStreamInfoForDataCollection()
{
$con = Propel::getConnection();
$result = [];
$stream_ids = self::getEnabledStreamIds();
$out = [];
$enabled_stream = self::getEnabledStreamIds();
foreach ($enabled_stream as $stream) {
$keys = ["{$stream}_output", "{$stream}_type", "{$stream}_bitrate", "{$stream}_host"];
$key_csv = implode(',', $keys);
$sql = 'SELECT keyname, value FROM cc_stream_setting'
. ' WHERE keyname IN (:key_csv)';
$stmt = $con->prepare($sql);
$stmt->bindParam(':key_csv', $key_csv);
if ($stmt->execute()) {
$rows = $stmt->fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: {$msg}");
}
$info = [];
foreach ($rows as $r) {
$temp = explode('_', $r['keyname']);
$info[$temp[1]] = $r['value'];
$out[$stream] = $info;
}
foreach ($stream_ids as $stream_id) {
$stream = self::getStreamDataNormalized($stream_id);
$keys = array_flip(['output', 'type', 'bitrate', 'host']);
$result[$stream_id] = array_intersect_key($stream, $keys);
}
return $out;
}
public static function setMasterLiveStreamPort($value)
{
self::setValue('master_live_stream_port', $value, 'integer');
return $result;
}
public static function getMasterLiveStreamPort()
{
return self::getValue('master_live_stream_port', 8001);
}
public static function setMasterLiveStreamMountPoint($value)
{
self::setValue('master_live_stream_mp', $value, 'string');
return Config::get('stream.inputs.main.port') ?? 8001;
}
public static function getMasterLiveStreamMountPoint()
{
return self::getValue('master_live_stream_mp', '/master');
}
public static function setDjLiveStreamPort($value)
{
self::setValue('dj_live_stream_port', $value, 'integer');
return Config::get('stream.inputs.main.mount') ?? 'main';
}
public static function getDjLiveStreamPort()
{
return self::getValue('dj_live_stream_port', 8002);
}
public static function setDjLiveStreamMountPoint($value)
{
self::setValue('dj_live_stream_mp', $value, 'string');
return Config::get('stream.inputs.show.port') ?? 8002;
}
public static function getDjLiveStreamMountPoint()
{
return self::getValue('dj_live_stream_mp', '/show');
return Config::get('stream.inputs.show.mount') ?? 'show';
}
public static function getAdminUser($stream)
{
return self::getValue($stream . '_admin_user');
}
public static function setAdminUser($stream, $v)
{
self::setValue($stream . '_admin_user', $v, 'string');
return self::getStreamDataNormalized($stream)['admin_user'];
}
public static function getAdminPass($stream)
{
return self::getValue($stream . '_admin_pass');
}
public static function setAdminPass($stream, $v)
{
self::setValue($stream . '_admin_pass', $v, 'string');
return self::getStreamDataNormalized($stream)['admin_pass'];
}
public static function getIcecastVorbisMetadata()
{
return self::getValue('icecast_vorbis_metadata', '');
foreach (Config::get('stream.outputs.merged') as $output) {
if ($output['audio']['enable_metadata'] ?? false) {
return true;
}
}
return '';
}
public static function getOutputSoundDevice()
{
return self::getValue('output_sound_device', 'false');
return Config::get('stream.outputs.system.0.enabled') ?? 'false';
}
public static function getOutputSoundDeviceType()
{
return self::getValue('output_sound_device_type', '');
return Config::get('stream.outputs.system.0.kind') ?? '';
}
}