Merge branch '2.2.x-saas' of dev.sourcefabric.org:airtime into 2.2.x-saas

This commit is contained in:
denise 2012-10-23 16:50:36 -04:00
commit 9cd389d16b
28 changed files with 329 additions and 139 deletions

View file

@ -1,2 +1,2 @@
PRODUCT_ID=Airtime
PRODUCT_RELEASE=2.1.3
PRODUCT_RELEASE=2.2.0

View file

@ -490,6 +490,10 @@ class ApiController extends Zend_Controller_Action
$file->setFileExistsFlag(true);
$file->setMetadata($md);
}
if ($md['is_record'] != 0) {
$this->uploadRecordedActionParam($md['MDATA_KEY_TRACKNUMBER'], $file->getId());
}
} elseif ($mode == "modify") {
$filepath = $md['MDATA_KEY_FILEPATH'];
$file = Application_Model_StoredFile::RecallByFilepath($filepath);
@ -562,7 +566,6 @@ class ApiController extends Zend_Controller_Action
// least 1 digit
if ( !preg_match('/^md\d+$/', $k) ) { continue; }
$info_json = json_decode($raw_json, $assoc = true);
unset( $info_json["is_record"] );
// Log invalid requests
if ( !array_key_exists('mode', $info_json) ) {
Logging::info("Received bad request(key=$k), no 'mode' parameter. Bad request is:");

View file

@ -143,10 +143,12 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
* upto this point
*/
if ($valid) {
$utc = new DateTimeZone('UTC');
$localTimezone = new DateTimeZone(Application_Model_Preference::GetTimezone());
$show_start = new DateTime($start_time);
$show_start->setTimezone(new DateTimeZone('UTC'));
$show_start->setTimezone($utc);
$show_end = new DateTime($end_time);
$show_end->setTimezone(new DateTimeZone('UTC'));
$show_end->setTimezone($utc);
if ($formData["add_show_repeats"]) {
@ -155,7 +157,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$date = Application_Model_Preference::GetShowsPopulatedUntil();
if (is_null($date)) {
$populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC'));
$populateUntilDateTime = new DateTime("now", $utc);
Application_Model_Preference::SetShowsPopulatedUntil($populateUntilDateTime);
} else {
$populateUntilDateTime = clone $date;
@ -164,7 +166,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
} elseif (!$formData["add_show_no_end"]) {
$popUntil = $formData["add_show_end_date"]." ".$formData["add_show_end_time"];
$populateUntilDateTime = new DateTime($popUntil);
$populateUntilDateTime->setTimezone(new DateTimeZone('UTC'));
$populateUntilDateTime->setTimezone($utc);
}
//get repeat interval
@ -203,8 +205,18 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
else
$daysAdd = $day - $startDow;
/* In case we are crossing daylights saving time we need
* to convert show start and show end to local time before
* adding the interval for the next repeating show
*/
$repeatShowStart->setTimezone($localTimezone);
$repeatShowEnd->setTimezone($localTimezone);
$repeatShowStart->add(new DateInterval("P".$daysAdd."D"));
$repeatShowEnd->add(new DateInterval("P".$daysAdd."D"));
//set back to UTC
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
}
/* Here we are checking each repeating show by
* the show day.
@ -238,8 +250,12 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows'));
break 1;
} else {
$repeatShowStart->setTimezone($localTimezone);
$repeatShowEnd->setTimezone($localTimezone);
$repeatShowStart->add(new DateInterval($interval));
$repeatShowEnd->add(new DateInterval($interval));
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
}
}
}

View file

@ -454,7 +454,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$column = CcFilesPeer::getTableMap()->getColumnByPhpName($criteria2PeerMap[$d['sp_criteria_field']]);
// validation on type of column
if ($d['sp_criteria_field'] == 'length') {
if (!preg_match("/(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) {
if (!preg_match("/^(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) {
$element->addError("'Length' should be in '00:00:00' format");
$isValid = false;
}

View file

@ -319,12 +319,12 @@ SQL;
if ($mins >59) {
$hour = intval($mins/60);
$hour = str_pad($hour, 2, "0", STR_PAD_LEFT);
$value = $mins%60;
$mins = $mins%60;
}
}
$hour = str_pad($hour, 2, "0", STR_PAD_LEFT);
$value = str_pad($value, 2, "0", STR_PAD_LEFT);
$length = $hour.":".$value.":00";
$mins = str_pad($mins, 2, "0", STR_PAD_LEFT);
$length = $hour.":".$mins.":00";
}
return $length;

View file

@ -287,7 +287,14 @@ SQL;
SQL;
$filesJoin = <<<SQL
cc_schedule AS sched
JOIN cc_files AS ft ON (sched.file_id = ft.id)
JOIN cc_files AS ft ON (sched.file_id = ft.id
AND ((sched.starts >= '{$p_start}'
AND sched.starts < '{$p_end}')
OR (sched.ends > '{$p_start}'
AND sched.ends <= '{$p_end}')
OR (sched.starts <= '{$p_start}'
AND sched.ends >= '{$p_end}'))
)
SQL;
@ -307,7 +314,14 @@ SQL;
SQL;
$streamJoin = <<<SQL
cc_schedule AS sched
JOIN cc_webstream AS ws ON (sched.stream_id = ws.id)
JOIN cc_webstream AS ws ON (sched.stream_id = ws.id
AND ((sched.starts >= '{$p_start}'
AND sched.starts < '{$p_end}')
OR (sched.ends > '{$p_start}'
AND sched.ends <= '{$p_end}')
OR (sched.starts <= '{$p_start}'
AND sched.ends >= '{$p_end}'))
)
LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id)
SQL;
@ -713,6 +727,7 @@ SQL;
'end' => $stream_end,
'uri' => $uri,
'type' => 'stream_buffer_end',
'row_id' => $item["id"],
'independent_event' => true
);
self::appendScheduleItem($data, $stream_end, $schedule_item);
@ -1127,7 +1142,6 @@ SQL;
}
} else {
if ($isAdminOrPM) {
Logging::info( $data );
Application_Model_Show::create($data);
}

View file

@ -1743,7 +1743,8 @@ SQL;
$days = $interval->format('%a');
$shows = Application_Model_Show::getShows($p_start, $p_end);
$nowEpoch = time();
$content_count = Application_Model_ShowInstance::getContentCount(
$p_start, $p_end);
$timezone = date_default_timezone_get();
foreach ($shows as $show) {
@ -1789,9 +1790,9 @@ SQL;
$showInstance = new Application_Model_ShowInstance(
$show["instance_id"]);
$showContent = $showInstance->getShowListContent();
$options["show_empty"] = empty($showContent) ? 1 : 0;
$options["show_empty"] = (array_key_exists($show['instance_id'],
$content_count)) ? 0 : 1;
$events[] = &self::makeFullCalendarEvent($show, $options,
$startsDT, $endsDT, $startsEpochStr, $endsEpochStr);

View file

@ -198,7 +198,9 @@ class Application_Model_ShowBuilder
} elseif (intval($p_item["si_record"]) === 1) {
$row["record"] = true;
if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
// at the time of creating on show, the recorded file is not in the DB yet.
// therefore, 'si_file_id' is null. So we need to check it.
if (Application_Model_Preference::GetUploadToSoundcloudOption() && isset($p_item['si_file_id'])) {
$file = Application_Model_StoredFile::Recall(
$p_item['si_file_id']);
if (isset($file)) {
@ -398,7 +400,7 @@ class Application_Model_ShowBuilder
//see if the displayed show instances have changed. (deleted,
//empty schedule etc)
if ($outdated === false && count($instances)
if ($outdated === false && count($instances)
!== count($currentInstances)) {
Logging::debug("show instances have changed.");
$outdated = true;
@ -459,7 +461,7 @@ class Application_Model_ShowBuilder
$display_items[] = $row;
}
if ($current_id !== -1 &&
if ($current_id !== -1 &&
!in_array($current_id, $this->showInstances)) {
$this->showInstances[] = $current_id;
}

View file

@ -661,6 +661,53 @@ SQL;
return $returnStr;
}
public static function getContentCount($p_start, $p_end)
{
$sql = <<<SQL
SELECT instance_id,
count(*) AS instance_count
FROM cc_schedule
WHERE ends > :p_start::TIMESTAMP
AND starts < :p_end::TIMESTAMP
GROUP BY instance_id
SQL;
$counts = Application_Common_Database::prepareAndExecute($sql, array(
':p_start' => $p_start->format("Y-m-d G:i:s"),
':p_end' => $p_end->format("Y-m-d G:i:s"))
, 'all');
$real_counts = array();
foreach ($counts as $c) {
$real_counts[$c['instance_id']] = $c['instance_count'];
}
return $real_counts;
}
public function showEmpty()
{
$sql = <<<SQL
SELECT s.starts
FROM cc_schedule AS s
WHERE s.instance_id = :instance_id
AND s.playout_status >= 0
AND ((s.stream_id IS NOT NULL)
OR (s.file_id IS NOT NULL)) LIMIT 1
SQL;
# TODO : use prepareAndExecute properly
$res = Application_Common_Database::prepareAndExecute($sql,
array( ':instance_id' => $this->_instanceId ), 'all' );
# TODO : A bit retarded. fix this later
foreach ($res as $r) {
return false;
}
return true;
}
public function getShowListContent()
{
$con = Propel::getConnection();
@ -670,15 +717,15 @@ SELECT *
FROM (
(SELECT s.starts,
0::INTEGER as type ,
f.id AS item_id,
f.id AS item_id,
f.track_title,
f.album_title AS album,
f.genre AS genre,
f.length AS length,
f.artist_name AS creator,
f.file_exists AS EXISTS,
f.filepath AS filepath,
f.mime AS mime
f.album_title AS album,
f.genre AS genre,
f.length AS length,
f.artist_name AS creator,
f.file_exists AS EXISTS,
f.filepath AS filepath,
f.mime AS mime
FROM cc_schedule AS s
LEFT JOIN cc_files AS f ON f.id = s.file_id
WHERE s.instance_id = :instance_id1
@ -689,12 +736,12 @@ FROM (
1::INTEGER as type,
ws.id AS item_id,
(ws.name || ': ' || ws.url) AS title,
null AS album,
null AS genre,
ws.length AS length,
sub.login AS creator,
't'::boolean AS EXISTS,
ws.url AS filepath,
null AS album,
null AS genre,
ws.length AS length,
sub.login AS creator,
't'::boolean AS EXISTS,
ws.url AS filepath,
ws.mime as mime
FROM cc_schedule AS s
LEFT JOIN cc_webstream AS ws ON ws.id = s.stream_id

View file

@ -127,9 +127,9 @@ class CcSchedule extends BaseCcSchedule {
}
if ($microsecond == 0) {
$this->fadein = $dt->format('H:i:s.u');
$this->fade_in = $dt->format('H:i:s.u');
} else {
$this->fadein = $dt->format('H:i:s').".".$microsecond;
$this->fade_in = $dt->format('H:i:s').".".$microsecond;
}
$this->modifiedColumns[] = CcSchedulePeer::FADE_IN;
@ -164,9 +164,9 @@ class CcSchedule extends BaseCcSchedule {
}
if ($microsecond == 0) {
$this->fadeout = $dt->format('H:i:s.u');
$this->fade_out = $dt->format('H:i:s.u');
} else {
$this->fadeout = $dt->format('H:i:s').".".$microsecond;
$this->fade_out = $dt->format('H:i:s').".".$microsecond;
}
$this->modifiedColumns[] = CcSchedulePeer::FADE_OUT;

View file

@ -53,7 +53,7 @@ class CcPlaylistTableMap extends TableMap {
*/
public function buildRelations()
{
$this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), null, null);
$this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), 'CASCADE', null);
$this->addRelation('CcPlaylistcontents', 'CcPlaylistcontents', RelationMap::ONE_TO_MANY, array('id' => 'playlist_id', ), 'CASCADE', null);
} // buildRelations()

View file

@ -63,7 +63,7 @@ class CcSubjsTableMap extends TableMap {
$this->addRelation('CcFilesRelatedByDbEditedby', 'CcFiles', RelationMap::ONE_TO_MANY, array('id' => 'editedby', ), null, null);
$this->addRelation('CcPerms', 'CcPerms', RelationMap::ONE_TO_MANY, array('id' => 'subj', ), 'CASCADE', null);
$this->addRelation('CcShowHosts', 'CcShowHosts', RelationMap::ONE_TO_MANY, array('id' => 'subjs_id', ), 'CASCADE', null);
$this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), null, null);
$this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), 'CASCADE', null);
$this->addRelation('CcBlock', 'CcBlock', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), null, null);
$this->addRelation('CcPref', 'CcPref', RelationMap::ONE_TO_MANY, array('id' => 'subjid', ), 'CASCADE', null);
$this->addRelation('CcSess', 'CcSess', RelationMap::ONE_TO_MANY, array('id' => 'userid', ), 'CASCADE', null);

View file

@ -404,6 +404,9 @@ abstract class BaseCcSubjsPeer {
// Invalidate objects in CcShowHostsPeer instance pool,
// since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule.
CcShowHostsPeer::clearInstancePool();
// Invalidate objects in CcPlaylistPeer instance pool,
// since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule.
CcPlaylistPeer::clearInstancePool();
// Invalidate objects in CcPrefPeer instance pool,
// since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule.
CcPrefPeer::clearInstancePool();

View file

@ -49,7 +49,7 @@
</dd>
<dt id="master_username-label">
<label class="optional" for="master_username"><?php echo $this->element->getElement('master_username')->getLabel() ?> :
<span class='stream_username_help_icon'></span>
<span class='master_username_help_icon'></span>
</label>
</dt>
<dd id="master_username-element">

View file

@ -91,9 +91,6 @@
<index name="cc_files_name_idx">
<index-column name="name"/>
</index>
<index name="cc_files_file_exists_idx">
<index-column name="file_exists"/>
</index>
</table>
<table name="cc_perms" phpName="CcPerms">
<column name="permid" phpName="Permid" type="INTEGER" primaryKey="true" required="true"/>
@ -206,7 +203,7 @@
<parameter name="foreign_table" value="cc_playlistcontents" />
<parameter name="expression" value="SUM(cliplength)" />
</behavior>
<foreign-key foreignTable="cc_subjs" name="cc_playlist_createdby_fkey">
<foreign-key foreignTable="cc_subjs" name="cc_playlist_createdby_fkey" onDelete="CASCADE">
<reference local="creator_id" foreign="id"/>
</foreign-key>
</table>
@ -332,6 +329,9 @@
<foreign-key foreignTable="cc_webstream" name="cc_show_stream_fkey" onDelete="CASCADE">
<reference local="stream_id" foreign="id"/>
</foreign-key>
<index name="cc_schedule_instance_id_idx">
<index-column name="instance_id"/>
</index>
</table>
<table name="cc_sess" phpName="CcSess">
<column name="sessid" phpName="Sessid" type="CHAR" size="32" primaryKey="true" required="true"/>

View file

@ -105,8 +105,6 @@ CREATE INDEX "cc_files_md5_idx" ON "cc_files" ("md5");
CREATE INDEX "cc_files_name_idx" ON "cc_files" ("name");
CREATE INDEX "cc_files_file_exists_idx" ON "cc_files" ("file_exists");
-----------------------------------------------------------------------------
-- cc_perms
-----------------------------------------------------------------------------
@ -429,6 +427,8 @@ COMMENT ON TABLE "cc_schedule" IS '';
SET search_path TO public;
CREATE INDEX "cc_schedule_instance_id_idx" ON "cc_schedule" ("instance_id");
-----------------------------------------------------------------------------
-- cc_sess
-----------------------------------------------------------------------------
@ -689,7 +689,7 @@ ALTER TABLE "cc_show_hosts" ADD CONSTRAINT "cc_perm_show_fkey" FOREIGN KEY ("sho
ALTER TABLE "cc_show_hosts" ADD CONSTRAINT "cc_perm_host_fkey" FOREIGN KEY ("subjs_id") REFERENCES "cc_subjs" ("id") ON DELETE CASCADE;
ALTER TABLE "cc_playlist" ADD CONSTRAINT "cc_playlist_createdby_fkey" FOREIGN KEY ("creator_id") REFERENCES "cc_subjs" ("id");
ALTER TABLE "cc_playlist" ADD CONSTRAINT "cc_playlist_createdby_fkey" FOREIGN KEY ("creator_id") REFERENCES "cc_subjs" ("id") ON DELETE CASCADE;
ALTER TABLE "cc_playlistcontents" ADD CONSTRAINT "cc_playlistcontents_file_id_fkey" FOREIGN KEY ("file_id") REFERENCES "cc_files" ("id") ON DELETE CASCADE;

View file

@ -104,7 +104,8 @@ select {
line-height:16px !important;
}
.airtime_auth_help_icon, .custom_auth_help_icon, .stream_username_help_icon, .playlist_type_help_icon {
.airtime_auth_help_icon, .custom_auth_help_icon, .stream_username_help_icon,
.playlist_type_help_icon, .master_username_help_icon {
cursor: help;
position: relative;
display:inline-block; zoom:1;

View file

@ -0,0 +1,5 @@
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
});

View file

@ -333,6 +333,27 @@ $(document).ready(function() {
})
$(".stream_username_help_icon").qtip({
content: {
text: "If your Icecast server expects a username of 'source', this field can be left blank."
},
hide: {
delay: 500,
fixed: true
},
style: {
border: {
width: 0,
radius: 4
},
classes: "ui-tooltip-dark ui-tooltip-rounded"
},
position: {
my: "left bottom",
at: "right center"
},
})
$(".master_username_help_icon").qtip({
content: {
text: "If your live streaming client does not ask for a username, this field should be 'source'."
},

View file

@ -206,7 +206,6 @@ function viewDisplay( view ) {
}
function eventRender(event, element, view) {
getCurrentShow();
$(element).data("event", event);
@ -371,7 +370,9 @@ function checkSCUploadStatus(){
});
});
}
/** This function adds and removes the current
* show icon
*/
function getCurrentShow(){
var url = '/Schedule/get-current-show/format/json',
id,

View file

@ -283,7 +283,7 @@ var AIRTIME = (function(AIRTIME){
mod.fnRemove = function(aItems) {
mod.disableUI();
if (confirm("Delete selected item(s)?")) {
if (confirm("Remove selected scheduled item(s)?")) {
$.post( "/showbuilder/schedule-remove",
{"items": aItems, "format": "json"},
mod.fnItemCallback

View file

@ -111,6 +111,10 @@ class UpgradeCommon{
$old = "list_all_db_files = 'list-all-files/format/json/api_key/%%api_key%%/dir_id/%%dir_id%%'";
$new = "list_all_db_files = 'list-all-files/format/json/api_key/%%api_key%%/dir_id/%%dir_id%%/all/%%all%%'";
exec("sed -i \"s#$old#$new#g\" /etc/airtime/api_client.cfg");
$old = "update_start_playing_url = 'notify-media-item-start-play/api_key/%%api_key%%/media_id/%%media_id%%/schedule_id/%%schedule_id%%'";
$new = "update_start_playing_url = 'notify-media-item-start-play/api_key/%%api_key%%/media_id/%%media_id%%/'";
exec("sed -i \"s#$old#$new#g\" /etc/airtime/api_client.cfg");
}
/**

View file

@ -14,6 +14,13 @@ INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_channels', 'ste
INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_channels', 'stereo', 'string');
CREATE FUNCTION airtime_to_int(chartoconvert character varying) RETURNS integer
AS
'SELECT CASE WHEN trim($1) SIMILAR TO ''[0-9]+'' THEN CAST(trim($1) AS integer) ELSE NULL END;'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
--clean up database of scheduled items that weren't properly deleted in 2.1.x
--due to a bug
DELETE
@ -27,14 +34,9 @@ WHERE id IN
ALTER TABLE cc_files
DROP CONSTRAINT cc_files_gunid_idx;
DROP TABLE cc_access;
DROP INDEX cc_files_file_exists_idx;
CREATE FUNCTION airtime_to_int(chartoconvert character varying) RETURNS integer
AS
'SELECT CASE WHEN trim($1) SIMILAR TO ''[0-9]+'' THEN CAST(trim($1) AS integer) ELSE NULL END;'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
DROP TABLE cc_access;
CREATE SEQUENCE cc_block_id_seq
START WITH 1
@ -140,6 +142,12 @@ ALTER TABLE cc_playlistcontents
ALTER TABLE cc_schedule
ADD COLUMN stream_id integer;
CREATE INDEX cc_schedule_instance_id_idx
ON cc_schedule
USING btree
(instance_id);
ALTER TABLE cc_subjs
ADD COLUMN cell_phone character varying(255);
@ -179,6 +187,33 @@ ALTER TABLE cc_schedule
ALTER TABLE cc_webstream_metadata
ADD CONSTRAINT cc_schedule_inst_fkey FOREIGN KEY (instance_id) REFERENCES cc_schedule(id) ON DELETE CASCADE;
ALTER TABLE cc_playlist
DROP CONSTRAINT cc_playlist_createdby_fkey;
ALTER SEQUENCE cc_block_id_seq
OWNED BY cc_block.id;
ALTER SEQUENCE cc_blockcontents_id_seq
OWNED BY cc_blockcontents.id;
ALTER SEQUENCE cc_blockcriteria_id_seq
OWNED BY cc_blockcriteria.id;
ALTER SEQUENCE cc_webstream_id_seq
OWNED BY cc_webstream.id;
ALTER SEQUENCE cc_webstream_metadata_id_seq
OWNED BY cc_webstream_metadata.id;
ALTER TABLE cc_playlist
ADD CONSTRAINT cc_playlist_createdby_fkey FOREIGN KEY (creator_id) REFERENCES cc_subjs(id) ON DELETE CASCADE;
DROP FUNCTION airtime_to_int(chartoconvert character varying);
UPDATE cc_files

View file

@ -117,3 +117,5 @@ get_files_without_replay_gain = 'get-files-without-replay-gain/api_key/%%api_key
update_replay_gain_value = 'update-replay-gain-value/api_key/%%api_key%%'
notify_webstream_data = 'notify-webstream-data/api_key/%%api_key%%/media_id/%%media_id%%/format/json'
notify_liquidsoap_started = 'rabbitmq-do-push/api_key/%%api_key%%/format/json'

View file

@ -199,6 +199,7 @@ class NewFile(BaseEvent, HasMetaData):
"""
req_dict = self.metadata.extract()
req_dict['mode'] = u'create'
req_dict['is_record'] = self.metadata.is_recorded()
self.assign_owner(req_dict)
req_dict['MDATA_KEY_FILEPATH'] = unicode( self.path )
return [req_dict]

View file

@ -27,7 +27,7 @@ def append_title(m) =
end
end
def crossfade(s)
def crossfade_airtime(s)
#duration is automatically overwritten by metadata fields passed in
#with audio
s = fade.in(type="log", duration=0., s)
@ -402,6 +402,11 @@ def set_dynamic_source_id(id) =
string_of(!current_dyn_id)
end
def get_dynamic_source_id() =
string_of(!current_dyn_id)
end
# Function to create a playlist source and output it.
def create_dynamic_source(uri) =
# The playlist source
@ -413,7 +418,7 @@ def create_dynamic_source(uri) =
# We register both source and output
# in the list of sources
dyn_sources :=
list.append([(uri,s),(uri,active_dyn_out)], !dyn_sources)
list.append([(!current_dyn_id, s),(!current_dyn_id, active_dyn_out)], !dyn_sources)
notify([("schedule_table_id", !current_dyn_id)])
"Done!"
@ -421,7 +426,62 @@ end
# A function to destroy a dynamic source
def destroy_dynamic_source_all(uri) =
def destroy_dynamic_source(id) =
# We need to find the source in the list,
# remove it and destroy it. Currently, the language
# lacks some nice operators for that so we do it
# the functional way
# This function is executed on every item in the list
# of dynamic sources
def parse_list(ret, current_element) =
# ret is of the form: (matching_sources, remaining_sources)
# We extract those two:
matching_sources = fst(ret)
remaining_sources = snd(ret)
# current_element is of the form: ("uri", source) so
# we check the first element
current_id = fst(current_element)
if current_id == id then
# In this case, we add the source to the list of
# matched sources
(list.append( [snd(current_element)],
matching_sources),
remaining_sources)
else
# In this case, we put the element in the list of remaining
# sources
(matching_sources,
list.append([current_element],
remaining_sources))
end
end
# Now we execute the function:
result = list.fold(parse_list, ([], []), !dyn_sources)
matching_sources = fst(result)
remaining_sources = snd(result)
# We store the remaining sources in dyn_sources
dyn_sources := remaining_sources
# If no source matched, we return an error
if list.length(matching_sources) == 0 then
"Error: no matching sources!"
else
# We stop all sources
list.iter(source.shutdown, matching_sources)
# And return
"Done!"
end
end
# A function to destroy a dynamic source
def destroy_dynamic_source_all() =
# We need to find the source in the list,
# remove it and destroy it. Currently, the language
# lacks some nice operators for that so we do it
@ -466,57 +526,3 @@ end
# A function to destroy a dynamic source
def destroy_dynamic_source(uri) =
# We need to find the source in the list,
# remove it and destroy it. Currently, the language
# lacks some nice operators for that so we do it
# the functional way
# This function is executed on every item in the list
# of dynamic sources
def parse_list(ret, current_element) =
# ret is of the form: (matching_sources, remaining_sources)
# We extract those two:
matching_sources = fst(ret)
remaining_sources = snd(ret)
# current_element is of the form: ("uri", source) so
# we check the first element
current_uri = fst(current_element)
if current_uri == uri then
# In this case, we add the source to the list of
# matched sources
(list.append( [snd(current_element)],
matching_sources),
remaining_sources)
else
# In this case, we put the element in the list of remaining
# sources
(matching_sources,
list.append([current_element],
remaining_sources))
end
end
# Now we execute the function:
result = list.fold(parse_list, ([], []), !dyn_sources)
matching_sources = fst(result)
remaining_sources = snd(result)
# We store the remaining sources in dyn_sources
dyn_sources := remaining_sources
# If no source matched, we return an error
if list.length(matching_sources) == 0 then
"Error: no matching sources!"
else
# We stop all sources
list.iter(source.shutdown, matching_sources)
# And return
"Done!"
end
end

View file

@ -19,7 +19,7 @@ queue = amplify(1., override="replay_gain", queue)
#live stream setup
set("harbor.bind_addr", "0.0.0.0")
current_dyn_id = ref ''
current_dyn_id = ref '-1'
pypo_data = ref '0'
stream_metadata_type = ref 0
@ -43,10 +43,11 @@ web_stream = input.harbor("test-harbor", port=8999, password=stream_harbor_pass)
web_stream = on_metadata(notify_stream, web_stream)
output.dummy(fallible=true, web_stream)
# the crossfade function controls fade in/out
queue = crossfade_airtime(queue)
queue = on_metadata(notify, queue)
queue = map_metadata(update=false, append_title, queue)
# the crossfade function controls fade in/out
queue = crossfade(queue)
output.dummy(fallible=true, queue)
@ -95,21 +96,28 @@ server.register(namespace="dynamic_source",
usage="id <id>",
"id",
fun (s) -> begin log("dynamic_source.id") set_dynamic_source_id(s) end)
server.register(namespace="dynamic_source",
description="Get the cc_schedule row id",
usage="get_id",
"get_id",
fun (s) -> begin log("dynamic_source.get_id") get_dynamic_source_id() end)
server.register(namespace="dynamic_source",
description="Start a new dynamic source.",
usage="start <uri>",
"read_start",
fun (s) -> begin log("dynamic_source.read_start") create_dynamic_source(s) end)
fun (uri) -> begin log("dynamic_source.read_start") create_dynamic_source(uri) end)
server.register(namespace="dynamic_source",
description="Stop a dynamic source.",
usage="stop <uri>",
usage="stop <id>",
"read_stop",
fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source(s) end)
server.register(namespace="dynamic_source",
description="Stop a dynamic source.",
usage="stop <uri>",
usage="stop <id>",
"read_stop_all",
fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source_all(s) end)
fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source_all() end)
default = amplify(id="silence_src", 0.00001, noise())
default = rewrite_metadata([("artist","Airtime"), ("title", "offline")], default)

View file

@ -55,7 +55,6 @@ class PypoPush(Thread):
self.pushed_objects = {}
self.logger = logging.getLogger('push')
self.current_stream_info = None
self.current_prebuffering_stream_id = None
def main(self):
@ -78,6 +77,7 @@ class PypoPush(Thread):
#We get to the following lines only if a schedule was received.
liquidsoap_queue_approx = self.get_queue_items_from_liquidsoap()
liquidsoap_stream_id = self.get_current_stream_id_from_liquidsoap()
tnow = datetime.utcnow()
current_event_chain, original_chain = self.get_current_chain(chains, tnow)
@ -92,7 +92,7 @@ class PypoPush(Thread):
#is scheduled. We need to verify whether the schedule we just received matches
#what Liquidsoap is playing, and if not, correct it.
self.handle_new_schedule(media_schedule, liquidsoap_queue_approx, current_event_chain)
self.handle_new_schedule(media_schedule, liquidsoap_queue_approx, liquidsoap_stream_id, current_event_chain)
#At this point everything in the present has been taken care of and Liquidsoap
@ -134,6 +134,25 @@ class PypoPush(Thread):
loops = 0
loops += 1
def get_current_stream_id_from_liquidsoap(self):
response = "-1"
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(LS_HOST, LS_PORT)
msg = 'dynamic_source.get_id\n'
tn.write(msg)
response = tn.read_until("\r\n").strip(" \r\n")
tn.write('exit\n')
tn.read_all()
except Exception, e:
self.logger.error("Error connecting to Liquidsoap: %s", e)
response = []
finally:
self.telnet_lock.release()
return response
def get_queue_items_from_liquidsoap(self):
"""
This function connects to Liquidsoap to find what media items are in its queue.
@ -175,10 +194,10 @@ class PypoPush(Thread):
return liquidsoap_queue_approx
def is_correct_current_item(self, media_item, liquidsoap_queue_approx):
def is_correct_current_item(self, media_item, liquidsoap_queue_approx, liquidsoap_stream_id):
correct = False
if media_item is None:
correct = (len(liquidsoap_queue_approx) == 0 and self.current_stream_info is None)
correct = (len(liquidsoap_queue_approx) == 0 and liquidsoap_stream_id == "-1")
else:
if is_file(media_item):
if len(liquidsoap_queue_approx) == 0:
@ -188,10 +207,7 @@ class PypoPush(Thread):
liquidsoap_queue_approx[0]['row_id'] == media_item['row_id'] and \
liquidsoap_queue_approx[0]['end'] == media_item['end']
elif is_stream(media_item):
if self.current_stream_info is None:
correct = False
else:
correct = self.current_stream_info['row_id'] == media_item['row_id']
correct = liquidsoap_stream_id == str(media_item['row_id'])
self.logger.debug("Is current item correct?: %s", str(correct))
return correct
@ -202,7 +218,7 @@ class PypoPush(Thread):
self.remove_from_liquidsoap_queue(0, None)
self.stop_web_stream_all()
def handle_new_schedule(self, media_schedule, liquidsoap_queue_approx, current_event_chain):
def handle_new_schedule(self, media_schedule, liquidsoap_queue_approx, liquidsoap_stream_id, current_event_chain):
"""
This function's purpose is to gracefully handle situations where
Liquidsoap already has a track in its queue, but the schedule
@ -213,14 +229,13 @@ class PypoPush(Thread):
file_chain = filter(lambda item: (item["type"] == "file"), current_event_chain)
stream_chain = filter(lambda item: (item["type"] == "stream_output_start"), current_event_chain)
self.logger.debug(self.current_stream_info)
self.logger.debug(current_event_chain)
#Take care of the case where the current playing may be incorrect
if len(current_event_chain) > 0:
current_item = current_event_chain[0]
if not self.is_correct_current_item(current_item, liquidsoap_queue_approx):
if not self.is_correct_current_item(current_item, liquidsoap_queue_approx, liquidsoap_stream_id):
self.clear_all_liquidsoap_items()
if is_stream(current_item):
if current_item['row_id'] != self.current_prebuffering_stream_id:
@ -234,7 +249,7 @@ class PypoPush(Thread):
#we've changed the queue, so let's refetch it
liquidsoap_queue_approx = self.get_queue_items_from_liquidsoap()
elif not self.is_correct_current_item(None, liquidsoap_queue_approx):
elif not self.is_correct_current_item(None, liquidsoap_queue_approx, liquidsoap_stream_id):
#Liquidsoap is playing something even though it shouldn't be
self.clear_all_liquidsoap_items()
@ -455,6 +470,7 @@ class PypoPush(Thread):
tn = telnetlib.Telnet(LS_HOST, LS_PORT)
msg = 'dynamic_source.id %s\n' % media_item['row_id']
self.logger.debug(msg)
tn.write(msg)
#example: dynamic_source.read_start http://87.230.101.24:80/top100station.mp3
@ -489,7 +505,6 @@ class PypoPush(Thread):
self.logger.debug(tn.read_all())
self.current_prebuffering_stream_id = None
self.current_stream_info = media_item
except Exception, e:
self.logger.error(str(e))
finally:
@ -508,10 +523,13 @@ class PypoPush(Thread):
self.logger.debug(msg)
tn.write(msg)
msg = 'dynamic_source.id -1\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
self.current_stream_info = None
except Exception, e:
self.logger.error(str(e))
finally:
@ -523,14 +541,17 @@ class PypoPush(Thread):
tn = telnetlib.Telnet(LS_HOST, LS_PORT)
#dynamic_source.stop http://87.230.101.24:80/top100station.mp3
msg = 'dynamic_source.read_stop %s\n' % media_item['uri'].encode('latin-1')
msg = 'dynamic_source.read_stop %s\n' % media_item['row_id']
self.logger.debug(msg)
tn.write(msg)
msg = 'dynamic_source.id -1\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
self.current_stream_info = None
except Exception, e:
self.logger.error(str(e))
finally:
@ -549,7 +570,6 @@ class PypoPush(Thread):
tn.write("exit\n")
self.logger.debug(tn.read_all())
self.current_stream_info = None
except Exception, e:
self.logger.error(str(e))
finally: