Merge branch 'master' of dev.sourcefabric.org:campcaster

Conflicts:
	backend/tests/PlaylistTests.php
This commit is contained in:
naomiaro 2010-11-15 11:01:00 -05:00
commit 65a823561d
32 changed files with 2225 additions and 1997 deletions

View File

@ -17,7 +17,7 @@ def api_client_factory(config):
print 'API Client "'+config["api_client"]+'" not supported. Please check your config file.' print 'API Client "'+config["api_client"]+'" not supported. Please check your config file.'
print print
sys.exit() sys.exit()
class ApiClientInterface: class ApiClientInterface:
# This is optional. # This is optional.
@ -25,10 +25,16 @@ class ApiClientInterface:
# 3rd party software. # 3rd party software.
def check_version(self): def check_version(self):
nil nil
# Required.
# This is the main method you need to implement when creating a new API client. # This is the main method you need to implement when creating a new API client.
def get_schedule(self): def get_schedule(self):
return 0, [] return 0, []
# Required.
# This downloads the media from the server.
def get_media(self, src, dst):
nil
# This is optional. # This is optional.
# You dont actually have to implement this function for the liquidsoap playout to work. # You dont actually have to implement this function for the liquidsoap playout to work.
@ -76,7 +82,7 @@ class CampcasterApiClient(ApiClientInterface):
try: try:
if e[1] == 404: if e[1] == 404:
print '#####################################' print '#####################################'
print '# Unable to contact the OBP-API' print '# Unable to contact the Campcaster-API'
print '# ' + url print '# ' + url
print '#####################################' print '#####################################'
sys.exit() sys.exit()
@ -140,6 +146,18 @@ class CampcasterApiClient(ApiClientInterface):
return status, response return status, response
def get_media(self, src, dst):
logger = logging.getLogger("CampcasterApiClient.get_media")
try:
src = src + "&api_key=" + self.config["api_key"]
urllib.urlretrieve(src, dst, False)
logger.info("downloaded %s to %s", src, dst)
except Exception, e:
logger.error("%s", e)
def update_scheduled_item(self, item_id, value): def update_scheduled_item(self, item_id, value):
logger = logging.getLogger("CampcasterApiClient.update_scheduled_item") logger = logging.getLogger("CampcasterApiClient.update_scheduled_item")
@ -160,20 +178,18 @@ class CampcasterApiClient(ApiClientInterface):
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id): def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
return logger = logging.getLogger("CampcasterApiClient.update_scheduled_item")
logger = logging.getLogger("ApiClient.update_scheduled_item")
url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
url = self.api_url + 'schedule/update_start_playing.php' \ url = url.replace("%%playlist_type%%", str(playlist_type))
+ '?playlist_type=' + str(playlist_type) \ url = url.replace("%%export_source%%", str(export_source))
+ '&export_source=' + str(export_source) \ url = url.replace("%%media_id%%", str(media_id))
+ '&media_id=' + str(media_id) \ url = url.replace("%%playlist_id%%", str(playlist_id))
+ '&playlist_id=' + str(playlist_id) \ url = url.replace("%%transmission_id%%", str(transmission_id))
+ '&transmission_id=' + str(transmission_id)
print url print url
try: try:
response = urllib.urlopen(url, self.api_auth) response = urllib.urlopen(url)
response = json.read(response.read()) response = json.read(response.read())
logger.info("API-Status %s", response['status']) logger.info("API-Status %s", response['status'])
logger.info("API-Message %s", response['message']) logger.info("API-Message %s", response['message'])
@ -188,7 +204,7 @@ class CampcasterApiClient(ApiClientInterface):
def generate_range_dp(self): def generate_range_dp(self):
logger = logging.getLogger("ApiClient.generate_range_dp") logger = logging.getLogger("CampcasterApiClient.generate_range_dp")
url = self.api_url + 'schedule/generate_range_dp.php' url = self.api_url + 'schedule/generate_range_dp.php'
@ -208,6 +224,10 @@ class CampcasterApiClient(ApiClientInterface):
################################################################################ ################################################################################
# OpenBroadcast API Client
################################################################################
# Also check out the php counterpart that handles the api requests:
# https://lab.digris.ch/svn/elgg/trunk/unstable/mod/medialibrary/application/controllers/api/pypo.php
OBP_MIN_VERSION = 2010100101 # required obp version OBP_MIN_VERSION = 2010100101 # required obp version
@ -215,9 +235,8 @@ class ObpApiClient():
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
#self.api_url = api_url self.api_auth = urllib.urlencode({'api_key': self.config["api_key"]})
#self.api_auth = api_auth
def check_version(self): def check_version(self):
obp_version = self.get_obp_version() obp_version = self.get_obp_version()
@ -240,11 +259,12 @@ class ObpApiClient():
print 'pypo is compatible with this version of OBP' print 'pypo is compatible with this version of OBP'
print print
def get_obp_version(self): def get_obp_version(self):
logger = logging.getLogger("ApiClient.get_obp_version") logger = logging.getLogger("ObpApiClient.get_obp_version")
# lookup OBP version
# lookup OBP version
url = self.api_url + 'api/pypo/status/json' url = self.config["base_url"] + self.config["api_base"]+ self.config["version_url"]
try: try:
logger.debug("Trying to contact %s", url) logger.debug("Trying to contact %s", url)
@ -258,7 +278,7 @@ class ObpApiClient():
if e[1] == 401: if e[1] == 401:
print '#####################################' print '#####################################'
print '# YOUR API KEY SEEMS TO BE INVALID' print '# YOUR API KEY SEEMS TO BE INVALID'
print '# ' + self.api_auth print '# ' + self.config["api_auth"]
print '#####################################' print '#####################################'
sys.exit() sys.exit()
@ -279,15 +299,26 @@ class ObpApiClient():
obp_version = 0 obp_version = 0
logger.error("Unable to detect OBP Version - %s", e) logger.error("Unable to detect OBP Version - %s", e)
return obp_version return obp_version
def get_media(self, src, dest):
try:
print '** urllib auth with: ',
print self.api_auth
urllib.urlretrieve(src, dst, False, self.api_auth)
logger.info("downloaded %s to %s", src, dst)
except Exception, e:
logger.error("%s", e)
def update_scheduled_item(self, item_id, value): def update_scheduled_item(self, item_id, value):
logger = logging.getLogger("ApiClient.update_shedueled_item") logger = logging.getLogger("ObpApiClient.update_scheduled_item")
# lookup OBP version # lookup OBP version
url = self.api_url + 'api/pypo/update_scheduled_item/' + str(item_id) + '?played=' + str(value) url = self.config["base_url"] + self.config["api_base"] + self.config["update_item_url"]
url = url.replace("%%item_id%%", str(item_id))
url = url.replace("%%played%%", str(value))
try: try:
response = urllib.urlopen(url, self.api_auth) response = urllib.urlopen(url, self.api_auth)
@ -300,22 +331,18 @@ class ObpApiClient():
api_status = False api_status = False
logger.critical("Unable to connect to the OBP API - %s", e) logger.critical("Unable to connect to the OBP API - %s", e)
return response return response
def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id): def update_start_playing(self, playlist_type, export_source, media_id, playlist_id, transmission_id):
logger = logging.getLogger("ApiClient.update_scheduled_item")
logger = logging.getLogger("ApiClient.update_shedueled_item")
url = self.api_url + 'api/pypo/update_start_playing/' \
+ '?playlist_type=' + str(playlist_type) \
+ '&export_source=' + str(export_source) \
+ '&export_source=' + str(export_source) \
+ '&media_id=' + str(media_id) \
+ '&playlist_id=' + str(playlist_id) \
+ '&transmission_id=' + str(transmission_id)
url = self.config["base_url"] + self.config["api_base"] + self.config["update_start_playing_url"]
url = url.replace("%%playlist_type%%", str(playlist_type))
url = url.replace("%%export_source%%", str(export_source))
url = url.replace("%%media_id%%", str(media_id))
url = url.replace("%%playlist_id%%", str(playlist_id))
url = url.replace("%%transmission_id%%", str(transmission_id))
print url print url
try: try:
@ -330,14 +357,13 @@ class ObpApiClient():
api_status = False api_status = False
logger.critical("Unable to connect to the OBP API - %s", e) logger.critical("Unable to connect to the OBP API - %s", e)
return response return response
def generate_range_dp(self): def generate_range_dp(self):
logger = logging.getLogger("ApiClient.generate_range_dp") logger = logging.getLogger("ObpApiClient.generate_range_dp")
url = self.api_url + 'api/pypo/generate_range_dp/' url = self.config["base_url"] + self.config["api_base"] + self.config["generate_range_url"]
try: try:
response = urllib.urlopen(url, self.api_auth) response = urllib.urlopen(url, self.api_auth)

View File

@ -27,23 +27,40 @@ api_key = 'AAA'
# Hostname # Hostname
base_url = 'http://localhost/' base_url = 'http://localhost/'
################################################################################
# Generic Config - if you are creating a new API client, define these values #
################################################################################
# Path to the base of the API
api_base = ''
# URL to get the version number of the API
version_url = ''
# Schedule export path.
# %%from%% - starting date/time in the form YYYY-MM-DD-hh-mm
# %%to%% - starting date/time in the form YYYY-MM-DD-hh-mm
export_url = ''
# Update whether an item has been played.
# %%item_id%%
# %%played%%
update_item_url = ''
# Update whether an item is currently playing.
update_start_playing_url = ''
# ???
generate_range_url = ''
##################### #####################
# Campcaster Config # # Campcaster Config #
##################### #####################
# Path to the base of the API
api_base = 'campcaster/' api_base = 'campcaster/'
# URL to get the version number of the API
version_url = 'schedule/api_version.php?api_key=%%api_key%%' version_url = 'schedule/api_version.php?api_key=%%api_key%%'
# Schedule export path.
# YYYY-MM-DD-hh-mm will be substituted for the tokens %%from%% and %%to%%
export_url = 'schedule/schedule.php?from=%%from%%&to=%%to%%&api_key=%%api_key%%' export_url = 'schedule/schedule.php?from=%%from%%&to=%%to%%&api_key=%%api_key%%'
update_item_url = 'schedule/schedule.php?item_id=%%item_id%%&played=%%played%%' update_item_url = 'schedule/schedule.php?item_id=%%item_id%%&played=%%played%%'
update_start_playing_url = 'schedule/update_start_playing.php?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%' update_start_playing_url = 'schedule/update_start_playing.php?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
generate_range_url = 'schedule/generate_range_dp.php' generate_range_url = 'schedule/generate_range_dp.php'
@ -51,13 +68,11 @@ generate_range_url = 'schedule/generate_range_dp.php'
# OBP config # # OBP config #
############## ##############
#base_url = 'http://localhost/' #base_url = 'http://localhost/'
#api_base = BASE_URL #api_base = ''
#version_url = api_base + 'api/pypo/status/json' #version_url = 'api/pypo/status/json'
#update_item_url = api_base + 'api/pypo/update_shedueled_item/$$item_id%%?played=%%played%%' #update_item_url = 'api/pypo/update_shedueled_item/$$item_id%%?played=%%played%%'
#update_start_playing_url = 'api/pypo/update_start_playing/?playlist_type=%%playlist_type%%&export_source=%%export_source%%&media_id=%%media_id%%&playlist_id=%%playlist_id%%&transmission_id=%%transmission_id%%'
# prod config #generate_range_url = 'api/pypo/generate_range_dp/'
#base_url = ''
#api_key = ''
############################################ ############################################

View File

@ -8,8 +8,14 @@ Python part of radio playout (pypo)
The main functions are "fetch" (./pypo_cli.py -f) and "push" (./pypo_cli.py -p) The main functions are "fetch" (./pypo_cli.py -f) and "push" (./pypo_cli.py -p)
Also check out the php counterpart that handles the api requests: There are two layers: scheduler & daypart (fallback)
https://lab.digris.ch/svn/elgg/trunk/unstable/mod/medialibrary/application/controllers/api/pypo.php
The daypart is a fallback-layer generated by the playlists daypart-settings
(eg a playlist creator can say that the list is good for Monday and Tues,
between 14:00 and 16:00). So if there is nothing in the schedule, pypo will
still play something (instead of silence..) This layer is optional.
It is there so that you dont have a fallback player which plays the same 100
tracks over and over again.
Attention & ToDos Attention & ToDos
- liquidsoap does not like mono files! So we have to make sure that only files with - liquidsoap does not like mono files! So we have to make sure that only files with
@ -290,7 +296,6 @@ class Playout:
# TODO: maybe a bit more modular.. # TODO: maybe a bit more modular..
silence_file = self.file_dir + 'basic/silence.mp3' silence_file = self.file_dir + 'basic/silence.mp3'
if int(playlist['played']) == 1: if int(playlist['played']) == 1:
logger.info("playlist %s already played / sent to liquidsoap, so will ignore it", pkey) logger.info("playlist %s already played / sent to liquidsoap, so will ignore it", pkey)
@ -311,14 +316,14 @@ class Playout:
else: else:
print 'Could not find silence file!' print 'Could not find silence file!'
print 'file is excpected to be at: ' + silence_file print 'File is expected to be at: ' + silence_file
logger.critical('file is excpected to be at: %s', silence_file) logger.critical('File is expected to be at: %s', silence_file)
sys.exit() sys.exit()
elif int(playlist['subtype']) == 6: elif int(playlist['subtype']) == 6:
""" """
This is a live-cast session This is a live-cast session
create a silence list. (could eg also be a falback list..) Create a silence list. (could eg also be a fallback list..)
""" """
logger.debug("found %s seconds of live-cast session at %s", pkey, playlist['duration']) logger.debug("found %s seconds of live-cast session at %s", pkey, playlist['duration'])
@ -330,8 +335,8 @@ class Playout:
else: else:
print 'Could not find silence file!' print 'Could not find silence file!'
print 'file is excpected to be at: ' + silence_file print 'File is expected to be at: ' + silence_file
logger.critical('file is excpected to be at: %s', silence_file) logger.critical('File is expected to be at: %s', silence_file)
sys.exit() sys.exit()
@ -361,18 +366,16 @@ class Playout:
else: else:
logger.debug("try to download %s", src) logger.debug("try to download %s", src)
try: api_client.get_media(src, dst)
print '** urllib auth with: ', #try:
print self.api_auth # print '** urllib auth with: ',
urllib.urlretrieve (src, dst, False, self.api_auth) # print self.api_auth
logger.info("downloaded %s to %s", src, dst) # urllib.urlretrieve (src, dst, False, self.api_auth)
except Exception, e: # logger.info("downloaded %s to %s", src, dst)
logger.error("%s", e) #except Exception, e:
# logger.error("%s", e)
elif src[0:4] == 'http' and do_cue == True: elif src[0:4] == 'http' and do_cue == True:
if os.path.isfile(dst): if os.path.isfile(dst):
logger.debug("file already in cache: %s", dst) logger.debug("file already in cache: %s", dst)
print 'cached' print 'cached'
@ -384,15 +387,15 @@ class Playout:
dst_tmp = self.tmp_dir + "".join([random.choice(string.letters) for i in xrange(10)]) + '.mp3' dst_tmp = self.tmp_dir + "".join([random.choice(string.letters) for i in xrange(10)]) + '.mp3'
print dst_tmp print dst_tmp
print '***' print '***'
api_client.get_media(src, dst_tmp)
try: #try:
print '** urllib auth with: ', # print '** urllib auth with: ',
print self.api_auth # print self.api_auth
urllib.urlretrieve (src, dst_tmp, False, self.api_auth) # urllib.urlretrieve (src, dst_tmp, False, self.api_auth)
logger.info("downloaded %s to %s", src, dst_tmp) # logger.info("downloaded %s to %s", src, dst_tmp)
except Exception, e: #except Exception, e:
logger.error("%s", e) # logger.error("%s", e)
#
# cue # cue
print "STARTIONG CUE" print "STARTIONG CUE"
@ -447,9 +450,6 @@ class Playout:
except Exception, e: except Exception, e:
logger.error("%s", e) logger.error("%s", e)
if do_cue == True: if do_cue == True:
if os.path.isfile(dst): if os.path.isfile(dst):
@ -494,9 +494,6 @@ class Playout:
except Exception, e: except Exception, e:
logger.error("%s", e) logger.error("%s", e)
if True == os.access(dst, os.R_OK): if True == os.access(dst, os.R_OK):
# check filesize (avoid zero-byte files) # check filesize (avoid zero-byte files)
#print 'waiting: ' + dst #print 'waiting: ' + dst
@ -513,7 +510,6 @@ class Playout:
print pl_entry print pl_entry
""" """
Tracks are only added to the playlist if they are accessible Tracks are only added to the playlist if they are accessible
on the file system and larger than 0 bytes. on the file system and larger than 0 bytes.
@ -523,7 +519,6 @@ class Playout:
ls_playlist += pl_entry + "\n" ls_playlist += pl_entry + "\n"
logger.debug("everything ok, adding %s to playlist", pl_entry) logger.debug("everything ok, adding %s to playlist", pl_entry)
else: else:
print 'zero-file: ' + dst + ' from ' + src print 'zero-file: ' + dst + ' from ' + src
logger.warning("zero-size file - skiping %s. will not add it to playlist", dst) logger.warning("zero-size file - skiping %s. will not add it to playlist", dst)
@ -531,8 +526,6 @@ class Playout:
else: else:
logger.warning("something went wrong. file %s not available. will not add it to playlist", dst) logger.warning("something went wrong. file %s not available. will not add it to playlist", dst)
except Exception, e: logger.info("%s", e) except Exception, e: logger.info("%s", e)

View File

@ -38,7 +38,7 @@ from configobj import ConfigObj
# custom imports # custom imports
from util import * from util import *
from obp import * from api_clients import *
from dls import * from dls import *
PYPO_VERSION = '0.9' PYPO_VERSION = '0.9'

View File

@ -1,6 +1,7 @@
<?php <?php
require_once('../conf.php'); require_once('../conf.php');
require_once('DB.php'); require_once('DB.php');
require_once('../backend/StoredFile.php');
$api_key = $_GET['api_key']; $api_key = $_GET['api_key'];
if(!in_array($api_key, $CC_CONFIG["apiKey"])) if(!in_array($api_key, $CC_CONFIG["apiKey"]))
@ -19,20 +20,35 @@ if (PEAR::isError($CC_DBC)) {
} }
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
$file_id = $_GET[""] $file_id = $_GET["file_id"];
if(!is_file($src)) if (ctype_alnum($file_id) && strlen($file_id) == 32) {
{ $media = StoredFile::RecallByGunid($file_id);
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); if ($media != null && !PEAR::isError($media)) {
//print 'Ressource in database, but not in storage. Sorry.'; //var_dump($media);
exit; $filepath = $media->getRealFileName();
if(!is_file($filepath))
{
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
//print 'Ressource in database, but not in storage. Sorry.';
exit;
}
// !! binary mode !!
$fp = fopen($filepath, 'rb');
header("Content-Type: audio/mpeg");
header("Content-Length: " . filesize($filepath));
fpassthru($fp);
}
else {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
}
} else {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
} }
// !! binary mode !!
$fp = fopen($src, 'rb');
header("Content-Type: audio/mpeg");
header("Content-Length: " . filesize($src));
fpassthru($fp);
exit; exit;
?> ?>

View File

@ -288,42 +288,42 @@ class Backup
*/ */
private function setFilenames() private function setFilenames()
{ {
if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
$this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames\n"); // $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames\n");
} // }
if (is_array($this->ids)) { // if (is_array($this->ids)) {
foreach ($this->ids as $i => $item) { // foreach ($this->ids as $i => $item) {
$gunid = $item['gunid']; // $gunid = $item['gunid'];
// get a stored file object of this gunid // // get a stored file object of this gunid
$sf = StoredFile::RecallByGunid($gunid); // $sf = StoredFile::RecallByGunid($gunid);
if (is_null($sf) || PEAR::isError($sf)) { // if (is_null($sf) || PEAR::isError($sf)) {
return $sf; // return $sf;
} // }
$lid = BasicStor::IdFromGunid($gunid); // $lid = BasicStor::IdFromGunid($gunid);
if (($res = BasicStor::Authorize('read', $lid, $this->sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('read', $lid, $this->sessid)) !== TRUE) {
$this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - authorize gunid:$gunid\n"); // $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - authorize gunid:$gunid\n");
return PEAR::raiseError('Backup::setFilenames : Authorize ... error.'); // return PEAR::raiseError('Backup::setFilenames : Authorize ... error.');
} // }
// if the file is a playlist then it has only a meta file // // if the file is a playlist then it has only a meta file
if (strtolower($sf->md->format) != 'playlist') { // if (strtolower($sf->md->format) != 'playlist') {
$this->filenames[] = array( // $this->filenames[] = array(
'filename' => $sf->getRealFileName(), // 'filename' => $sf->getRealFileName(),
'format' => $sf->md->format // 'format' => $sf->md->format
); // );
} // }
$this->filenames[] = array( // $this->filenames[] = array(
'filename' => $sf->getRealMetadataFileName(), // 'filename' => $sf->getRealMetadataFileName(),
'format' => $sf->md->format // 'format' => $sf->md->format
); // );
if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
$this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames - add file: {$sf->md->format}|".$sf->getRealMetadataFileName()."\n"); // $this->addLogItem("-I- ".date("Ymd-H:i:s")." setFilenames - add file: {$sf->md->format}|".$sf->getRealMetadataFileName()."\n");
} // }
} // }
return $this->filenames; // return $this->filenames;
} else { // } else {
$this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - The IDs variable isn't array.\n"); // $this->addLogItem("-E- ".date("Ymd-H:i:s")." setFilenames - The IDs variable isn't array.\n");
return PEAR::raiseError('Backup::setFilenames : The IDs variable isn\'t array.'); // return PEAR::raiseError('Backup::setFilenames : The IDs variable isn\'t array.');
} // }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,11 @@
<?php <?php
if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
echo __FILE__.':line '.__LINE__.": Greenbox begin<br>";
}
require_once("BasicStor.php"); require_once("BasicStor.php");
if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) { if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
echo __FILE__.':line '.__LINE__.": Loaded BasicStor<br>"; echo __FILE__.':line '.__LINE__.": Loaded BasicStor<br>";
} }
require_once("LocStor.php");
if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
echo __FILE__.':line '.__LINE__.": Loaded LocStor<br>";
}
require_once("Playlist.php"); require_once("Playlist.php");
require_once("Renderer.php"); require_once("Renderer.php");
require_once('Prefs.php'); require_once('Prefs.php');
@ -51,7 +50,7 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('write', null, $p_sessionId)) !== TRUE) { if (($res = BasicStor::Authorize('write', null, $p_sessionId)) !== TRUE) {
return $res; return $res;
} }
$storedFile = $this->bsPutFile($p_values); $storedFile = StoredFile::Insert($p_values);
return $storedFile; return $storedFile;
} // fn putFile } // fn putFile
@ -87,12 +86,11 @@ class GreenBox extends BasicStor {
"gunid" => $gunid, "gunid" => $gunid,
"filetype" => "webstream" "filetype" => "webstream"
); );
$storedFile = $this->bsPutFile($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }
$oid = $storedFile->getId(); $r = $storedFile->setMetadataValue('ls:url', $url);
$r = $this->bsSetMetadataValue($oid, 'ls:url', $url);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
@ -152,13 +150,13 @@ class GreenBox extends BasicStor {
* Session id * Session id
* @return array * @return array
*/ */
public function analyzeFile($id, $sessid='') // public function analyzeFile($id, $sessid='')
{ // {
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res; // return $res;
} // }
return $this->bsAnalyzeFile($id); // return $this->bsAnalyzeFile($id);
} // fn analyzeFile // }
/** /**
@ -171,13 +169,13 @@ class GreenBox extends BasicStor {
* Session id * Session id
* @return boolean|PEAR_Error * @return boolean|PEAR_Error
*/ */
public function renameFile($id, $newName, $sessid='') // public function renameFile($id, $newName, $sessid='')
{ // {
if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
return $res; // return $res;
} // }
return $this->bsRenameFile($id, $newName); // return $this->bsRenameFile($id, $newName);
} // fn renameFile // }
/** /**
@ -193,23 +191,23 @@ class GreenBox extends BasicStor {
* session id * session id
* @return TRUE|PEAR_Error * @return TRUE|PEAR_Error
*/ */
public function replaceFile($id, $mediaFileLP, $mdataFileLP, $sessid='') // public function replaceFile($id, $mediaFileLP, $mdataFileLP, $sessid='')
{ // {
if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
return $res; // return $res;
} // }
return $this->bsReplaceFile($id, $mediaFileLP, $mdataFileLP); // return $this->bsReplaceFile($id, $mediaFileLP, $mdataFileLP);
} // fn replaceFile // }
/** /**
* Delete file * Delete file
* *
* @param int $id * @param int $id
* virt.file's local id * local id
* @param int $sessid * @param int $sessid
* @param boolean $forced * @param boolean $forced
* if true don't use trash * if true don't use trash -- now ignored
* @return true|PEAR_Error * @return true|PEAR_Error
*/ */
public function deleteFile($id, $sessid='', $forced=FALSE) public function deleteFile($id, $sessid='', $forced=FALSE)
@ -217,8 +215,9 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
return $res; return $res;
} }
return $this->bsDeleteFile($id, $forced); $f = StoredFile::Recall($id);
} // fn deleteFile return $f->delete(true);
}
/* ------------------------------------------------------------- metadata */ /* ------------------------------------------------------------- metadata */
@ -260,7 +259,8 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res; return $res;
} }
return $this->bsGetMetadata($id); $f = StoredFile::Recall($id);
return $f->getMetadata();
} }
@ -345,8 +345,9 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res; return $res;
} }
return $this->bsGetMetadataValue($id, $category); $f = StoredFile::Recall($id);
} // fn getMetadataValue return $f->getMetadataValue($category);
}
/** /**
@ -367,7 +368,8 @@ class GreenBox extends BasicStor {
if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('write', $id, $sessid)) !== TRUE) {
return $res; return $res;
} }
return $this->bsSetMetadataValue($id, $category, $value); $f = StoredFile::Recall($id);
return $f->setMetadataValue($category, $value);
} // fn setMetadataValue } // fn setMetadataValue
@ -560,7 +562,7 @@ class GreenBox extends BasicStor {
return; return;
$res = $pl->lock($sessid); $res = $pl->lock($sessid);
return $res; return $res;
} }
@ -743,10 +745,6 @@ class GreenBox extends BasicStor {
* current playtime (hh:mm:ss.ssssss) * current playtime (hh:mm:ss.ssssss)
* @param int $distance * @param int $distance
* 0=current clip; 1=next clip ... * 0=current clip; 1=next clip ...
* @param string $lang
* xml:lang value for select language version
* @param string $deflang
* xml:lang for default language
* @return array of matching clip info: * @return array of matching clip info:
* <ul> * <ul>
* <li>gunid string, global unique id of clip</li> * <li>gunid string, global unique id of clip</li>
@ -755,10 +753,9 @@ class GreenBox extends BasicStor {
* <li>duration string, total playlength of clip </li> * <li>duration string, total playlength of clip </li>
* </ul> * </ul>
*/ */
public function displayPlaylistClipAtOffset($sessid, $plid, $offset, $distance=0, public function displayPlaylistClipAtOffset($sessid, $plid, $offset, $distance=0)
$lang=NULL, $deflang=NULL)
{ {
$pl = StoredFile::RecallByGunid($plid); $pl = Playlist::Recall($plid);
if (is_null($pl) || PEAR::isError($pl)) { if (is_null($pl) || PEAR::isError($pl)) {
return $pl; return $pl;
} }
@ -767,23 +764,17 @@ class GreenBox extends BasicStor {
return $res; return $res;
} }
$res['title'] = NULL; $res['title'] = NULL;
$id = BasicStor::IdFromGunid($res['gunid']); $f = StoredFile::RecallByGunid($res['gunid']);
if (PEAR::isError($id)) { if (PEAR::isError($f)) {
return $id; return $f;
}
if (!is_null($id)) {
$res['title'] = $this->bsGetMetadataValue($id, "dc:title");
} }
$res['title'] = $f->getMetadataValue("dc:title");
$res['playlist_title'] = NULL; $res['playlist_title'] = NULL;
$id = BasicStor::IdFromGunid($plid); $pl = Playlist::Recall($plid);
if (PEAR::isError($id)) { $res['playlist'] = $pl->getName();
return $id;
}
if (!is_null($id)) {
$res['playlist'] = $this->bsGetMetadataValue($id, "dc:title");
}
return $res; return $res;
} // fn displayPlaylistClipAtOffset }
/** /**
@ -1100,7 +1091,7 @@ class GreenBox extends BasicStor {
$fakeFile = $CC_CONFIG['accessDir']."/$token.rss"; $fakeFile = $CC_CONFIG['accessDir']."/$token.rss";
if ($token != '123456789abcdeff' || !file_exists($fakeFile)){ if ($token != '123456789abcdeff' || !file_exists($fakeFile)){
return PEAR::raiseError( return PEAR::raiseError(
"LocStor::renderPlaylistToRSSCheck: invalid token ($token)" "renderPlaylistToRSSCheck: invalid token ($token)"
); );
} }
return array( return array(
@ -1592,20 +1583,6 @@ class GreenBox extends BasicStor {
/* ========================================================= info methods */ /* ========================================================= info methods */
/**
* Get type of stored file (by local id)
*
* @param int $id
* local id
* @return string|PEAR_Error
*/
public static function getFileType($id)
{
$type = BasicStor::GetObjType($id);
return $type;
} // fn getFileType
/** /**
* Check if file gunid exists in the storage and * Check if file gunid exists in the storage and
* user have permission to read it * user have permission to read it
@ -1619,12 +1596,11 @@ class GreenBox extends BasicStor {
*/ */
public function existsFile($sessid, $gunid, $ftype=NULL) public function existsFile($sessid, $gunid, $ftype=NULL)
{ {
$id = BasicStor::IdFromGunid($gunid); if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
$ex = $this->bsExistsFile($id, $ftype); return $res;
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { }
return $res; $f = StoredFile::RecallByGunid($gunid);
} return $f->existsFile();
return $ex;
} // fn existsFile } // fn existsFile

View File

@ -1,4 +1,7 @@
<?php <?php
if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
echo __FILE__.':line '.__LINE__.": LocStor loading<br>";
}
require_once("BasicStor.php"); require_once("BasicStor.php");
if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) { if (isset($WHITE_SCREEN_OF_DEATH) && $WHITE_SCREEN_OF_DEATH) {
echo __FILE__.':line '.__LINE__.": Loaded BasicStor<br>"; echo __FILE__.':line '.__LINE__.": Loaded BasicStor<br>";
@ -107,10 +110,7 @@ class LocStor extends BasicStor {
if ($fname == '') { if ($fname == '') {
$fname = "newFile"; $fname = "newFile";
} }
$res = $this->bsRenameFile($storedFile->id, $fname); $storedFile->setName($fname);
if (PEAR::isError($res)) {
return $res;
}
return $this->bsOpenPut($chsum, $storedFile->gunid); return $this->bsOpenPut($chsum, $storedFile->gunid);
} }
@ -194,8 +194,7 @@ class LocStor extends BasicStor {
if (is_null($storedFile) || PEAR::isError($storedFile)) { if (is_null($storedFile) || PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }
$oid = $storedFile->getId(); $r = $storedFile->setMetadataValue('ls:url', $url);
$r = $this-> bsSetMetadataValue($oid, 'ls:url', $url);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
return $r; return $r;
} }
@ -263,7 +262,8 @@ class LocStor extends BasicStor {
if (PEAR::isError($ex)) { if (PEAR::isError($ex)) {
return $ex; return $ex;
} }
$id = BasicStor::IdFromGunid($gunid); $media = StoredFile::RecallByGunid($gunid);
$id = $media->getId();
if (is_null($id) || !$ex) { if (is_null($id) || !$ex) {
return PEAR::raiseError( return PEAR::raiseError(
"LocStor::downloadRawAudioDataOpen: gunid not found ($gunid)", "LocStor::downloadRawAudioDataOpen: gunid not found ($gunid)",
@ -306,7 +306,8 @@ class LocStor extends BasicStor {
{ {
// $res = $this->existsAudioClip($sessid, $gunid); // $res = $this->existsAudioClip($sessid, $gunid);
// if(PEAR::isError($res)) return $res; // if(PEAR::isError($res)) return $res;
$id = BasicStor::IdFromGunid($gunid); $media = StoredFile::RecallByGunid($gunid)
$id = $media->getGunid();
if (is_null($id)) { if (is_null($id)) {
return PEAR::raiseError( return PEAR::raiseError(
"LocStor::downloadMetadataOpen: gunid not found ($gunid)" "LocStor::downloadMetadataOpen: gunid not found ($gunid)"
@ -351,7 +352,7 @@ class LocStor extends BasicStor {
if (($res = BasicStor::Authorize('read', $storedFile->getId(), $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('read', $storedFile->getId(), $sessid)) !== TRUE) {
return $res; return $res;
} }
$md = $this->bsGetMetadata($storedFile->getId()); $md = $storedFile->getMetadata();
if (PEAR::isError($md)) { if (PEAR::isError($md)) {
return $md; return $md;
} }
@ -504,15 +505,14 @@ class LocStor extends BasicStor {
*/ */
protected function existsFile($sessid, $gunid, $ftype=NULL) protected function existsFile($sessid, $gunid, $ftype=NULL)
{ {
$id = BasicStor::IdFromGunid($gunid);
if (is_null($id)) {
return FALSE;
}
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res; return $res;
} }
$ex = $this->bsExistsFile($id, $ftype); $f = StoredFile::RecallByGunid($gunid);
return $ex; if (PEAR::isError($f)) {
return FALSE;
}
return $f->existsFile();
} }
@ -540,7 +540,7 @@ class LocStor extends BasicStor {
if (($res = BasicStor::Authorize('write', $storedFile->getId(), $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('write', $storedFile->getId(), $sessid)) !== TRUE) {
return $res; return $res;
} }
$res = $this->bsDeleteFile($storedFile->getId(), $forced); $res = $storedFile->delete();
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
@ -602,26 +602,14 @@ class LocStor extends BasicStor {
"metadata" => dirname(__FILE__).'/emptyPlaylist.xml', "metadata" => dirname(__FILE__).'/emptyPlaylist.xml',
"gunid" => $playlistId, "gunid" => $playlistId,
"filetype" => "playlist"); "filetype" => "playlist");
// This is all wrong now.
$storedFile = StoredFile::Insert($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) {
$res = BasicStor::RemoveObj($oid);
return $storedFile;
}
if ($fname == '') { if ($fname == '') {
$fname = "newFile.xml"; $fname = "newFile.xml";
} }
$res = $this->bsRenameFile($oid, $fname); $storedFile->setName($fname);
if (PEAR::isError($res)) { $storedFile->setState('ready');
return $res; $storedFile->setMime('application/smil');
}
$res = $storedFile->setState('ready');
if (PEAR::isError($res)) {
return $res;
}
$res = $storedFile->setMime('application/smil');
if (PEAR::isError($res)) {
return $res;
}
return $storedFile->gunid; return $storedFile->gunid;
} }
@ -775,7 +763,7 @@ class LocStor extends BasicStor {
if (($res = BasicStor::Authorize('write', $storedFile->getId(), $sessid)) !== TRUE) { if (($res = BasicStor::Authorize('write', $storedFile->getId(), $sessid)) !== TRUE) {
return $res; return $res;
} }
$res = $this->bsDeleteFile($storedFile->getId(), $forced); $res = $storedFile->delete();
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
@ -803,32 +791,32 @@ class LocStor extends BasicStor {
* } * }
*/ */
public function accessPlaylist($sessid, $playlistId, $recursive=FALSE, $parent='0') public function accessPlaylist($sessid, $playlistId, $recursive=FALSE, $parent='0')
{ // {
if ($recursive) { // if ($recursive) {
require_once("AccessRecur.php"); // require_once("AccessRecur.php");
$r = AccessRecur::accessPlaylist($this, $sessid, $playlistId); // $r = AccessRecur::accessPlaylist($this, $sessid, $playlistId);
if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
return $r; // return $r;
} // }
return $r; // return $r;
} // }
$ex = $this->existsPlaylist($sessid, $playlistId); // $ex = $this->existsPlaylist($sessid, $playlistId);
if (PEAR::isError($ex)) { // if (PEAR::isError($ex)) {
return $ex; // return $ex;
} // }
if (!$ex) { // if (!$ex) {
return PEAR::raiseError( // return PEAR::raiseError(
"LocStor::accessPlaylist: playlist not found ($playlistId)", // "LocStor::accessPlaylist: playlist not found ($playlistId)",
GBERR_NOTF // GBERR_NOTF
); // );
} // }
$id = BasicStor::IdFromGunid($playlistId); // $id = BasicStor::IdFromGunid($playlistId);
if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) { // if (($res = BasicStor::Authorize('read', $id, $sessid)) !== TRUE) {
return $res; // return $res;
} // }
$res = $this->bsOpenDownload($id, 'metadata', $parent); // $res = $this->bsOpenDownload($id, 'metadata', $parent);
#unset($res['filename']); // #unset($res['filename']);
return $res; // return $res;
} }
@ -953,7 +941,8 @@ class LocStor extends BasicStor {
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
return BasicStor::GunidFromId($res); $media = StoredFile::Recall($id);
return $media->getGunId();
} }
@ -1444,7 +1433,7 @@ class LocStor extends BasicStor {
"gunid" => $pars['gunid'], "gunid" => $pars['gunid'],
"filetype" => "audioclip" "filetype" => "audioclip"
); );
$storedFile = $this->bsPutFile($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }
@ -1462,7 +1451,7 @@ class LocStor extends BasicStor {
"gunid" => $pars['gunid'], "gunid" => $pars['gunid'],
"filetype" => "playlist" "filetype" => "playlist"
); );
$storedFile = $this->bsPutFile($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }
@ -1534,97 +1523,99 @@ class LocStor extends BasicStor {
*/ */
function downloadOpen($sessid, $trtype, $pars=array()) function downloadOpen($sessid, $trtype, $pars=array())
{ {
global $CC_CONFIG; // global $CC_CONFIG;
switch ($trtype) { // switch ($trtype) {
case "unknown": // case "unknown":
case "audioclip": // case "audioclip":
case "metadata": // case "metadata":
case "playlist": // case "playlist":
case "playlistPkg": // case "playlistPkg":
if (!isset($pars['gunid'])) { // if (!isset($pars['gunid'])) {
return PEAR::raiseError("Archive::downloadOpen: gunid not set"); // return PEAR::raiseError("Archive::downloadOpen: gunid not set");
} // }
break; // break;
} // }
$gunid = $pars['gunid']; // $gunid = $pars['gunid'];
// resolve trtype by object type: // // resolve trtype by object type:
if ( ($trtype == 'unknown') || ($trtype == 'playlistPkg') ) { // if ( ($trtype == 'unknown') || ($trtype == 'playlistPkg') ) {
$trtype2 = BasicStor::GetType($gunid); // $media = StoredFile::RecallByGunid($gunid);
if (PEAR::isError($trtype2)) { // $trtype2 = $media->getType();
return $trtype2; // if (PEAR::isError($trtype2)) {
} // return $trtype2;
// required with content: // }
$trtype = ( ($trtype2 == 'playlist') && ($trtype == 'playlistPkg') ? // // required with content:
'playlistPkg' : $trtype2); // $trtype = ( ($trtype2 == 'playlist') && ($trtype == 'playlistPkg') ?
//return PEAR::raiseError("Archive::downloadOpen: TT=$trtype TT2=$trtype2 G=$gunid"); // 'playlistPkg' : $trtype2);
} // //return PEAR::raiseError("Archive::downloadOpen: TT=$trtype TT2=$trtype2 G=$gunid");
switch ($trtype) { // }
case "audioclip": // switch ($trtype) {
$res = $this->downloadRawAudioDataOpen($sessid, $gunid); // case "audioclip":
break; // $res = $this->downloadRawAudioDataOpen($sessid, $gunid);
case "metadata": // break;
$res = $this->downloadMetadataOpen($sessid, $gunid); // case "metadata":
break; // $res = $this->downloadMetadataOpen($sessid, $gunid);
case "playlist": // break;
$res = $this->accessPlaylist($sessid, $gunid); // case "playlist":
break; // $res = $this->accessPlaylist($sessid, $gunid);
case "playlistPkg": // break;
$res = $this->bsExportPlaylistOpen($gunid); // case "playlistPkg":
if (PEAR::isError($res)) { // $res = $this->bsExportPlaylistOpen($gunid);
return $res; // if (PEAR::isError($res)) {
} // return $res;
$tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_'); // }
$plfpath = "$tmpn.lspl"; // $tmpn = tempnam($CC_CONFIG['transDir'], 'plExport_');
copy($res['fname'], $plfpath); // $plfpath = "$tmpn.lspl";
$res = $this->bsExportPlaylistClose($res['token']); // copy($res['fname'], $plfpath);
if (PEAR::isError($res)) { // $res = $this->bsExportPlaylistClose($res['token']);
return $res; // if (PEAR::isError($res)) {
} // return $res;
$fname = "transported_playlist.lspl"; // }
$id = BasicStor::IdFromGunid($gunid); // $fname = "transported_playlist.lspl";
$acc = BasicStor::bsAccess($plfpath, 'lspl', NULL, 'download'); // $id = BasicStor::IdFromGunid($gunid);
if (PEAR::isError($acc)) { // $acc = BasicStor::bsAccess($plfpath, 'lspl', NULL, 'download');
return $acc; // if (PEAR::isError($acc)) {
} // return $acc;
$url = BasicStor::GetUrlPart()."access/".basename($acc['fname']); // }
$chsum = md5_file($plfpath); // $url = BasicStor::GetUrlPart()."access/".basename($acc['fname']);
$size = filesize($plfpath); // $chsum = md5_file($plfpath);
$res = array( // $size = filesize($plfpath);
'url'=>$url, 'token'=>$acc['token'], // $res = array(
'chsum'=>$chsum, 'size'=>$size, // 'url'=>$url, 'token'=>$acc['token'],
'filename'=>$fname // 'chsum'=>$chsum, 'size'=>$size,
); // 'filename'=>$fname
break; // );
case "searchjob": // break;
$res = $pars; // case "searchjob":
break; // $res = $pars;
case "file": // break;
$res = array(); // case "file":
break; // $res = array();
default: // break;
return PEAR::raiseError("Archive::downloadOpen: NotImpl ($trtype)"); // default:
} // return PEAR::raiseError("Archive::downloadOpen: NotImpl ($trtype)");
if (PEAR::isError($res)) { // }
return $res; // if (PEAR::isError($res)) {
} // return $res;
switch ($trtype) { // }
case "audioclip": // switch ($trtype) {
case "metadata": // case "audioclip":
case "playlist": // case "metadata":
case "playlistPkg": // case "playlist":
$title = $this->bsGetTitle(NULL, $gunid); // case "playlistPkg":
break; // $f = StoredFile::RecallByGunid($gunid);
case "searchjob": // $title = $f->getTitle();
$title = 'searchjob'; // break;
break; // case "searchjob":
case "file": // $title = 'searchjob';
$title = 'regular file'; // break;
break; // case "file":
default: // $title = 'regular file';
} // break;
$res['title'] = $title; // default:
$res['trtype'] = $trtype; // }
return $res; // $res['title'] = $title;
// $res['trtype'] = $trtype;
// return $res;
} }

View File

@ -73,65 +73,65 @@ class M3uPlaylist {
*/ */
function import(&$gb, $aPath, $rPath, &$gunids, $plid, $subjid=NULL) function import(&$gb, $aPath, $rPath, &$gunids, $plid, $subjid=NULL)
{ {
$path = realpath("$aPath/$rPath"); // $path = realpath("$aPath/$rPath");
if (FALSE === $path) { // if (FALSE === $path) {
return PEAR::raiseError( // return PEAR::raiseError(
"M3uPlaylist::import: file doesn't exist ($aPath/$rPath)" // "M3uPlaylist::import: file doesn't exist ($aPath/$rPath)"
); // );
} // }
$arr = M3uPlaylist::parse($path); // $arr = M3uPlaylist::parse($path);
if (PEAR::isError($arr)) { // if (PEAR::isError($arr)) {
return $arr; // return $arr;
} // }
require_once("Playlist.php"); // require_once("Playlist.php");
$pl =& Playlist::create($gb, $plid, "imported_M3U"); // $pl =& Playlist::create($gb, $plid, "imported_M3U");
if (PEAR::isError($pl)) { // if (PEAR::isError($pl)) {
return $pl; // return $pl;
} // }
$r = $pl->lock($gb, $subjid); // $r = $pl->lock($gb, $subjid);
if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
return $r; // return $r;
} // }
foreach ($arr as $i => $it) { // foreach ($arr as $i => $it) {
list($md, $uri) = preg_split("|\n|", $it); // list($md, $uri) = preg_split("|\n|", $it);
list($length, $title) = preg_split("|, *|", $md); // list($length, $title) = preg_split("|, *|", $md);
// $gunid = StoredFile::CreateGunid(); // // $gunid = StoredFile::CreateGunid();
$gunid = ( isset($gunids[basename($uri)]) ? $gunids[basename($uri)] : NULL); // $gunid = ( isset($gunids[basename($uri)]) ? $gunids[basename($uri)] : NULL);
$acId = BasicStor::IdFromGunid($gunid); // $acId = BasicStor::IdFromGunid($gunid);
if (PEAR::isError($acId)) { // if (PEAR::isError($acId)) {
return $acId; // return $acId;
} // }
$length = Playlist::secondsToPlaylistTime($length); // $length = Playlist::secondsToPlaylistTime($length);
$offset = '???'; // $offset = '???';
if (preg_match("|\.([a-zA-Z0-9]+)$|", $uri, $va)) { // if (preg_match("|\.([a-zA-Z0-9]+)$|", $uri, $va)) {
switch (strtolower($ext = $va[1])) { // switch (strtolower($ext = $va[1])) {
case "lspl": // case "lspl":
case "xml": // case "xml":
case "smil": // case "smil":
case "m3u": // case "m3u":
$acId = $gb->bsImportPlaylistRaw($gunid, // $acId = $gb->bsImportPlaylistRaw($gunid,
$aPath, $uri, $ext, $gunids, $subjid); // $aPath, $uri, $ext, $gunids, $subjid);
if (PEAR::isError($acId)) { // if (PEAR::isError($acId)) {
break; // break;
} // }
//no break! // //no break!
default: // default:
if (is_null($gunid)) { // if (is_null($gunid)) {
return PEAR::raiseError( // return PEAR::raiseError(
"M3uPlaylist::import: no gunid"); // "M3uPlaylist::import: no gunid");
} // }
$r = $pl->addAudioClip($acId); // $r = $pl->addAudioClip($acId);
if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
return $r; // return $r;
} // }
} // }
} // }
} // }
$r = $pl->unlock($gb); // $r = $pl->unlock($gb);
if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
return $r; // return $r;
} // }
return $pl; // return $pl;
} }
/** /**

View File

@ -68,7 +68,7 @@ class Playlist {
$storedPlaylist = new Playlist(); $storedPlaylist = new Playlist();
$storedPlaylist->name = isset($p_values['filename']) ? $p_values['filename'] : date("H:i:s"); $storedPlaylist->name = isset($p_values['filename']) ? $p_values['filename'] : date("H:i:s");
$storedPlaylist->mtime = new DateTime("now"); $storedPlaylist->mtime = new DateTime("now");
$pl = new CcPlaylist(); $pl = new CcPlaylist();
$pl->setDbName($storedPlaylist->name); $pl->setDbName($storedPlaylist->name);
$pl->setDbState("incomplete"); $pl->setDbState("incomplete");
@ -79,20 +79,30 @@ class Playlist {
$storedPlaylist->setState('ready'); $storedPlaylist->setState('ready');
return $storedPlaylist->id; return $storedPlaylist->id;
} }
public static function Delete($id) { public static function Delete($id) {
$pl = CcPlaylistQuery::create()->findPK($id); $pl = CcPlaylistQuery::create()->findPK($id);
if($pl === NULL) if($pl === NULL)
return FALSE; return FALSE;
$pl->delete();
return TRUE; $pl->delete();
return TRUE;
} }
/**
/**
* Delete the file from all playlists.
* @param string $p_fileId
*/
public static function DeleteFileFromAllPlaylists($p_fileId)
{
CcPlaylistcontentsQuery::create()->filterByDbFileId($p_fileId)->delete();
}
/**
* Fetch instance of Playlist object.<br> * Fetch instance of Playlist object.<br>
* *
* @param string $id * @param string $id
@ -126,10 +136,10 @@ class Playlist {
public function setName($p_newname) public function setName($p_newname)
{ {
$pl = CcPlaylistQuery::create()->findPK($this->id); $pl = CcPlaylistQuery::create()->findPK($this->id);
if($pl === NULL) if($pl === NULL)
return FALSE; return FALSE;
$pl->setDbName($p_newname); $pl->setDbName($p_newname);
$pl->setDbMtime(new DateTime("now")); $pl->setDbMtime(new DateTime("now"));
$pl->save(); $pl->save();
@ -153,7 +163,7 @@ class Playlist {
$pl = CcPlaylistQuery::create()->findPK($id); $pl = CcPlaylistQuery::create()->findPK($id);
if($pl === NULL) if($pl === NULL)
return FALSE; return FALSE;
return $pl->getDbName(); return $pl->getDbName();
} }
@ -169,18 +179,18 @@ class Playlist {
public function setState($p_state, $p_editedby=NULL) public function setState($p_state, $p_editedby=NULL)
{ {
$pl = CcPlaylistQuery::create()->findPK($this->id); $pl = CcPlaylistQuery::create()->findPK($this->id);
if($pl === NULL) if($pl === NULL)
return FALSE; return FALSE;
$pl->setDbState($p_state); $pl->setDbState($p_state);
$pl->setDbMtime(new DateTime("now")); $pl->setDbMtime(new DateTime("now"));
$eb = (!is_null($p_editedby) ? $p_editedby : NULL); $eb = (!is_null($p_editedby) ? $p_editedby : NULL);
$pl->setDbEditedby($eb); $pl->setDbEditedby($eb);
$pl->save(); $pl->save();
$this->state = $p_state; $this->state = $p_state;
$this->editedby = $p_editedby; $this->editedby = $p_editedby;
return TRUE; return TRUE;
@ -199,11 +209,11 @@ class Playlist {
if (is_null($id)) { if (is_null($id)) {
return $this->state; return $this->state;
} }
$pl = CcPlaylistQuery::create()->findPK($id); $pl = CcPlaylistQuery::create()->findPK($id);
if($pl === NULL) if($pl === NULL)
return FALSE; return FALSE;
return $pl->getDbState(); return $pl->getDbState();
} }
@ -237,15 +247,15 @@ class Playlist {
if (is_null($id)) { if (is_null($id)) {
return ($this->currentlyaccessing > 0); return ($this->currentlyaccessing > 0);
} }
$pl = CcPlaylistQuery::create()->findPK($id); $pl = CcPlaylistQuery::create()->findPK($id);
if (is_null($pl)) { if (is_null($pl)) {
return PEAR::raiseError( return PEAR::raiseError(
"StoredPlaylist::isAccessed: invalid id ($id)", "StoredPlaylist::isAccessed: invalid id ($id)",
GBERR_FOBJNEX GBERR_FOBJNEX
); );
} }
return ($pl->getDbCurrentlyaccessing() > 0); return ($pl->getDbCurrentlyaccessing() > 0);
} }
@ -309,7 +319,7 @@ class Playlist {
} }
private function getNextPos() { private function getNextPos() {
$res = CcPlaylistQuery::create() $res = CcPlaylistQuery::create()
->findPK($this->id) ->findPK($this->id)
->computeLastPosition(); ->computeLastPosition();
@ -325,24 +335,21 @@ class Playlist {
* @return array * @return array
*/ */
public function getContents() { public function getContents() {
$files = array();
$files;
$rows = CcPlaylistcontentsQuery::create() $rows = CcPlaylistcontentsQuery::create()
->joinWith('CcFiles') ->joinWith('CcFiles')
->orderByDbPosition() ->orderByDbPosition()
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->find(); ->find();
foreach ($rows as $row) { foreach ($rows as $row) {
$files[] = $row->toArray(BasePeer::TYPE_PHPNAME, true, true); $files[] = $row->toArray(BasePeer::TYPE_PHPNAME, true, true);
} }
return $files; return $files;
} }
public function getLength() { public function getLength() {
$res = CcPlaylistQuery::create() $res = CcPlaylistQuery::create()
->findPK($this->id) ->findPK($this->id)
->computeLength(); ->computeLength();
@ -426,9 +433,8 @@ class Playlist {
*/ */
public function addAudioClip($ac_id, $p_position=NULL, $p_fadeIn=NULL, $p_fadeOut=NULL, $p_clipLength=NULL, $p_cuein=NULL, $p_cueout=NULL) public function addAudioClip($ac_id, $p_position=NULL, $p_fadeIn=NULL, $p_fadeOut=NULL, $p_clipLength=NULL, $p_cuein=NULL, $p_cueout=NULL)
{ {
$_SESSION['debug'] = "in add"; $_SESSION['debug'] = "in add";
//get audio clip. //get audio clip.
$ac = StoredFile::Recall($ac_id); $ac = StoredFile::Recall($ac_id);
if (is_null($ac) || PEAR::isError($ac)) { if (is_null($ac) || PEAR::isError($ac)) {
@ -451,7 +457,7 @@ class Playlist {
return $p_position; return $p_position;
} }
// insert default values if parameter was empty // insert default values if parameter was empty
$p_cuein = !is_null($p_cuein) ? $p_cuein : '00:00:00.000000'; $p_cuein = !is_null($p_cuein) ? $p_cuein : '00:00:00.000000';
$p_cueout = !is_null($p_cueout) ? $p_cueout : $acLen; $p_cueout = !is_null($p_cueout) ? $p_cueout : $acLen;
@ -463,7 +469,7 @@ class Playlist {
$clipLengthS = $clipLengthS - ($acLengthS - self::playlistTimeToSeconds($p_cueout)); $clipLengthS = $clipLengthS - ($acLengthS - self::playlistTimeToSeconds($p_cueout));
} }
$p_clipLength = self::secondsToPlaylistTime($clipLengthS); $p_clipLength = self::secondsToPlaylistTime($clipLengthS);
$res = $this->insertPlaylistElement($this->id, $ac_id, $p_position, $p_clipLength, $p_cuein, $p_cueout, $p_fadeIn, $p_fadeOut); $res = $this->insertPlaylistElement($this->id, $ac_id, $p_position, $p_clipLength, $p_cuein, $p_cueout, $p_fadeIn, $p_fadeOut);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
@ -483,12 +489,12 @@ class Playlist {
{ {
if($pos < 0 || $pos >= $this->getNextPos()) if($pos < 0 || $pos >= $this->getNextPos())
return FALSE; return FALSE;
$row = CcPlaylistcontentsQuery::create() $row = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos) ->filterByDbPosition($pos)
->findOne(); ->findOne();
if(is_null($row)) if(is_null($row))
return FALSE; return FALSE;
@ -536,21 +542,21 @@ class Playlist {
public function changeFadeInfo($pos, $fadeIn, $fadeOut) public function changeFadeInfo($pos, $fadeIn, $fadeOut)
{ {
$errArray= array(); $errArray= array();
if(is_null($pos) || $pos < 0 || $pos >= $this->getNextPos()) { if(is_null($pos) || $pos < 0 || $pos >= $this->getNextPos()) {
$errArray["error"]="Invalid position."; $errArray["error"]="Invalid position.";
return $errArray; return $errArray;
} }
$row = CcPlaylistcontentsQuery::create() $row = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos) ->filterByDbPosition($pos)
->findOne(); ->findOne();
$clipLength = $row->getDbCliplength(); $clipLength = $row->getDbCliplength();
if(!is_null($fadeIn) && !is_null($fadeOut)) { if(!is_null($fadeIn) && !is_null($fadeOut)) {
if(Playlist::playlistTimeToSeconds($fadeIn) > Playlist::playlistTimeToSeconds($clipLength)) { if(Playlist::playlistTimeToSeconds($fadeIn) > Playlist::playlistTimeToSeconds($clipLength)) {
$errArray["error"]="Fade In can't be larger than overall playlength."; $errArray["error"]="Fade In can't be larger than overall playlength.";
return $errArray; return $errArray;
@ -559,29 +565,29 @@ class Playlist {
$errArray["error"]="Fade Out can't be larger than overall playlength."; $errArray["error"]="Fade Out can't be larger than overall playlength.";
return $errArray; return $errArray;
} }
$row->setDbFadein($fadeIn); $row->setDbFadein($fadeIn);
$row->setDbFadeout($fadeOut); $row->setDbFadeout($fadeOut);
} }
else if(!is_null($fadeIn)) { else if(!is_null($fadeIn)) {
if(Playlist::playlistTimeToSeconds($fadeIn) > Playlist::playlistTimeToSeconds($clipLength)) { if(Playlist::playlistTimeToSeconds($fadeIn) > Playlist::playlistTimeToSeconds($clipLength)) {
$errArray["error"]="Fade In can't be larger than overall playlength."; $errArray["error"]="Fade In can't be larger than overall playlength.";
return $errArray; return $errArray;
} }
$row->setDbFadein($fadeIn); $row->setDbFadein($fadeIn);
} }
else if(!is_null($fadeOut)){ else if(!is_null($fadeOut)){
if(Playlist::playlistTimeToSeconds($fadeOut) > Playlist::playlistTimeToSeconds($clipLength)) { if(Playlist::playlistTimeToSeconds($fadeOut) > Playlist::playlistTimeToSeconds($clipLength)) {
$errArray["error"]="Fade Out can't be larger than overall playlength."; $errArray["error"]="Fade Out can't be larger than overall playlength.";
return $errArray; return $errArray;
} }
$row->setDbFadeout($fadeOut); $row->setDbFadeout($fadeOut);
} }
$row->save(); $row->save();
return array("fadeIn"=>$fadeIn, "fadeOut"=>$fadeOut); return array("fadeIn"=>$fadeIn, "fadeOut"=>$fadeOut);
@ -601,34 +607,34 @@ class Playlist {
public function changeClipLength($pos, $cueIn, $cueOut) public function changeClipLength($pos, $cueIn, $cueOut)
{ {
$errArray= array(); $errArray= array();
if(is_null($cueIn) && is_null($cueOut)) { if(is_null($cueIn) && is_null($cueOut)) {
$errArray["error"]="Cue in and cue out are null."; $errArray["error"]="Cue in and cue out are null.";
return $errArray; return $errArray;
} }
if(is_null($pos) || $pos < 0 || $pos >= $this->getNextPos()) { if(is_null($pos) || $pos < 0 || $pos >= $this->getNextPos()) {
$errArray["error"]="Invalid position."; $errArray["error"]="Invalid position.";
return $errArray; return $errArray;
} }
$row = CcPlaylistcontentsQuery::create() $row = CcPlaylistcontentsQuery::create()
->joinWith(CcFiles) ->joinWith(CcFiles)
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos) ->filterByDbPosition($pos)
->findOne(); ->findOne();
$oldCueIn = $row->getDBCuein(); $oldCueIn = $row->getDBCuein();
$oldCueOut = $row->getDbCueout(); $oldCueOut = $row->getDbCueout();
$fadeIn = $row->getDbFadein(); $fadeIn = $row->getDbFadein();
$fadeOut = $row->getDbFadeout(); $fadeOut = $row->getDbFadeout();
$file = $row->getCcFiles(); $file = $row->getCcFiles();
$origLength = $file->getDbLength(); $origLength = $file->getDbLength();
if(!is_null($cueIn) && !is_null($cueOut)){ if(!is_null($cueIn) && !is_null($cueOut)){
if($cueOut === ""){ if($cueOut === ""){
$cueOut = $origLength; $cueOut = $origLength;
} }
@ -640,58 +646,58 @@ class Playlist {
$errArray["error"] = "Can't set cue out to be greater than file length."; $errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray; return $errArray;
} }
$row->setDbCuein($cueIn); $row->setDbCuein($cueIn);
$row->setDbCueout($cueOut); $row->setDbCueout($cueOut);
$row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($cueOut) $row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($cueOut)
- Playlist::playlistTimeToSeconds($cueIn))); - Playlist::playlistTimeToSeconds($cueIn)));
} }
else if(!is_null($cueIn)) { else if(!is_null($cueIn)) {
if(Playlist::playlistTimeToSeconds($cueIn) > Playlist::playlistTimeToSeconds($oldCueOut)) { if(Playlist::playlistTimeToSeconds($cueIn) > Playlist::playlistTimeToSeconds($oldCueOut)) {
$errArray["error"] = "Can't set cue in to be larger than cue out."; $errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray; return $errArray;
} }
$row->setDbCuein($cueIn); $row->setDbCuein($cueIn);
$row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($oldCueOut) $row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($oldCueOut)
- Playlist::playlistTimeToSeconds($cueIn))); - Playlist::playlistTimeToSeconds($cueIn)));
} }
else if(!is_null($cueOut)) { else if(!is_null($cueOut)) {
if($cueOut === ""){ if($cueOut === ""){
$cueOut = $origLength; $cueOut = $origLength;
} }
if(Playlist::playlistTimeToSeconds($cueOut) < Playlist::playlistTimeToSeconds($oldCueIn)) { if(Playlist::playlistTimeToSeconds($cueOut) < Playlist::playlistTimeToSeconds($oldCueIn)) {
$errArray["error"] ="Can't set cue out to be smaller than cue in."; $errArray["error"] ="Can't set cue out to be smaller than cue in.";
return $errArray; return $errArray;
} }
if(Playlist::playlistTimeToSeconds($cueOut) > Playlist::playlistTimeToSeconds($origLength)){ if(Playlist::playlistTimeToSeconds($cueOut) > Playlist::playlistTimeToSeconds($origLength)){
$errArray["error"] ="Can't set cue out to be greater than file length."; $errArray["error"] ="Can't set cue out to be greater than file length.";
return $errArray; return $errArray;
} }
$row->setDbCueout($cueOut); $row->setDbCueout($cueOut);
$row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($cueOut) $row->setDBCliplength(Playlist::secondsToPlaylistTime(Playlist::playlistTimeToSeconds($cueOut)
- Playlist::playlistTimeToSeconds($oldCueIn))); - Playlist::playlistTimeToSeconds($oldCueIn)));
} }
$cliplength = $row->getDbCliplength(); $cliplength = $row->getDbCliplength();
if(Playlist::playlistTimeToSeconds($fadeIn) > Playlist::playlistTimeToSeconds($cliplength)){ if(Playlist::playlistTimeToSeconds($fadeIn) > Playlist::playlistTimeToSeconds($cliplength)){
$fadeIn = $cliplength; $fadeIn = $cliplength;
$row->setDbFadein($fadeIn); $row->setDbFadein($fadeIn);
} }
if(Playlist::playlistTimeToSeconds($fadeOut) > Playlist::playlistTimeToSeconds($cliplength)){ if(Playlist::playlistTimeToSeconds($fadeOut) > Playlist::playlistTimeToSeconds($cliplength)){
$fadeOut = $cliplength; $fadeOut = $cliplength;
$row->setDbFadein($fadeOut); $row->setDbFadein($fadeOut);
} }
$row->save(); $row->save();
return array("cliplength"=>$cliplength, "cueIn"=>$cueIn, "cueOut"=>$cueOut, "length"=>$this->getLength(), return array("cliplength"=>$cliplength, "cueIn"=>$cueIn, "cueOut"=>$cueOut, "length"=>$this->getLength(),
@ -721,12 +727,12 @@ class Playlist {
public function getPLMetaData($category) public function getPLMetaData($category)
{ {
$cat = $this->categories[$category]; $cat = $this->categories[$category];
if($cat === 'length') { if($cat === 'length') {
return $this->getLength(); return $this->getLength();
} }
$row = CcPlaylistQuery::create()->findPK($this->id); $row = CcPlaylistQuery::create()->findPK($this->id);
$method = 'get' . $cat; $method = 'get' . $cat;
return $row->$method(); return $row->$method();
} }
@ -735,7 +741,7 @@ class Playlist {
{ {
$cat = $this->categories[$category]; $cat = $this->categories[$category];
$row = CcPlaylistQuery::create()->findPK($this->id); $row = CcPlaylistQuery::create()->findPK($this->id);
$method = 'set' . $cat; $method = 'set' . $cat;
$row->$method($value); $row->$method($value);
$row->save(); $row->save();
@ -753,7 +759,7 @@ class Playlist {
*/ */
public function export() public function export()
{ {
} }
@ -809,7 +815,7 @@ class Playlist {
*/ */
public function outputToSmil($toString=TRUE) public function outputToSmil($toString=TRUE)
{ {
} }
@ -824,7 +830,7 @@ class Playlist {
*/ */
public function outputToM3u($toString=TRUE) public function outputToM3u($toString=TRUE)
{ {
} }
@ -839,15 +845,15 @@ class Playlist {
*/ */
public function outputToRss($toString=TRUE) public function outputToRss($toString=TRUE)
{ {
} }
/** /**
* Get audioClip length and title * Get audioClip length and title
* *
* @param int $acId * @param StoredFile $p_media
* local id of audioClip inserted to playlist *
* @return array with fields: * @return array with fields:
* <ul> * <ul>
* <li>acGunid, string - audioClip gunid</li> * <li>acGunid, string - audioClip gunid</li>
@ -856,24 +862,24 @@ class Playlist {
* <li>elType string - audioClip | playlist</li> * <li>elType string - audioClip | playlist</li>
* </ul> * </ul>
*/ */
private function getAudioClipInfo($ac) private function getAudioClipInfo($p_media)
{ {
$ac_id = BasicStor::IdFromGunid($ac->gunid); $ac_id = $p_media->getId();
$r = $ac->md['dcterms:extent']; $r = $p_media->getMetadataValue('dcterms:extent');
if (isset($r)) { if (isset($r)) {
$acLen = $r; $acLen = $r;
} else { } else {
$acLen = '00:00:00.000000'; $acLen = '00:00:00.000000';
} }
$r = $ac->md['dc:title']; $r = $p_media->getMetadataValue('dc:title');
if (isset($r)) { if (isset($r)) {
$acTit = $r; $acTit = $r;
} else { } else {
$acTit = $acGunid; $acTit = $acGunid;
} }
$elType = BasicStor::GetObjType($ac_id); $elType = $p_media->getType();
$trTbl = array('audioclip'=>'audioClip', 'webstream'=>'audioClip','playlist'=>'playlist'); $trTbl = array('audioclip'=>'audioClip', 'webstream'=>'audioClip','playlist'=>'playlist');
$elType = $trTbl[$elType]; $elType = $trTbl[$elType];
@ -921,7 +927,7 @@ class Playlist {
$fadeIn = '00:00:00.000'; $fadeIn = '00:00:00.000';
if(is_null($fadeOut)) if(is_null($fadeOut))
$fadeOut = '00:00:00.000'; $fadeOut = '00:00:00.000';
$row = new CcPlaylistcontents(); $row = new CcPlaylistcontents();
$row->setDbPlaylistId($plId); $row->setDbPlaylistId($plId);
$row->setDbFileId($fileId); $row->setDbFileId($fileId);
@ -1384,21 +1390,21 @@ class PlaylistAudioClipExport
public static function OutputToRss(&$pl, $plac, $ind='') public static function OutputToRss(&$pl, $plac, $ind='')
{ {
$gunid = $plac['attrs']['id']; $id = $plac['attrs']['id'];
$ac = StoredFile::RecallByGunid($gunid); $playlist = Playlist::Recall($id);
if (is_null($ac) || PEAR::isError($ac)) { if (is_null($playlist) || PEAR::isError($playlist)) {
return $ac; return $playlist;
} }
$RADext = $ac->getFileExtension(); $RADext = $playlist->getFileExtension();
if (PEAR::isError($RADext)) { if (PEAR::isError($RADext)) {
return $RADext; return $RADext;
} }
$title = $pl->gb->bsGetMetadataValue($ac->getId(), 'dc:title'); $title = $playlist->getName();
$desc = $pl->gb->bsGetMetadataValue($ac->getId(), 'dc:description'); $desc = $playlist->getPLMetaData("dc:description");
return array( return array(
'type' => 'audioclip', 'type' => 'audioclip',
'gunid' => $gunid, 'gunid' => $id,
'src' => "http://XXX/YY/$gunid.$RADext", 'src' => "http://XXX/YY/$id.$RADext",
'playlength' => $plac['attrs']['playlength'], 'playlength' => $plac['attrs']['playlength'],
'title' => $title, 'title' => $title,
'desc' => $desc, 'desc' => $desc,

View File

@ -205,36 +205,36 @@ class Renderer
*/ */
function rnRender2StorageCore(&$gb, $token) function rnRender2StorageCore(&$gb, $token)
{ {
$r = BasicStor::bsRelease($token, 'render'); // $r = BasicStor::bsRelease($token, 'render');
if (PEAR::isError($r)) { // if (PEAR::isError($r)) {
return $r; // return $r;
} // }
$realOgg = $r['realFname']; // $realOgg = $r['realFname'];
$owner = $r['owner']; // $owner = $r['owner'];
$gunid = $r['gunid']; // $gunid = $r['gunid'];
$fileName = 'rendered_playlist'; // $fileName = 'rendered_playlist';
$id = BasicStor::IdFromGunid($gunid); // $id = BasicStor::IdFromGunid($gunid);
if (PEAR::isError($id)) { // if (PEAR::isError($id)) {
return $id; // return $id;
} // }
$mdata = ''; // $mdata = '';
foreach (array('dc:title', 'dcterms:extent', 'dc:creator', 'dc:description') as $item) { // foreach (array('dc:title', 'dcterms:extent', 'dc:creator', 'dc:description') as $item) {
$val = $gb->bsGetMetadataValue($id, $item); // $val = $gb->bsGetMetadataValue($id, $item);
$mdata .= " <$item>$val</$item>\n"; // $mdata .= " <$item>$val</$item>\n";
} // }
$mdata = "<audioClip>\n <metadata>\n$mdata </metadata>\n</audioClip>\n"; // $mdata = "<audioClip>\n <metadata>\n$mdata </metadata>\n</audioClip>\n";
//$mdata = "<audioClip>\n <metadata>\n$mdata<dcterms:extent>0</dcterms:extent>\n</metadata>\n</audioClip>\n"; // //$mdata = "<audioClip>\n <metadata>\n$mdata<dcterms:extent>0</dcterms:extent>\n</metadata>\n</audioClip>\n";
$values = array( // $values = array(
"filename" => $fileName, // "filename" => $fileName,
"filepath" => $realOgg, // "filepath" => $realOgg,
"metadata" => $mdata, // "metadata" => $mdata,
"filetype" => "audioclip" // "filetype" => "audioclip"
); // );
$storedFile = $gb->bsPutFile($values); // $storedFile = $gb->bsPutFile($values);
if (PEAR::isError($storedFile)) { // if (PEAR::isError($storedFile)) {
return $storedFile; // return $storedFile;
} // }
return array('gunid' => $storedFile->getGunid()); // return array('gunid' => $storedFile->getGunid());
} }

View File

@ -265,83 +265,83 @@ class Restore {
* @return mixed * @return mixed
* true if success or PEAR_error * true if success or PEAR_error
*/ */
function addFileToStorage($file,$type,$gunid) // function addFileToStorage($file,$type,$gunid)
{ // {
if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
$this->addLogItem("-I- ".date("Ymd-H:i:s")." addFileToStorage - file:$file | type:$type | id:$gunid\n"); // $this->addLogItem("-I- ".date("Ymd-H:i:s")." addFileToStorage - file:$file | type:$type | id:$gunid\n");
} // }
require_once("XmlParser.php"); // require_once("XmlParser.php");
$tree = XmlParser::parse($file); // $tree = XmlParser::parse($file);
$mediaFileLP = str_replace('.xml','',$file); // $mediaFileLP = str_replace('.xml','',$file);
$mediaFileLP = ($type=='audioClip' && is_file($mediaFileLP))?$mediaFileLP:''; // $mediaFileLP = ($type=='audioClip' && is_file($mediaFileLP))?$mediaFileLP:'';
$ex = $this->gb->existsFile($this->sessid,$gunid); // $ex = $this->gb->existsFile($this->sessid,$gunid);
if (PEAR::isError($ex)) { // if (PEAR::isError($ex)) {
$this->addLogItem("-E- ".date("Ymd-H:i:s"). // $this->addLogItem("-E- ".date("Ymd-H:i:s").
" addFileToStorage - existsFile($gunid) ". // " addFileToStorage - existsFile($gunid) ".
"(".$ex->getMessage()."/".$ex->getUserInfo().")\n" // "(".$ex->getMessage()."/".$ex->getUserInfo().")\n"
); // );
} // }
if (!PEAR::isError($ex) && $ex) { // file is exists in storage server // if (!PEAR::isError($ex) && $ex) { // file is exists in storage server
//replace it // //replace it
$id = BasicStor::IdFromGunid($gunid); // $id = BasicStor::IdFromGunid($gunid);
$replace = $this->gb->replaceFile( // $replace = $this->gb->replaceFile(
$id, # id int, virt.file's local id // $id, # id int, virt.file's local id
$mediaFileLP, # mediaFileLP string, local path of media file // $mediaFileLP, # mediaFileLP string, local path of media file
$file, # mdataFileLP string, local path of metadata file // $file, # mdataFileLP string, local path of metadata file
$this->sessid); # sessid string, session id // $this->sessid); # sessid string, session id
if (PEAR::isError($replace)) { // if (PEAR::isError($replace)) {
$this->addLogItem("-E- ".date("Ymd-H:i:s"). // $this->addLogItem("-E- ".date("Ymd-H:i:s").
" addFileToStorage - replaceFile Error ". // " addFileToStorage - replaceFile Error ".
"(".$replace->getMessage()."/".$replace->getUserInfo().")\n" // "(".$replace->getMessage()."/".$replace->getUserInfo().")\n"
); // );
file_put_contents($this->statusFile, 'fault|'.$replace->getMessage()."/".$replace->getUserInfo()); // file_put_contents($this->statusFile, 'fault|'.$replace->getMessage()."/".$replace->getUserInfo());
return $replace; // return $replace;
} // }
#$this->addLogItem("replace it \n"); // #$this->addLogItem("replace it \n");
} else { // } else {
// add as new // // add as new
$name = $tree->children[0]->children[0]->content; // $name = $tree->children[0]->children[0]->content;
if (empty($name)) { // if (empty($name)) {
$name = $tree->attrs['title']->val; // $name = $tree->attrs['title']->val;
} // }
if (empty($name)) { // if (empty($name)) {
$name = '???'; // $name = '???';
} // }
if ($this->loglevel=='debug') { // if ($this->loglevel=='debug') {
$this->addLogItem("-I- ".date("Ymd-H:i:s")." putFile\n". // $this->addLogItem("-I- ".date("Ymd-H:i:s")." putFile\n".
"$name, $mediaFileLP, $file, {$this->sessid}, $gunid, $type \n" // "$name, $mediaFileLP, $file, {$this->sessid}, $gunid, $type \n"
); // );
} // }
$values = array( // $values = array(
"filename" => $name, // "filename" => $name,
"filepath" => $mediaFileLP, // "filepath" => $mediaFileLP,
"metadata" => $file, // "metadata" => $file,
"gunid" => $gunid, // "gunid" => $gunid,
"filetype" => $type // "filetype" => $type
); // );
$put = $this->gb->putFile($values, $this->sessid); // $put = $this->gb->putFile($values, $this->sessid);
//$this->addLogItem("add as new \n"); // //$this->addLogItem("add as new \n");
if (PEAR::isError($put)) { // if (PEAR::isError($put)) {
$this->addLogItem("-E- ".date("Ymd-H:i:s"). // $this->addLogItem("-E- ".date("Ymd-H:i:s").
" addFileToStorage - putFile Error ". // " addFileToStorage - putFile Error ".
"(".$put->getMessage()."/".$put->getUserInfo().")\n" // "(".$put->getMessage()."/".$put->getUserInfo().")\n"
."\n---\n".file_get_contents($file)."\n---\n" // ."\n---\n".file_get_contents($file)."\n---\n"
); // );
file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo()); // file_put_contents($this->statusFile, 'fault|'.$put->getMessage()."/".$put->getUserInfo());
//$this->addLogItem("Error Object: ".print_r($put,true)."\n"); // //$this->addLogItem("Error Object: ".print_r($put,true)."\n");
return $put; // return $put;
} // }
} // }
$ac = StoredFile::RecallByGunid($gunid); // $ac = StoredFile::RecallByGunid($gunid);
if (is_null($ac) || PEAR::isError($ac)) { // if (is_null($ac) || PEAR::isError($ac)) {
return $ac; // return $ac;
} // }
$res = $ac->setState('ready'); // $res = $ac->setState('ready');
if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
return $res; // return $res;
} // }
return true; // return true;
} // }
/** /**

View File

@ -170,7 +170,7 @@ class ScheduleGroup {
} }
$sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"] $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]
." WHERE group_id = ".$this->groupId; ." WHERE group_id = ".$this->groupId;
return $CC_DBC->query($sql); return $CC_DBC->query($sql);
} }
@ -230,13 +230,32 @@ class Schedule {
return ($count == '0'); return ($count == '0');
} }
public function onAddTrackToPlaylist($playlistId, $audioTrackId) { // public function onAddTrackToPlaylist($playlistId, $audioTrackId) {
//
// }
//
// public function onRemoveTrackFromPlaylist($playlistId, $audioTrackId) {
//
// }
/**
* Return TRUE if file is going to be played in the future.
*
* @param string $p_fileId
*/
public function IsFileScheduledInTheFuture($p_fileId)
{
global $CC_CONFIG, $CC_DBC;
$sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"]
." WHERE file_id = {$p_fileId} AND starts > NOW()";
$count = $CC_DBC->GetOne($sql);
if (is_numeric($count) && ($count != '0')) {
return TRUE;
} else {
return FALSE;
}
} }
public function onRemoveTrackFromPlaylist($playlistId, $audioTrackId) {
}
/** /**
* Returns array indexed numberically of: * Returns array indexed numberically of:
@ -326,7 +345,7 @@ class Schedule {
$t = explode("-", $p_time); $t = explode("-", $p_time);
return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00"; return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00";
} }
/** /**
* Export the schedule in json formatted for pypo (the liquidsoap scheduler) * Export the schedule in json formatted for pypo (the liquidsoap scheduler)
* *
@ -337,29 +356,29 @@ class Schedule {
*/ */
public static function ExportRangeAsJson($p_fromDateTime, $p_toDateTime) public static function ExportRangeAsJson($p_fromDateTime, $p_toDateTime)
{ {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$range_start = Schedule::PypoTimeToCcTime($p_fromDateTime); $range_start = Schedule::PypoTimeToCcTime($p_fromDateTime);
$range_end = Schedule::PypoTimeToCcTime($p_toDateTime); $range_end = Schedule::PypoTimeToCcTime($p_toDateTime);
$range_dt = array('start' => $range_start, 'end' => $range_end); $range_dt = array('start' => $range_start, 'end' => $range_end);
//var_dump($range_dt); //var_dump($range_dt);
// Scheduler wants everything in a playlist // Scheduler wants everything in a playlist
$data = Schedule::GetItems($range_start, $range_end, true); $data = Schedule::GetItems($range_start, $range_end, true);
//echo "<pre>";var_dump($data); //echo "<pre>";var_dump($data);
$playlists = array(); $playlists = array();
if (is_array($data) && count($data) > 0) if (is_array($data) && count($data) > 0)
{ {
foreach ($data as $dx) foreach ($data as $dx)
{ {
// Is this the first item in the playlist? // Is this the first item in the playlist?
$start = $dx['start']; $start = $dx['start'];
// chop off subseconds // chop off subseconds
$start = substr($start, 0, 19); $start = substr($start, 0, 19);
// Start time is the array key, needs to be in the format "YYYY-MM-DD-HH-mm-ss" // Start time is the array key, needs to be in the format "YYYY-MM-DD-HH-mm-ss"
$pkey = Schedule::CcTimeToPypoTime($start); $pkey = Schedule::CcTimeToPypoTime($start);
$timestamp = strtotime($start); $timestamp = strtotime($start);
$playlists[$pkey]['source'] = "PLAYLIST"; $playlists[$pkey]['source'] = "PLAYLIST";
$playlists[$pkey]['x_ident'] = $dx["playlist_id"]; $playlists[$pkey]['x_ident'] = $dx["playlist_id"];
$playlists[$pkey]['subtype'] = '1'; // Just needs to be between 1 and 4 inclusive $playlists[$pkey]['subtype'] = '1'; // Just needs to be between 1 and 4 inclusive
@ -372,16 +391,16 @@ class Schedule {
foreach ($playlists as &$playlist) foreach ($playlists as &$playlist)
{ {
$scheduleGroup = new ScheduleGroup($playlist["schedule_id"]); $scheduleGroup = new ScheduleGroup($playlist["schedule_id"]);
$items = $scheduleGroup->getItems(); $items = $scheduleGroup->getItems();
$medias = array(); $medias = array();
$playlist['subtype'] = '1'; $playlist['subtype'] = '1';
foreach ($items as $item) foreach ($items as $item)
{ {
$storedFile = StoredFile::Recall($item["file_id"]); $storedFile = StoredFile::Recall($item["file_id"]);
$uri = $storedFile->getFileUrl(); $uri = $storedFile->getFileUrl();
$medias[] = array( $medias[] = array(
'id' => $item["file_id"], 'id' => $storedFile->getGunid(), //$item["file_id"],
'uri' => $uri, 'uri' => $uri,
'fade_in' => $item["fade_in"], 'fade_in' => $item["fade_in"],
'fade_out' => $item["fade_out"], 'fade_out' => $item["fade_out"],

View File

@ -2,6 +2,53 @@
require_once("Playlist.php"); require_once("Playlist.php");
require_once(dirname(__FILE__)."/../3rd_party/getid3/var/getid3.php"); require_once(dirname(__FILE__)."/../3rd_party/getid3/var/getid3.php");
require_once("BasicStor.php"); require_once("BasicStor.php");
require_once("Schedule.php");
$g_metadata_xml_to_db_mapping = array(
"dc:format" => "format",
"ls:bitrate" => "bit_rate",
"ls:samplerate" => "sample_rate",
"dcterms:extent" => "length",
"dc:title" => "track_title",
"dc:description" => "comments",
"dc:type" => "genre",
"dc:creator" => "artist_name",
"dc:source" => "album_title",
"ls:channels" => "channels",
"ls:filename" => "name",
"ls:year" => "year",
"ls:url" => "url",
"ls:track_num" => "track_number",
"ls:mood" => "mood",
"ls:bpm" => "bpm",
"ls:disc_num" => "disc_number",
"ls:rating" => "rating",
"ls:encoded_by" => "encoded_by",
"dc:publisher" => "label",
"ls:composer" => "composer",
"ls:encoder" => "encoder",
"ls:crc" => "checksum",
"ls:lyrics" => "lyrics",
"ls:orchestra" => "orchestra",
"ls:conductor" => "conductor",
"ls:lyricist" => "lyricist",
"ls:originallyricist" => "original_lyricist",
"ls:radiostationname" => "radio_station_name",
"ls:audiofileinfourl" => "info_url",
"ls:artisturl" => "artist_url",
"ls:audiosourceurl" => "audio_source_url",
"ls:radiostationurl" => "radio_station_url",
"ls:buycdurl" => "buy_this_url",
"ls:isrcnumber" => "isrc_number",
"ls:catalognumber" => "catalog_number",
"ls:originalartist" => "original_artist",
"dc:rights" => "copyright",
"dcterms:temporal" => "report_datetime",
"dcterms:spatial" => "report_location",
"dcterms:entity" => "report_organization",
"dc:subject" => "subject",
"dc:contributor" => "contributor",
"dc:language" => "language");
/** /**
* Track numbers in metadata tags can come in many formats: * Track numbers in metadata tags can come in many formats:
@ -279,7 +326,7 @@ function camp_get_audio_metadata($p_filename, $p_testonly = false)
*/ */
class StoredFile { class StoredFile {
// *** Variable stored in the database *** // *** Variables stored in the database ***
/** /**
* @var int * @var int
@ -314,7 +361,7 @@ class StoredFile {
private $mime; private $mime;
/** /**
* Can be 'playlist' or 'audioclip'. * Can be 'audioclip'...others might be coming, like webstream.
* *
* @var string * @var string
*/ */
@ -381,18 +428,49 @@ class StoredFile {
*/ */
public function __construct($p_gunid=NULL) public function __construct($p_gunid=NULL)
{ {
global $CC_CONFIG;
global $CC_DBC;
$this->gunid = $p_gunid; $this->gunid = $p_gunid;
if (empty($this->gunid)) { if (empty($this->gunid)) {
$this->gunid = StoredFile::generateGunid(); $this->gunid = StoredFile::generateGunid();
} }
//$this->resDir = $this->_getResDir($this->gunid);
//$this->filepath = "{$this->resDir}/{$this->gunid}";
$this->exists = is_file($this->filepath) && is_readable($this->filepath); $this->exists = is_file($this->filepath) && is_readable($this->filepath);
$this->md = $this->loadMetadata(); $this->md = $this->loadMetadata();
} }
/**
* Convert XML name to database column name. Used for backwards compatibility
* with old code.
*
* @param string $p_category
* @return string|null
*/
public static function xmlCategoryToDbColumn($p_category)
{
global $g_metadata_xml_to_db_mapping;
if (array_key_exists($p_category, $g_metadata_xml_to_db_mapping)) {
return $g_metadata_xml_to_db_mapping[$p_category];
}
return null;
}
/**
* Convert database column name to XML name.
*
* @param string $p_dbColumn
* @return string|null
*/
public static function dbColumnToXmlCatagory($p_dbColumn)
{
global $g_metadata_xml_to_db_mapping;
$str = array_search($p_dbColumn, $g_metadata_xml_to_db_mapping);
// make return value consistent with xmlCategoryToDbColumn()
if ($str === FALSE) {
$str = null;
}
return $str;
}
/** /**
* GUNID needs to be set before you call this function. * GUNID needs to be set before you call this function.
* *
@ -417,7 +495,7 @@ class StoredFile {
} }
$compatibilityData = array(); $compatibilityData = array();
foreach ($this->md as $key => $value) { foreach ($this->md as $key => $value) {
if ($xmlName = BasicStor::dbColumnToXmlCatagory($key)) { if ($xmlName = StoredFile::dbColumnToXmlCatagory($key)) {
$compatibilityData[$xmlName] = $value; $compatibilityData[$xmlName] = $value;
} }
} }
@ -435,7 +513,7 @@ class StoredFile {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
foreach ($p_values as $category => $value) { foreach ($p_values as $category => $value) {
$escapedValue = pg_escape_string($value); $escapedValue = pg_escape_string($value);
$columnName = BasicStor::xmlCategoryToDbColumn($category); $columnName = StoredFile::xmlCategoryToDbColumn($category);
if (!is_null($columnName)) { if (!is_null($columnName)) {
$sql = "UPDATE ".$CC_CONFIG["filesTable"] $sql = "UPDATE ".$CC_CONFIG["filesTable"]
." SET $columnName='$escapedValue'" ." SET $columnName='$escapedValue'"
@ -529,7 +607,6 @@ class StoredFile {
// Insert record into the database // Insert record into the database
$escapedName = pg_escape_string($storedFile->name); $escapedName = pg_escape_string($storedFile->name);
$escapedFtype = pg_escape_string($storedFile->ftype); $escapedFtype = pg_escape_string($storedFile->ftype);
$CC_DBC->query("BEGIN");
$sql = "INSERT INTO ".$CC_CONFIG['filesTable'] $sql = "INSERT INTO ".$CC_CONFIG['filesTable']
."(id, name, gunid, mime, state, ftype, mtime, md5)" ."(id, name, gunid, mime, state, ftype, mtime, md5)"
."VALUES ({$sqlId}, '{$escapedName}', " ."VALUES ({$sqlId}, '{$escapedName}', "
@ -537,6 +614,7 @@ class StoredFile {
." '{$storedFile->mime}', 'incomplete', '$escapedFtype'," ." '{$storedFile->mime}', 'incomplete', '$escapedFtype',"
." now(), '{$storedFile->md5}')"; ." now(), '{$storedFile->md5}')";
//$_SESSION["debug"] .= "sql: ".$sql."<br>"; //$_SESSION["debug"] .= "sql: ".$sql."<br>";
//echo $sql."\n";
$res = $CC_DBC->query($sql); $res = $CC_DBC->query($sql);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK"); $CC_DBC->query("ROLLBACK");
@ -548,16 +626,15 @@ class StoredFile {
$sql = "SELECT currval('".$CC_CONFIG["filesSequence"]."_seq')"; $sql = "SELECT currval('".$CC_CONFIG["filesSequence"]."_seq')";
$storedFile->id = $CC_DBC->getOne($sql); $storedFile->id = $CC_DBC->getOne($sql);
} }
BasicStor::bsSetMetadataBatch($storedFile->id, $metadata); $storedFile->setMetadataBatch($metadata);
// Save media file // Save media file
$res = $storedFile->addFile($p_values['filepath'], $p_copyMedia); $res = $storedFile->addFile($p_values['filepath'], $p_copyMedia);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
echo "StoredFile::Insert: ERROR adding file: '".$res->getMessage()."'\n"; echo "StoredFile::Insert -- addFile(): '".$res->getMessage()."'\n";
$CC_DBC->query("ROLLBACK");
return $res; return $res;
} }
if (empty($storedFile->mime)) { if (empty($storedFile->mime)) {
//echo "StoredFile::Insert: WARNING: Having to recalculate MIME value\n"; //echo "StoredFile::Insert: WARNING: Having to recalculate MIME value\n";
$storedFile->setMime($storedFile->getMime()); $storedFile->setMime($storedFile->getMime());
@ -566,13 +643,6 @@ class StoredFile {
// Save state // Save state
$storedFile->setState('ready'); $storedFile->setState('ready');
// Commit changes
$res = $CC_DBC->query("COMMIT");
if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK");
return $res;
}
// Recall the object to get all the proper values // Recall the object to get all the proper values
$storedFile = StoredFile::RecallByGunid($storedFile->gunid); $storedFile = StoredFile::RecallByGunid($storedFile->gunid);
return $storedFile; return $storedFile;
@ -583,21 +653,21 @@ class StoredFile {
* Should be supplied with only ONE parameter, all the rest should * Should be supplied with only ONE parameter, all the rest should
* be NULL. * be NULL.
* *
* @param int $p_oid * @param int $p_id
* local object id in the tree * local id
* @param string $p_gunid * @param string $p_gunid
* global unique id of file * global unique id of file
* @param string $p_md5sum * @param string $p_md5sum
* MD5 sum of the file * MD5 sum of the file
* @return StoredFile|Playlist|NULL * @return StoredFile|Playlist|NULL
* Return NULL if the object doesnt exist in the DB. * Return NULL if the object doesnt exist in the DB.
*/ */
public static function Recall($p_oid=null, $p_gunid=null, $p_md5sum=null) public static function Recall($p_id=null, $p_gunid=null, $p_md5sum=null)
{ {
global $CC_DBC; global $CC_DBC;
global $CC_CONFIG; global $CC_CONFIG;
if (!is_null($p_oid)) { if (!is_null($p_id)) {
$cond = "id='".intval($p_oid)."'"; $cond = "id='".intval($p_id)."'";
} elseif (!is_null($p_gunid)) { } elseif (!is_null($p_gunid)) {
$cond = "gunid='$p_gunid'"; $cond = "gunid='$p_gunid'";
} elseif (!is_null($p_md5sum)) { } elseif (!is_null($p_md5sum)) {
@ -605,31 +675,16 @@ class StoredFile {
} else { } else {
return null; return null;
} }
$sql = "SELECT id, gunid," $sql = "SELECT *"
." name, mime, ftype, state, currentlyaccessing, editedby, "
." mtime, md5"
." FROM ".$CC_CONFIG['filesTable'] ." FROM ".$CC_CONFIG['filesTable']
." WHERE $cond"; ." WHERE $cond";
//echo $sql; //echo $sql;
$row = $CC_DBC->getRow($sql); $row = $CC_DBC->getRow($sql);
if (PEAR::isError($row)) { if (PEAR::isError($row) || is_null($row)) {
return $row; return $row;
} }
if (is_null($row)) {
return null;
}
$gunid = $row['gunid']; $gunid = $row['gunid'];
if ($row['ftype'] == 'audioclip') { $storedFile = new StoredFile($gunid);
$storedFile = new StoredFile($gunid);
} elseif ($row['ftype'] == 'playlist') {
$storedFile = new Playlist($gunid);
} else { // fallback
$storedFile = new StoredFile($gunid);
}
$storedFile->loadMetadata();
//$storedFile->gunidBigint = $row['gunid_bigint'];
//$storedFile->md->gunidBigint = $row['gunid_bigint'];
$storedFile->md["gunid"] = $row['gunid'];
$storedFile->id = $row['id']; $storedFile->id = $row['id'];
$storedFile->name = $row['name']; $storedFile->name = $row['name'];
$storedFile->mime = $row['mime']; $storedFile->mime = $row['mime'];
@ -639,6 +694,7 @@ class StoredFile {
$storedFile->editedby = $row['editedby']; $storedFile->editedby = $row['editedby'];
$storedFile->mtime = $row['mtime']; $storedFile->mtime = $row['mtime'];
$storedFile->md5 = $row['md5']; $storedFile->md5 = $row['md5'];
$storedFile->filepath = $row['filepath'];
$storedFile->exists = TRUE; $storedFile->exists = TRUE;
$storedFile->setFormat($row['ftype']); $storedFile->setFormat($row['ftype']);
return $storedFile; return $storedFile;
@ -757,6 +813,7 @@ class StoredFile {
$sql = "UPDATE ".$CC_CONFIG["filesTable"] $sql = "UPDATE ".$CC_CONFIG["filesTable"]
." SET filepath='{$sqlPath}'" ." SET filepath='{$sqlPath}'"
." WHERE id={$this->id}"; ." WHERE id={$this->id}";
//echo $sql."\n";
$res = $CC_DBC->query($sql); $res = $CC_DBC->query($sql);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
@ -803,25 +860,52 @@ class StoredFile {
/** /**
* Delete media file from filesystem * Delete media file from filesystem.
* You cant delete a file if it is being accessed.
* You cant delete a file if it is scheduled to be played in the future.
* The file will be removed from all playlists it is a part of.
* *
* @return boolean|PEAR_Error * @return boolean|PEAR_Error
*/ */
public function deleteFile() public function deleteFile()
{ {
global $CC_CONFIG;
if (!$this->exists) { if (!$this->exists) {
return FALSE; return FALSE;
} }
if (!file_exists($this->filepath) || @unlink($this->filepath)) { if ($this->isAccessed()) {
$this->exists = FALSE; return PEAR::raiseError(
return TRUE; 'Cannot delete a file that is currently accessed.'
} else {
return PEAR::raiseError(
"StoredFile::deleteFile: unlink failed ({$this->filepath})",
GBERR_FILEIO
); );
} }
return $this->exists;
// Check if the file is scheduled to be played in the future
if (Schedule::IsFileScheduledInTheFuture($this->id)) {
return PEAR::raiseError(
'Cannot delete a file that is scheduled in the future.'
);
}
// Delete it from all playlists
//Playlist::DeleteFileFromAllPlaylists($this->id);
// Only delete the file from filesystem if it has been copied to the
// storage directory. (i.e. dont delete linked files)
if (substr($this->filepath, 0, strlen($CC_CONFIG["storageDir"])) == $CC_CONFIG["storageDir"]) {
// Delete the file
if (!file_exists($this->filepath) || @unlink($this->filepath)) {
$this->exists = FALSE;
return TRUE;
} else {
return PEAR::raiseError(
"StoredFile::deleteFile: unlink failed ({$this->filepath})",
GBERR_FILEIO
);
}
} else {
$this->exists = FALSE;
return TRUE;
}
} }
@ -858,7 +942,7 @@ class StoredFile {
"id" => $p_nid, "id" => $p_nid,
"filename" => $p_src->name, "filename" => $p_src->name,
"filepath" => $p_src->getRealFileName(), "filepath" => $p_src->getRealFileName(),
"filetype" => BasicStor::GetType($p_src->gunid) "filetype" => $p_src->getType()
); );
$storedFile = StoredFile::Insert($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
@ -884,42 +968,42 @@ class StoredFile {
* 'file'|'string' * 'file'|'string'
* @return TRUE|PEAR_Error * @return TRUE|PEAR_Error
*/ */
public function replace($p_oid, $p_name, $p_localFilePath='', $p_metadata='', // public function replace($p_oid, $p_name, $p_localFilePath='', $p_metadata='',
$p_mdataLoc='file') // $p_mdataLoc='file')
{ // {
global $CC_CONFIG, $CC_DBC; // global $CC_CONFIG, $CC_DBC;
$CC_DBC->query("BEGIN"); // $CC_DBC->query("BEGIN");
$res = $this->setName($p_name); // $res = $this->setName($p_name);
if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK"); // $CC_DBC->query("ROLLBACK");
return $res; // return $res;
} // }
if ($p_localFilePath != '') { // if ($p_localFilePath != '') {
$res = $this->setRawMediaData($p_localFilePath); // $res = $this->setRawMediaData($p_localFilePath);
} else { // } else {
$res = $this->deleteFile(); // $res = $this->deleteFile();
} // }
if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK"); // $CC_DBC->query("ROLLBACK");
return $res; // return $res;
} // }
if ($p_metadata != '') { // if ($p_metadata != '') {
$res = $this->setMetadata($p_metadata, $p_mdataLoc); // $res = $this->setMetadata($p_metadata, $p_mdataLoc);
} else { // } else {
// $res = $this->md->delete(); //// $res = $this->md->delete();
$res = $this->clearMetadata(); // $res = $this->clearMetadata();
} // }
if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK"); // $CC_DBC->query("ROLLBACK");
return $res; // return $res;
} // }
$res = $CC_DBC->query("COMMIT"); // $res = $CC_DBC->query("COMMIT");
if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK"); // $CC_DBC->query("ROLLBACK");
return $res; // return $res;
} // }
return TRUE; // return TRUE;
} // }
/** /**
@ -989,6 +1073,17 @@ class StoredFile {
} }
private static function NormalizeExtent($v)
{
if (!preg_match("|^\d{2}:\d{2}:\d{2}.\d{6}$|", $v)) {
$s = Playlist::playlistTimeToSeconds($v);
$t = Playlist::secondsToPlaylistTime($s);
return $t;
}
return $v;
}
/** /**
* Replace metadata with new XML file * Replace metadata with new XML file
* *
@ -1002,25 +1097,110 @@ class StoredFile {
* (NULL = no validation) * (NULL = no validation)
* @return boolean * @return boolean
*/ */
public function setMetadata($p_metadata, $p_mdataLoc='file', $p_format=NULL) // public function setMetadata($p_metadata, $p_mdataLoc='file', $p_format=NULL)
{ // {
global $CC_CONFIG, $CC_DBC; // global $CC_CONFIG, $CC_DBC;
$CC_DBC->query("BEGIN"); // $CC_DBC->query("BEGIN");
$res = $this->md->replace($p_metadata, $p_mdataLoc, $p_format); // $res = $this->md->replace($p_metadata, $p_mdataLoc, $p_format);
if (PEAR::isError($res)) { // if (PEAR::isError($res)) {
$CC_DBC->query("ROLLBACK");
return $res;
}
// $r = $this->md->regenerateXmlFile();
// if (PEAR::isError($r)) {
// $CC_DBC->query("ROLLBACK"); // $CC_DBC->query("ROLLBACK");
// return $r; // return $res;
// } // }
$res = $CC_DBC->query("COMMIT"); // $res = $CC_DBC->query("COMMIT");
// if (PEAR::isError($res)) {
// return $res;
// }
// return TRUE;
// }
/**
* Set metadata element value
*
* @param string $category
* Metadata element identification (e.g. dc:title)
* @param string $value
* value to store, if NULL then delete record
* @return boolean
*/
public function setMetadataValue($p_category, $p_value)
{
global $CC_CONFIG, $CC_DBC;
if (!is_string($p_category) || is_array($p_value)) {
return FALSE;
}
if ($p_category == 'dcterms:extent') {
$p_value = StoredFile::NormalizeExtent($p_value);
}
$columnName = StoredFile::xmlCategoryToDbColumn($p_category); // Get column name
if (!is_null($columnName)) {
$escapedValue = pg_escape_string($p_value);
$sql = "UPDATE ".$CC_CONFIG["filesTable"]
." SET $columnName='$escapedValue'"
." WHERE id=$p_id";
//var_dump($sql);
$res = $CC_DBC->query($sql);
if (PEAR::isError($res)) { if (PEAR::isError($res)) {
return $res; return $res;
} }
}
return TRUE;
}
/**
* Set metadata values in 'batch' mode
*
* @param array $values
* array of key/value pairs
* (e.g. 'dc:title'=>'New title')
* @return boolean
*/
public function setMetadataBatch($values)
{
global $CC_CONFIG, $CC_DBC;
if (!is_array($values)) {
$values = array($values);
}
if (count($values) == 0) {
return true;
}
foreach ($values as $category => $oneValue) {
$columnName = StoredFile::xmlCategoryToDbColumn($category);
if (!is_null($columnName)) {
if ($category == 'dcterms:extent') {
$oneValue = StoredFile::NormalizeExtent($oneValue);
}
// Since track_number is an integer, you cannot set
// it to be the empty string, so we NULL it instead.
if ($columnName == 'track_number' && empty($oneValue)) {
$sqlPart = "$columnName = NULL";
} elseif (($columnName == 'length') && (strlen($oneValue) > 8)) {
// Postgres doesnt like it if you try to store really large hour
// values. TODO: We need to fix the underlying problem of getting the
// right values.
$parts = explode(':', $oneValue);
$hour = intval($parts[0]);
if ($hour > 24) {
continue;
} else {
$sqlPart = "$columnName = '$oneValue'";
}
} else {
$escapedValue = pg_escape_string($oneValue);
$sqlPart = "$columnName = '$escapedValue'";
}
$sqlValues[] = $sqlPart;
}
}
if (count($sqlValues)==0) {
return TRUE; return TRUE;
}
$sql = "UPDATE ".$CC_CONFIG["filesTable"]
." SET ".join(",", $sqlValues)
." WHERE id=$id";
$CC_DBC->query($sql);
return TRUE;
} }
@ -1034,6 +1214,20 @@ class StoredFile {
return $this->md; return $this->md;
} }
/**
* Get one metadata value.
*
* @param string $p_name
* @return string
*/
public function getMetadataValue($p_name)
{
if (isset($this->md[$p_name])){
return $this->md[$p_name];
} else {
return "";
}
}
/** /**
* Rename stored virtual file * Rename stored virtual file
@ -1135,7 +1329,7 @@ class StoredFile {
* Delete stored virtual file * Delete stored virtual file
* *
* @param boolean $p_deleteFile * @param boolean $p_deleteFile
* @see MetaData *
* @return TRUE|PEAR_Error * @return TRUE|PEAR_Error
*/ */
public function delete($p_deleteFile = true) public function delete($p_deleteFile = true)
@ -1147,10 +1341,6 @@ class StoredFile {
return $res; return $res;
} }
} }
// $res = $this->md->delete();
// if (PEAR::isError($res)) {
// return $res;
// }
$sql = "SELECT to_hex(token)as token, ext " $sql = "SELECT to_hex(token)as token, ext "
." FROM ".$CC_CONFIG['accessTable'] ." FROM ".$CC_CONFIG['accessTable']
." WHERE gunid='{$this->gunid}'"; ." WHERE gunid='{$this->gunid}'";
@ -1178,27 +1368,25 @@ class StoredFile {
return TRUE; return TRUE;
} }
/**
* Returns gunIds of the playlists the stored file is in.
* TODO update this to work with new tables.
*/
/* /**
* Returns an array of playlist objects that this file is a part of.
* @return array
*/
public function getPlaylists() { public function getPlaylists() {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$sql = "SELECT playlist_id "
$_SESSION['delete'] = "gunid: " . $this->gunid; ." FROM ".$CC_CONFIG['playistTable']
." WHERE file_id='{$this->id}'";
$sql = "SELECT gunid " $ids = $CC_DBC->getAll($sql);
." FROM ".$CC_CONFIG['mdataTable'] $playlists = array();
." WHERE object='{$this->gunid}'"; if (is_array($ids) && count($ids) > 0) {
foreach ($ids as $id) {
$_SESSION['delete'] = $sql; $playlists[] = Playlist::Recall($id);
$playlists = $CC_DBC->getAll($sql); }
}
return $playlists; return $playlists;
} }
*/
/** /**
@ -1314,7 +1502,7 @@ class StoredFile {
if (is_null($indb)) { if (is_null($indb)) {
return FALSE; return FALSE;
} }
if (BasicStor::GetType($this->gunid) == 'audioclip') { if ($this->ftype == 'audioclip') {
return $this->existsFile(); return $this->existsFile();
} }
return TRUE; return TRUE;
@ -1394,7 +1582,7 @@ class StoredFile {
* *
* @return string * @return string
*/ */
function getMime() public function getMime()
{ {
$a = $this->analyzeFile(); $a = $this->analyzeFile();
if (PEAR::isError($a)) { if (PEAR::isError($a)) {
@ -1407,6 +1595,20 @@ class StoredFile {
} }
/**
* Convenience function.
* @return string
*/
public function getTitle()
{
return $this->md["title"];
}
public function getType()
{
return $this->ftype;
}
/** /**
* Get storage-internal file state * Get storage-internal file state
* *
@ -1482,8 +1684,8 @@ class StoredFile {
public function getFileUrl() public function getFileUrl()
{ {
global $CC_CONFIG; global $CC_CONFIG;
return "http://".$CC_CONFIG["storageUrlHost"].$CC_CONFIG["storageUrlPath"] return "http://".$CC_CONFIG["storageUrlHost"]
."/stor/".substr($this->gunid, 0, 3)."/{$this->gunid}"; ."api/get_media.php?file_id={$this->gunid}";
} }
/** /**

View File

@ -1417,7 +1417,7 @@ class Transport
"gunid" => $row['gunid'], "gunid" => $row['gunid'],
"filetype" => "audioclip" "filetype" => "audioclip"
); );
$storedFile = $this->gb->bsPutFile($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
$mdtrec->setLock(FALSE); $mdtrec->setLock(FALSE);
return $storedFile; return $storedFile;
@ -1473,7 +1473,7 @@ class Transport
"gunid" => $row['gunid'], "gunid" => $row['gunid'],
"filetype" => "playlist" "filetype" => "playlist"
); );
$storedFile = $this->gb->bsPutFile($values); $storedFile = StoredFile::Insert($values);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
return $storedFile; return $storedFile;
} }

View File

@ -1,23 +1,25 @@
<?php <?php
$path = dirname(__FILE__).'/../../3rd_party/php/pear'; $path = dirname(__FILE__).'/../../3rd_party/php/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path); set_include_path(get_include_path() . PATH_SEPARATOR . $path);
$WHITE_SCREEN_OF_DEATH = true;
require_once(dirname(__FILE__).'/../../conf.php'); require_once(dirname(__FILE__).'/../../conf.php');
require_once('DB.php'); require_once('DB.php');
require_once('PHPUnit.php'); require_once('PHPUnit.php');
//require_once 'BasicStorTests.php'; require_once 'StoredFileTests.php';
//require_once 'SchedulerTests.php'; //require_once 'SchedulerTests.php';
//require_once 'SchedulerExportTests.php'; //require_once 'SchedulerExportTests.php';
require_once 'PlayListTests.php'; require_once 'PlaylistTests.php';
$suite = new PHPUnit_TestSuite("PlayListTests"); //$suite = new PHPUnit_TestSuite("PlayListTests");
//$suite = new PHPUnit_TestSuite("BasicStorTest"); $suite = new PHPUnit_TestSuite("StoredFileTest");
//$suite = new PHPUnit_TestSuite("SchedulerTests"); //$suite = new PHPUnit_TestSuite("SchedulerTests");
//$suite->addTestSuite("BasicStorTest");
//$suite->addTestSuite("SchedulerTests"); //$suite->addTestSuite("SchedulerTests");
//$suite->addTestSuite("SchedulerExportTests"); //$suite->addTestSuite("SchedulerExportTests");
//$suite->addTestSuite("PlayListTests"); $suite->addTestSuite("PlaylistTests");
$result = PHPUnit::run($suite); $result = PHPUnit::run($suite);
echo $result->toString(); echo $result->toString();
?> ?>

View File

@ -10,7 +10,6 @@ Propel::init(dirname(__FILE__)."/../../backend/propel-db/build/conf/campcaster-c
// Add the generated 'classes' directory to the include path // Add the generated 'classes' directory to the include path
set_include_path(dirname(__FILE__)."/../../backend/propel-db/build/classes" . PATH_SEPARATOR . get_include_path()); set_include_path(dirname(__FILE__)."/../../backend/propel-db/build/classes" . PATH_SEPARATOR . get_include_path());
//require_once(dirname(__FILE__).'/../../conf.php');
require_once('DB.php'); require_once('DB.php');
require_once('PHPUnit.php'); require_once('PHPUnit.php');
@ -30,7 +29,7 @@ if (PEAR::isError($CC_DBC)) {
} }
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
class PlayListTests extends PHPUnit_TestCase { class PlaylistTests extends PHPUnit_TestCase {
private $greenbox; private $greenbox;
@ -41,11 +40,11 @@ class PlayListTests extends PHPUnit_TestCase {
function setup() { function setup() {
global $CC_CONFIG, $CC_DBC; global $CC_CONFIG, $CC_DBC;
$this->greenbox = new GreenBox(); $this->greenbox = new GreenBox();
} }
function testGBCreatePlaylist() { function testGBCreatePlaylist() {
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("create"); $pl_id = $pl->create("create");
@ -54,32 +53,32 @@ class PlayListTests extends PHPUnit_TestCase {
return; return;
} }
} }
function testGBLock() { function testGBLock() {
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("lock test"); $pl_id = $pl->create("lock test");
$sessid = Alib::Login('root', 'q'); $sessid = Alib::Login('root', 'q');
$res = $this->greenbox->lockPlaylistForEdit($pl_id, $sessid); $res = $this->greenbox->lockPlaylistForEdit($pl_id, $sessid);
if($res !== TRUE) { if($res !== TRUE) {
$this->fail("problems locking playlist for editing."); $this->fail("problems locking playlist for editing.");
return; return;
} }
} }
function testGBUnLock() { function testGBUnLock() {
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("unlock test"); $pl_id = $pl->create("unlock test");
$sessid = Alib::Login('root', 'q'); $sessid = Alib::Login('root', 'q');
$this->greenbox->lockPlaylistForEdit($pl_id, $sessid); $this->greenbox->lockPlaylistForEdit($pl_id, $sessid);
$res = $this->greenbox->releaseLockedPlaylist($pl_id, $sessid); $res = $this->greenbox->releaseLockedPlaylist($pl_id, $sessid);
if($res !== TRUE) { if($res !== TRUE) {
$this->fail("problems unlocking playlist."); $this->fail("problems unlocking playlist.");
return; return;
} }
} }
@ -87,66 +86,77 @@ class PlayListTests extends PHPUnit_TestCase {
function testGBSetPLMetaData() { function testGBSetPLMetaData() {
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("set meta data test"); $pl_id = $pl->create("set meta data test");
$res = $this->greenbox->setPLMetadataValue($pl_id, "dc:title", "A Title"); $res = $this->greenbox->setPLMetadataValue($pl_id, "dc:title", "A Title");
if($res !== TRUE) { if($res !== TRUE) {
$this->fail("problems setting playlist metadata."); $this->fail("problems setting playlist metadata.");
return; return;
} }
} }
function testGBGetPLMetaData() { function testGBGetPLMetaData() {
$pl = new Playlist(); $pl = new Playlist();
$name = "Testing"; $name = "Testing";
$pl_id = $pl->create($name); $pl_id = $pl->create($name);
$res = $this->greenbox->getPLMetadataValue($pl_id, "dc:title"); $res = $this->greenbox->getPLMetadataValue($pl_id, "dc:title");
if($res !== $name) { if($res !== $name) {
$this->fail("problems getting playlist metadata."); $this->fail("problems getting playlist metadata.");
return; return;
} }
} }
function testAddAudioClip() { function testAddAudioClip() {
// Add a file
$values = array("filepath" => dirname(__FILE__)."/test10001.mp3");
$this->storedFile = StoredFile::Insert($values, false);
// Add a file
$values = array("filepath" => dirname(__FILE__)."/test10002.mp3");
$this->storedFile2 = StoredFile::Insert($values, false);
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("Add"); $pl_id = $pl->create("Playlist Unit Test ". uniqid());
$res = $pl->addAudioClip($this->storedFile->getId());
$res = $this->greenbox->addAudioClipToPlaylist($pl_id, '1');
if($res !== TRUE) { if($res !== TRUE) {
$this->fail("problems adding audioclip to playlist."); $this->fail("problems adding audioclip to playlist.");
return; return;
} }
$res = $pl->addAudioClip($this->storedFile2->getId());
if($res !== TRUE) {
$this->fail("problems adding audioclip 2 to playlist.");
return;
}
} }
function testMoveAudioClip() { function testMoveAudioClip() {
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("Move"); $pl_id = $pl->create("Move");
$this->greenbox->addAudioClipToPlaylist($pl_id, '1'); $this->greenbox->addAudioClipToPlaylist($pl_id, '1');
$this->greenbox->addAudioClipToPlaylist($pl_id, '2'); $this->greenbox->addAudioClipToPlaylist($pl_id, '2');
$res = $this->greenbox->moveAudioClipInPlaylist($pl_id, 0, 1); $res = $this->greenbox->moveAudioClipInPlaylist($pl_id, 0, 1);
if($res !== TRUE) { if($res !== TRUE) {
$this->fail("problems moving audioclip in playlist."); $this->fail("problems moving audioclip in playlist.");
return; return;
} }
} }
function testDeleteAudioClip() { function testDeleteAudioClip() {
$pl = new Playlist(); $pl = new Playlist();
$pl_id = $pl->create("Delete"); $pl_id = $pl->create("Delete");
$this->greenbox->addAudioClipToPlaylist($pl_id, '1'); $this->greenbox->addAudioClipToPlaylist($pl_id, '1');
$res = $this->greenbox->delAudioClipFromPlaylist($pl_id, 0); $res = $this->greenbox->delAudioClipFromPlaylist($pl_id, 0);
if($res !== TRUE) { if($res !== TRUE) {
$this->fail("problems deleting audioclip from playlist."); $this->fail("problems deleting audioclip from playlist.");
return; return;
} }
} }
function testFadeInfo() { function testFadeInfo() {
@ -162,7 +172,6 @@ class PlayListTests extends PHPUnit_TestCase {
return; return;
} }
} }
} }
?> ?>

View File

@ -60,7 +60,7 @@ class SchedulerTests extends PHPUnit_TestCase {
function testAddAndRemovePlaylist() { function testAddAndRemovePlaylist() {
// Create a playlist // Create a playlist
$playlist = new Playlist(); $playlist = new Playlist();
$playlist->create("Scheduler Unit Test"); $playlist->create("Scheduler Unit Test ".uniqid());
$result = $playlist->addAudioClip($this->storedFile->getId()); $result = $playlist->addAudioClip($this->storedFile->getId());
$result = $playlist->addAudioClip($this->storedFile2->getId()); $result = $playlist->addAudioClip($this->storedFile2->getId());
$result = $playlist->addAudioClip($this->storedFile2->getId()); $result = $playlist->addAudioClip($this->storedFile2->getId());
@ -76,7 +76,7 @@ class SchedulerTests extends PHPUnit_TestCase {
$this->fail("Wrong number of items added."); $this->fail("Wrong number of items added.");
} }
$items = $group->getItems(); $items = $group->getItems();
if ($items[1]["starts"] != "2010-11-11 01:30:34.231") { if (!is_array($items) || ($items[1]["starts"] != "2010-11-11 01:30:34.231")) {
$this->fail("Wrong start time for 2nd item."); $this->fail("Wrong start time for 2nd item.");
} }

View File

@ -1,7 +1,7 @@
<?php <?php
require_once(dirname(__FILE__).'/../StoredFile.php'); require_once(dirname(__FILE__).'/../StoredFile.php');
require_once(dirname(__FILE__).'/../BasicStor.php'); //require_once(dirname(__FILE__).'/../BasicStor.php');
require_once(dirname(__FILE__).'/../GreenBox.php'); //require_once(dirname(__FILE__).'/../GreenBox.php');
$dsn = $CC_CONFIG['dsn']; $dsn = $CC_CONFIG['dsn'];
$CC_DBC = DB::connect($dsn, TRUE); $CC_DBC = DB::connect($dsn, TRUE);
@ -11,16 +11,13 @@ if (PEAR::isError($CC_DBC)) {
} }
$CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC); $CC_DBC->setFetchMode(DB_FETCHMODE_ASSOC);
class BasicStorTest extends PHPUnit_TestCase { class StoredFileTest extends PHPUnit_TestCase {
private $greenbox; function __construct($name) {
parent::__construct($name);
// function __construct($name) { }
// parent::__construct($name);
// }
function setup() { function setup() {
$this->greenbox = new GreenBox();
} }
function testGetAudioMetadata() { function testGetAudioMetadata() {
@ -53,11 +50,13 @@ class BasicStorTest extends PHPUnit_TestCase {
} }
$values = array("filepath" => $filePath); $values = array("filepath" => $filePath);
$storedFile = $this->greenbox->bsPutFile($values, false); // Insert and link to file, dont copy it
$storedFile = StoredFile::Insert($values, false);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
$this->fail("Failed to create StoredFile: ".$storedFile->getMessage()); $this->fail("Failed to create StoredFile: ".$storedFile->getMessage());
return; return;
} }
//var_dump($storedFile);
$id = $storedFile->getId(); $id = $storedFile->getId();
if (!is_numeric($id)) { if (!is_numeric($id)) {
$this->fail("StoredFile not created correctly. id = ".$id); $this->fail("StoredFile not created correctly. id = ".$id);

View File

@ -269,7 +269,8 @@ class uiBase
$this->id = $this->gb->storId; $this->id = $this->gb->storId;
} }
if (!is_null($this->id)) { if (!is_null($this->id)) {
$this->type = Greenbox::getFileType($this->id); $f = StoredFile::Recall($this->id);
$this->type = $f->getType();
} }
} }
@ -481,35 +482,35 @@ class uiBase
* local ID of file * local ID of file
* @param string $format * @param string $format
*/ */
public function analyzeFile($id, $format) // public function analyzeFile($id, $format)
{ // {
$ia = $this->gb->analyzeFile($id, $this->sessid); // $ia = $this->gb->analyzeFile($id, $this->sessid);
$s = $ia['playtime_seconds']; // $s = $ia['playtime_seconds'];
$extent = date('H:i:s', floor($s)-date('Z')).substr(number_format($s, 6), strpos(number_format($s, 6), '.')); // $extent = date('H:i:s', floor($s)-date('Z')).substr(number_format($s, 6), strpos(number_format($s, 6), '.'));
//
if ($format=='text') { // if ($format=='text') {
return "<div align='left'><pre>".var_export($ia, TRUE)."</pre></div>"; // return "<div align='left'><pre>".var_export($ia, TRUE)."</pre></div>";
} // }
return FALSE; // return FALSE;
} // fn analyzeFile // }
public function toHex($gunid) // public function toHex($gunid)
{ // {
global $CC_DBC; // global $CC_DBC;
$res = $CC_DBC->query("SELECT to_hex($gunid)"); // $res = $CC_DBC->query("SELECT to_hex($gunid)");
$row = $res->fetchRow(); // $row = $res->fetchRow();
return $row['to_hex']; // return $row['to_hex'];
} // }
public function toInt8($gunid) // public function toInt8($gunid)
{ // {
global $CC_DBC; // global $CC_DBC;
$res = $CC_DBC->query("SELECT x'$gunid'::bigint"); // $res = $CC_DBC->query("SELECT x'$gunid'::bigint");
$row = $res->fetchRow(); // $row = $res->fetchRow();
return $row['int8']; // return $row['int8'];
} // }
/** /**
@ -540,17 +541,17 @@ class uiBase
public function getMetaInfo($id) public function getMetaInfo($id)
{ {
$type = strtolower(GreenBox::getFileType($id)); $media = StoredFile::Recall($id);
$type = strtolower($media->getType());
$data = array('id' => $id, $data = array('id' => $id,
'gunid' => BasicStor::GunidFromId($id), 'gunid' => $media->getGunid(),
'title' => $this->getMetadataValue($id, UI_MDATA_KEY_TITLE), 'title' => $media->getMetadataValue($id, UI_MDATA_KEY_TITLE),
'creator' => $this->getMetadataValue($id, UI_MDATA_KEY_CREATOR), 'creator' => $media->getMetadataValue($id, UI_MDATA_KEY_CREATOR),
'duration' => $this->getMetadataValue($id, UI_MDATA_KEY_DURATION), 'duration' => $media->getMetadataValue($id, UI_MDATA_KEY_DURATION),
'type' => $type, 'type' => $type,
'source' => $type == 'audioclip' ? $this->getMetadataValue($id, UI_MDATA_KEY_SOURCE) : NULL, 'source' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SOURCE) : NULL,
'bitRate' => $type == 'audioclip' ? $this->getMetadataValue($id, UI_MDATA_KEY_BITRATE) : NULL, 'bitRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_BITRATE) : NULL,
'sampleRate' => $type == 'audioclip' ? $this->getMetadataValue($id, UI_MDATA_KEY_SAMPLERATE) : NULL, 'sampleRate' => $type == 'audioclip' ? $media->getMetadataValue($id, UI_MDATA_KEY_SAMPLERATE) : NULL,
); );
return ($data); return ($data);
} }

View File

@ -2,7 +2,6 @@
/** /**
* @package Campcaster * @package Campcaster
* @subpackage htmlUI * @subpackage htmlUI
*/ */
class uiBrowser extends uiBase { class uiBrowser extends uiBase {
@ -389,8 +388,8 @@ class uiBrowser extends uiBase {
function listen2Audio($clipid) function listen2Audio($clipid)
{ {
global $CC_CONFIG; global $CC_CONFIG;
$id = BasicStor::IdFromGunid($clipid); $media = StoredFile::RecallByGunid($clipid);
$type = Greenbox::getFileType($id); $type = $media->getType();
if (1) { if (1) {
header("Location: http://{$_SERVER['SERVER_NAME']}".$CC_CONFIG['accessRawAudioUrl']."?sessid={$this->sessid}&id=$clipid\n"); header("Location: http://{$_SERVER['SERVER_NAME']}".$CC_CONFIG['accessRawAudioUrl']."?sessid={$this->sessid}&id=$clipid\n");

View File

@ -137,20 +137,21 @@ if (isset($_REQUEST['popup']) && is_array($_REQUEST['popup'])){
break; break;
case "PL.downloadExportedFile": case "PL.downloadExportedFile":
$exportedPlaylist = $uiBrowser->gb->exportPlaylistOpen($uiBrowser->sessid,
BasicStor::GunidFromId($_REQUEST['id']), // $exportedPlaylist = $uiBrowser->gb->exportPlaylistOpen($uiBrowser->sessid,
$_REQUEST['playlisttype'], // BasicStor::GunidFromId($_REQUEST['id']),
$_REQUEST['exporttype']=='playlistOnly'?true:false); // $_REQUEST['playlisttype'],
$fp = fopen($exportedPlaylist['fname'],'r'); // $_REQUEST['exporttype']=='playlistOnly'?true:false);
if (is_resource($fp)) { // $fp = fopen($exportedPlaylist['fname'],'r');
header("Content-Type: application/octet-stream"); // if (is_resource($fp)) {
header("Content-Length: " . filesize($exportedPlaylist['fname'])); // header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="playlist.tar"'); // header("Content-Length: " . filesize($exportedPlaylist['fname']));
header("Content-Transfer-Encoding: binary\n"); // header('Content-Disposition: attachment; filename="playlist.tar"');
fpassthru($fp); // header("Content-Transfer-Encoding: binary\n");
$uiBrowser->gb->exportPlaylistClose($exportedPlaylist['token']); // fpassthru($fp);
} // $uiBrowser->gb->exportPlaylistClose($exportedPlaylist['token']);
//$Smarty->display('popup/PLAYLIST.downloadExportedFile.tpl'); // }
// //$Smarty->display('popup/PLAYLIST.downloadExportedFile.tpl');
break; break;
case "SCHEDULER.addItem": case "SCHEDULER.addItem":
@ -354,10 +355,10 @@ if ($uiBrowser->userid) {
$Smarty->assign('showFile', TRUE); $Smarty->assign('showFile', TRUE);
break; break;
case "_analyzeFile": // case "_analyzeFile":
$Smarty->assign('_analyzeFile', $uiBrowser->analyzeFile($uiBrowser->id, 'text')); // $Smarty->assign('_analyzeFile', $uiBrowser->analyzeFile($uiBrowser->id, 'text'));
$Smarty->assign('showFile', TRUE); // $Smarty->assign('showFile', TRUE);
break; // break;
case "changeStationPrefs": case "changeStationPrefs":
$Smarty->assign('dynform', $uiBrowser->changeStationPrefs($ui_fmask['stationPrefs'])); $Smarty->assign('dynform', $uiBrowser->changeStationPrefs($ui_fmask['stationPrefs']));

View File

@ -124,7 +124,7 @@ class uiHandler extends uiBase {
$metadata['ls:filename'] = basename($audio_file); $metadata['ls:filename'] = basename($audio_file);
} }
// bsSetMetadataBatch doesnt like these values // setMetadataBatch doesnt like these values
unset($metadata['audio']); unset($metadata['audio']);
unset($metadata['playtime_seconds']); unset($metadata['playtime_seconds']);
@ -141,7 +141,7 @@ class uiHandler extends uiBase {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}'); die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": ' + $storedFile->getMessage() + '}}');
} }
$result = $this->gb->bsSetMetadataBatch($storedFile->getId(), $metadata); $result = $storedFile->setMetadataBatch($metadata);
return $storedFile->getId(); return $storedFile->getId();
} }
@ -263,12 +263,6 @@ class uiHandler extends uiBase {
$id = $formdata['id']; $id = $formdata['id'];
$folderId = $formdata['folderId']; $folderId = $formdata['folderId'];
if (Greenbox::getFileType($folderId) != 'Folder') {
$this->_retMsg('The target is not a folder.');
$this->redirUrl = UI_BROWSER."?act=fileList";
return FALSE;
}
if (!$this->_validateForm($formdata, $mask)) { if (!$this->_validateForm($formdata, $mask)) {
$this->redirUrl = UI_BROWSER."?act=editFile&id=".$id; $this->redirUrl = UI_BROWSER."?act=editFile&id=".$id;
return FALSE; return FALSE;
@ -301,7 +295,7 @@ class uiHandler extends uiBase {
$metadata['ls:filename'] = $formdata['mediafile']['name']; $metadata['ls:filename'] = $formdata['mediafile']['name'];
} }
// bsSetMetadataBatch doesnt like these values // setMetadataBatch doesnt like these values
unset($metadata['audio']); unset($metadata['audio']);
unset($metadata['playtime_seconds']); unset($metadata['playtime_seconds']);
@ -326,7 +320,7 @@ class uiHandler extends uiBase {
return FALSE; return FALSE;
} }
$result = $this->gb->bsSetMetadataBatch($storedFile->getId(), $metadata); $result = $storedFile->setMetadataBatch($metadata);
$this->redirUrl = UI_BROWSER."?act=addFileMData&id=".$storedFile->getId(); $this->redirUrl = UI_BROWSER."?act=addFileMData&id=".$storedFile->getId();
$this->_retMsg('Audioclip has been uploaded successfully.'); $this->_retMsg('Audioclip has been uploaded successfully.');
@ -353,45 +347,45 @@ class uiHandler extends uiBase {
* @param unknown_type $langid * @param unknown_type $langid
* @return void * @return void
*/ */
function translateMetadata($id, $langid=UI_DEFAULT_LANGID) // function translateMetadata($id, $langid=UI_DEFAULT_LANGID)
{ // {
include(dirname(__FILE__).'/formmask/metadata.inc.php'); // include(dirname(__FILE__).'/formmask/metadata.inc.php');
//
$ia = $this->gb->analyzeFile($id, $this->sessid); // $ia = $this->gb->analyzeFile($id, $this->sessid);
if (PEAR::isError($ia)) { // if (PEAR::isError($ia)) {
$this->_retMsg($ia->getMessage()); // $this->_retMsg($ia->getMessage());
return; // return;
}
// This is really confusing: the import script does not do it
// this way. Which way is the right way?
$this->setMetadataValue($id, UI_MDATA_KEY_DURATION, Playlist::secondsToPlaylistTime($ia['playtime_seconds']));
// $this->setMetadataValue($id, UI_MDATA_KEY_FORMAT, UI_MDATA_VALUE_FORMAT_FILE);
// some data from raw audio
// if (isset($ia['audio']['channels'])) {
// $this->setMetadataValue($id, UI_MDATA_KEY_CHANNELS, $ia['audio']['channels']);
// } // }
// if (isset($ia['audio']['sample_rate'])) { // // This is really confusing: the import script does not do it
// $this->setMetadataValue($id, UI_MDATA_KEY_SAMPLERATE, $ia['audio']['sample_rate']); // // this way. Which way is the right way?
// $this->setMetadataValue($id, UI_MDATA_KEY_DURATION, Playlist::secondsToPlaylistTime($ia['playtime_seconds']));
//// $this->setMetadataValue($id, UI_MDATA_KEY_FORMAT, UI_MDATA_VALUE_FORMAT_FILE);
//
// // some data from raw audio
//// if (isset($ia['audio']['channels'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_CHANNELS, $ia['audio']['channels']);
//// }
//// if (isset($ia['audio']['sample_rate'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_SAMPLERATE, $ia['audio']['sample_rate']);
//// }
//// if (isset($ia['audio']['bitrate'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_BITRATE, $ia['audio']['bitrate']);
//// }
//// if (isset($ia['audio']['codec'])) {
//// $this->setMetadataValue($id, UI_MDATA_KEY_ENCODER, $ia['audio']['codec']);
//// }
//
// // from id3 Tags
// // loop main, music, talk
// foreach ($mask['pages'] as $key => $val) {
// // loop through elements
// foreach ($mask['pages'][$key] as $k => $v) {
// if (isset($v['element']) && isset($ia[$v['element']])) {
// $this->setMetadataValue($id, $v['element'], $ia[$v['element']], $langid);
// }
// }
// } // }
// if (isset($ia['audio']['bitrate'])) { // }
// $this->setMetadataValue($id, UI_MDATA_KEY_BITRATE, $ia['audio']['bitrate']);
// }
// if (isset($ia['audio']['codec'])) {
// $this->setMetadataValue($id, UI_MDATA_KEY_ENCODER, $ia['audio']['codec']);
// }
// from id3 Tags
// loop main, music, talk
foreach ($mask['pages'] as $key => $val) {
// loop through elements
foreach ($mask['pages'][$key] as $k => $v) {
if (isset($v['element']) && isset($ia[$v['element']])) {
$this->setMetadataValue($id, $v['element'], $ia[$v['element']], $langid);
}
}
}
}
/** /**
@ -403,13 +397,8 @@ class uiHandler extends uiBase {
function addWebstream($formdata, $mask) function addWebstream($formdata, $mask)
{ {
$id = $formdata['id']; $id = $formdata['id'];
$folderId = $formdata['folderId']; //$folderId = $formdata['folderId'];
if (Greenbox::getFileType($folderId) != 'Folder') {
$this->_retMsg ('The target is not a folder.');
$this->redirUrl = UI_BROWSER."?act=fileList";
return FALSE;
}
if (!$this->_validateForm($formdata, $mask)) { if (!$this->_validateForm($formdata, $mask)) {
$this->redirUrl = UI_BROWSER."?act=editWebstream&id=".$id; $this->redirUrl = UI_BROWSER."?act=editWebstream&id=".$id;
return FALSE; return FALSE;
@ -534,16 +523,13 @@ class uiHandler extends uiBase {
} }
foreach ($ids as $id) { foreach ($ids as $id) {
if (Greenbox::getFileType($id) == 'playlist') { $media = StoredFile::Recall($id);
$r = $this->gb->deletePlaylist($id, $this->sessid); $r = $media->delete();
} else {
$r = $this->gb->deleteFile($id, $this->sessid);
}
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
$this->_retMsg($r->getMessage()); $this->_retMsg($r->getMessage());
return FALSE; return FALSE;
} }
} }
return TRUE; return TRUE;

View File

@ -11,7 +11,7 @@ class uiPlaylist
public $activeId; public $activeId;
public $title; public $title;
public $duration; public $duration;
private $Base; private $Base;
private $reloadUrl; private $reloadUrl;
private $redirectUrl; private $redirectUrl;
@ -33,10 +33,10 @@ class uiPlaylist
public function setReload($url=NULL) public function setReload($url=NULL)
{ {
if($url) if($url)
$this->Base->redirUrl = $url; $this->Base->redirUrl = $url;
else else
$this->Base->redirUrl = $this->reloadUrl; $this->Base->redirUrl = $this->reloadUrl;
} // fn setReload } // fn setReload
@ -65,7 +65,7 @@ class uiPlaylist
public function getActiveArr() public function getActiveArr()
{ {
if (!$this->activeId) { if (!$this->activeId) {
return FALSE; return FALSE;
} }
@ -91,7 +91,7 @@ class uiPlaylist
if ($this->activeId) { if ($this->activeId) {
$this->release(); $this->release();
} }
$userid = $this->Base->gb->playlistIsAvailable($plid, $this->Base->sessid); $userid = $this->Base->gb->playlistIsAvailable($plid, $this->Base->sessid);
if ($userid !== TRUE) { if ($userid !== TRUE) {
if (UI_WARNING) { if (UI_WARNING) {
@ -107,10 +107,10 @@ class uiPlaylist
$this->Base->_retMsg('Unable to open playlist "$1".', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); $this->Base->_retMsg('Unable to open playlist "$1".', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE));
return FALSE; return FALSE;
} }
$this->Base->gb->savePref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY, $plid); $this->Base->gb->savePref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY, $plid);
$this->activeId = $plid; $this->activeId = $plid;
if ($msg && UI_VERBOSE) { if ($msg && UI_VERBOSE) {
$this->Base->_retMsg('Playlist "$1" opened.', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE)); $this->Base->_retMsg('Playlist "$1" opened.', $this->Base->getMetadataValue($plid, UI_MDATA_KEY_TITLE));
} }
@ -120,7 +120,7 @@ class uiPlaylist
public function release($msg=TRUE) public function release($msg=TRUE)
{ {
// release PL // release PL
// delete PL from session // delete PL from session
if (!$this->activeId) { if (!$this->activeId) {
@ -139,12 +139,9 @@ class uiPlaylist
} }
return FALSE; return FALSE;
} }
if ($msg && UI_VERBOSE) {
$this->Base->_retMsg('Playlist "$1" released.', $this->Base->getMetadataValue(BasicStor::IdFromGunid($plgunid), UI_MDATA_KEY_TITLE));
}
$this->activeId = NULL; $this->activeId = NULL;
$this->Base->gb->delPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY); $this->Base->gb->delPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY);
return TRUE; return TRUE;
} // fn release } // fn release
@ -164,16 +161,16 @@ class uiPlaylist
public function loadLookedFromPref() public function loadLookedFromPref()
{ {
if (is_string($plid = $this->Base->gb->loadPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY))) { if (is_string($plid = $this->Base->gb->loadPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY))) {
if (!$this->Base->gb->existsPlaylist($plid)) { if (!$this->Base->gb->existsPlaylist($plid)) {
$this->Base->gb->delPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY); $this->Base->gb->delPref($this->Base->sessid, UI_PL_ACCESSTOKEN_KEY);
$this->Base->_retMsg('Playlist not found in database.'); $this->Base->_retMsg('Playlist not found in database.');
$this->Base->redirUrl = UI_BROWSER.'?popup[]=_2PL.simpleManagement&popup[]=_close'; $this->Base->redirUrl = UI_BROWSER.'?popup[]=_2PL.simpleManagement&popup[]=_close';
return FALSE; return FALSE;
} }
$this->activeId = $plid; $this->activeId = $plid;
$this->Base->redirUrl = UI_BROWSER.'?popup[]=_2PL.simpleManagement&popup[]=_close'; $this->Base->redirUrl = UI_BROWSER.'?popup[]=_2PL.simpleManagement&popup[]=_close';
return TRUE; return TRUE;
} }
@ -195,7 +192,7 @@ class uiPlaylist
$cliplength = NULL; $cliplength = NULL;
$cueIn = NULL; $cueIn = NULL;
$cueIn = NULL; $cueIn = NULL;
/* /*
gstreamer bug: gstreamer bug:
Warning: The clipEnd can't be bigger than ninety nine percent (99%) of the clipLength, Warning: The clipEnd can't be bigger than ninety nine percent (99%) of the clipLength,
@ -208,14 +205,14 @@ class uiPlaylist
$this->Base->_retMsg('No item(s) selected.'); $this->Base->_retMsg('No item(s) selected.');
} }
return FALSE; return FALSE;
} }
if (!is_array($elemIds)) { if (!is_array($elemIds)) {
$elemIds = array($elemIds); $elemIds = array($elemIds);
} }
if (isset($duration)) { if (isset($duration)) {
$length = sprintf('%02d', $duration['H']).':'.sprintf('%02d', $duration['i']).':'.sprintf('%02d', $duration['s']).'.000000'; $length = sprintf('%02d', $duration['H']).':'.sprintf('%02d', $duration['i']).':'.sprintf('%02d', $duration['s']).'.000000';
} }
foreach ($elemIds as $elemId) { foreach ($elemIds as $elemId) {
$r = $this->Base->gb->addAudioClipToPlaylist($this->activeId, $elemId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut); $r = $this->Base->gb->addAudioClipToPlaylist($this->activeId, $elemId, $pos, $fadeIn, $fadeOut, $cliplength, $cueIn, $cueOut);
if (PEAR::isError($r)) { if (PEAR::isError($r)) {
@ -226,9 +223,9 @@ class uiPlaylist
return FALSE; return FALSE;
} }
} }
$this->Base->SCRATCHPAD->reloadActivePLMetadata($this->activeId); $this->Base->SCRATCHPAD->reloadActivePLMetadata($this->activeId);
return TRUE; return TRUE;
} // fn addItem } // fn addItem
@ -243,20 +240,20 @@ class uiPlaylist
} }
if (!is_array($positions)) if (!is_array($positions))
$positions = array($positions); $positions = array($positions);
//so the automatic updating of playlist positioning doesn't affect removal. //so the automatic updating of playlist positioning doesn't affect removal.
sort($positions); sort($positions);
$positions = array_reverse($positions); $positions = array_reverse($positions);
foreach ($positions as $pos) { foreach ($positions as $pos) {
if ($this->Base->gb->delAudioClipFromPlaylist($this->activeId, $pos) !== TRUE) { if ($this->Base->gb->delAudioClipFromPlaylist($this->activeId, $pos) !== TRUE) {
$this->Base->_retMsg('Cannot remove item from playlist.'); $this->Base->_retMsg('Cannot remove item from playlist.');
return FALSE; return FALSE;
} }
} }
$this->Base->SCRATCHPAD->reloadActivePLMetadata($this->activeId); $this->Base->SCRATCHPAD->reloadActivePLMetadata($this->activeId);
return TRUE; return TRUE;
} // fn removeItem } // fn removeItem
@ -274,14 +271,14 @@ class uiPlaylist
// create PL // create PL
// activate // activate
// add clip if $id is set // add clip if $id is set
if ($this->activeId) { if ($this->activeId) {
$this->release(); $this->release();
} }
$datetime = strftime('%Y-%m-%d %H:%M:%S'); $datetime = strftime('%Y-%m-%d %H:%M:%S');
$plid = $this->Base->gb->createPlaylist($datetime, $this->Base->sessid); $plid = $this->Base->gb->createPlaylist($datetime, $this->Base->sessid);
if (!$plid) { if (!$plid) {
$this->Base->_retMsg('Cannot create playlist.'); $this->Base->_retMsg('Cannot create playlist.');
return FALSE; return FALSE;
@ -290,7 +287,7 @@ class uiPlaylist
$this->Base->gb->setPLMetadataValue($plid, UI_MDATA_KEY_CREATOR, $this->Base->login); $this->Base->gb->setPLMetadataValue($plid, UI_MDATA_KEY_CREATOR, $this->Base->login);
$this->Base->gb->setPLMetadataValue($plid, UI_MDATA_KEY_DESCRIPTION, tra('created at $1', $datetime)); $this->Base->gb->setPLMetadataValue($plid, UI_MDATA_KEY_DESCRIPTION, tra('created at $1', $datetime));
if ($this->activate($plid)===FALSE) { if ($this->activate($plid)===FALSE) {
$this->Base->_retMsg('Cannot activate playlist.'); $this->Base->_retMsg('Cannot activate playlist.');
return FALSE; return FALSE;
@ -300,14 +297,14 @@ class uiPlaylist
return FALSE; return FALSE;
} }
} }
return $plid; return $plid;
} // fn create } // fn create
public function moveItem($oldPos, $newPos) public function moveItem($oldPos, $newPos)
{ {
$response = array(); $response = array();
$r = $this->Base->gb->moveAudioClipInPlaylist($this->activeId, $oldPos, $newPos); $r = $this->Base->gb->moveAudioClipInPlaylist($this->activeId, $oldPos, $newPos);
if (PEAR::isError($r) || $r === FALSE) { if (PEAR::isError($r) || $r === FALSE) {
$response["error"] = "Failed to Move file."; $response["error"] = "Failed to Move file.";
@ -315,9 +312,9 @@ class uiPlaylist
$response["newPos"] = $newPos; $response["newPos"] = $newPos;
} }
else{ else{
$response["error"] = FALSE; $response["error"] = FALSE;
} }
die(json_encode($response)); die(json_encode($response));
} // fn moveItem } // fn moveItem
@ -325,22 +322,22 @@ class uiPlaylist
public function setClipLength($pos, $cueIn, $cueOut) public function setClipLength($pos, $cueIn, $cueOut)
{ {
$response = array(); $response = array();
$res = $this->Base->gb->changeClipLength($this->activeId, $pos, $cueIn, $cueOut); $res = $this->Base->gb->changeClipLength($this->activeId, $pos, $cueIn, $cueOut);
$response = $res; $response = $res;
die(json_encode($response)); die(json_encode($response));
} }
public function setFadeLength($pos, $fadeIn, $fadeOut) public function setFadeLength($pos, $fadeIn, $fadeOut)
{ {
$response = array(); $response = array();
$res = $this->Base->gb->changeFadeInfo($this->activeId, $pos, $fadeIn, $fadeOut); $res = $this->Base->gb->changeFadeInfo($this->activeId, $pos, $fadeIn, $fadeOut);
$response = $res; $response = $res;
die(json_encode($response)); die(json_encode($response));
} // fn setFade } // fn setFade
@ -353,7 +350,7 @@ class uiPlaylist
foreach ($mask['playlist'] as $k=>$v) { foreach ($mask['playlist'] as $k=>$v) {
$mask['playlist'][$k]['element'] = uiBase::formElementEncode($v['element']); $mask['playlist'][$k]['element'] = uiBase::formElementEncode($v['element']);
$getval = $this->Base->gb->getPLMetadataValue($id, $v['element'], $langid); $getval = $this->Base->gb->getPLMetadataValue($id, $v['element'], $langid);
if ($getval) { if ($getval) {
$mask['playlist'][$k]['default'] = $getval; $mask['playlist'][$k]['default'] = $getval;
@ -398,9 +395,9 @@ class uiPlaylist
} else { } else {
$this->Base->redirUrl = UI_BROWSER."?act=PL.editMetaData&id=$id&curr_langid=".$formdata['target_langid']; $this->Base->redirUrl = UI_BROWSER."?act=PL.editMetaData&id=$id&curr_langid=".$formdata['target_langid'];
} }
foreach ($mask['playlist'] as $k=>$v) { foreach ($mask['playlist'] as $k=>$v) {
$formdata[uiBase::formElementEncode($v['element'])] ? $mData[uiBase::formElementDecode($v['element'])] = $formdata[uiBase::formElementEncode($v['element'])] : NULL; $formdata[uiBase::formElementEncode($v['element'])] ? $mData[uiBase::formElementDecode($v['element'])] = $formdata[uiBase::formElementEncode($v['element'])] : NULL;
} }
@ -419,7 +416,7 @@ class uiPlaylist
} }
if (UI_VERBOSE) { if (UI_VERBOSE) {
$this->Base->_retMsg('Metadata saved.'); $this->Base->_retMsg('Metadata saved.');
} }
$this->Base->SCRATCHPAD->reloadMetadata(); $this->Base->SCRATCHPAD->reloadMetadata();
} // fn editMetadata } // fn editMetadata
@ -429,7 +426,7 @@ class uiPlaylist
{ {
$id = $this->activeId; $id = $this->activeId;
$this->release(FALSE); $this->release(FALSE);
$res = $this->Base->gb->deletePlaylist($id); $res = $this->Base->gb->deletePlaylist($id);
if ($res === TRUE) { if ($res === TRUE) {
return $id; return $id;
@ -438,7 +435,7 @@ class uiPlaylist
$this->Base->_retMsg('Cannot delete this playlist.'); $this->Base->_retMsg('Cannot delete this playlist.');
return FALSE; return FALSE;
} // fn deleteActive } // fn deleteActive
public function delete($id) public function delete($id)
{ {
$res = $this->Base->gb->deletePlaylist($id); $res = $this->Base->gb->deletePlaylist($id);

View File

@ -209,7 +209,7 @@ class uiScheduler extends uiCalendar {
// $hour = $arr['hour']; // $hour = $arr['hour'];
// $minute = $arr['minute']; // $minute = $arr['minute'];
// $second = $arr['second']; // $second = $arr['second'];
extract($arr); extract($arr);
if (isset($today)) { if (isset($today)) {
@ -456,25 +456,6 @@ class uiScheduler extends uiCalendar {
return $items; return $items;
} // fn getDayEntrys } // fn getDayEntrys
/*
function getDayHourlyEntrys($year, $month, $day)
{
$date = $year.'-'.$month.'-'.$day;
$arr = $this->displayScheduleMethod($date.' 00:00:00', $date.' 23:59:59.999999');
if (!count($arr))
return FALSE;
foreach ($arr as $key => $val) {
$items[date('H', self::datetimeToTimestamp($val['start']))][]= array (
'start' => substr($val['start'], strpos($val['start'], 'T')+1),
'end' => substr($val['end'], strpos($val['end'], 'T') + 1),
'title' => $this->Base->getMetadataValue(BasicStor::IdFromGunid($val['playlistId']), UI_MDATA_KEY_TITLE),
'creator' => $this->Base->getMetadataValue(BasicStor::IdFromGunid($val['playlistId']), UI_MDATA_KEY_CREATOR),
);
}
#print_r($items);
return $items;
}
*/
private function getDayUsage($year, $month, $day) private function getDayUsage($year, $month, $day)
{ {
@ -487,11 +468,12 @@ class uiScheduler extends uiCalendar {
} }
foreach ($arr as $key => $val) { foreach ($arr as $key => $val) {
$id = BasicStor::IdFromGunid($val['playlistId']); $pl = Playlist::Recall($val['playlistId']);
$arr[$key]['title'] = $this->Base->getMetadataValue($id, UI_MDATA_KEY_TITLE); //$id = BasicStor::IdFromGunid($val['playlistId']);
$arr[$key]['creator'] = $this->Base->getMetadataValue($id, UI_MDATA_KEY_CREATOR); $arr[$key]['title'] = $pl->getName(); //$this->Base->getMetadataValue($id, UI_MDATA_KEY_TITLE);
$arr[$key]['pos'] = self::datetimeToTimestamp($val['start']); $arr[$key]['creator'] = $pl->getPLMetaData("dc:title");// $this->Base->getMetadataValue($id, UI_MDATA_KEY_CREATOR);
$arr[$key]['span'] = date('H', self::datetimeToTimestamp($val['end'])) - date('H', self::datetimeToTimestamp($val['start'])) +1; $arr[$key]['pos'] = self::datetimeToTimestamp($val['start']);
$arr[$key]['span'] = date('H', self::datetimeToTimestamp($val['end'])) - date('H', self::datetimeToTimestamp($val['start'])) +1;
} }
return $arr; return $arr;
} // fn getDayUsage } // fn getDayUsage
@ -595,7 +577,7 @@ class uiScheduler extends uiCalendar {
} }
return TRUE; return TRUE;
} // fn copyPlfromSP }
/** /**
@ -707,22 +689,27 @@ class uiScheduler extends uiCalendar {
{ {
// just use methods which work without valid authentification // just use methods which work without valid authentification
$c_pl = self::getScheduledPlaylist(); $c_pl = self::getScheduledPlaylist();
$pl = Playlist::Recall($c_pl['playlistId']);
$n_clip = null; $n_clip = null;
if ($c_clip = $this->getClipFromCurrent($c_pl, 0)) { if ($c_clip = $this->getClipFromCurrent($c_pl, 0)) {
$n_clip = $this->getClipFromCurrent($c_pl, 1); $n_clip = $this->getClipFromCurrent($c_pl, 1);
} }
$nextClip = StoredFile::Recall($n_clip);
$u_clip = null; $u_clip = null;
$u_pl_start = null; $u_pl_start = null;
if ($u_pl = self::getScheduledPlaylist(2)) { if ($u_pl = self::getScheduledPlaylist(2)) {
$u_clip = $this->getClipFromPlaylist($u_pl); $u_clip = $this->getClipFromPlaylist($u_pl);
$u_pl_start = explode(':', date('H:i:s', self::datetimeToTimestamp($u_pl['start']))); $u_pl_start = explode(':', date('H:i:s', self::datetimeToTimestamp($u_pl['start'])));
} }
$upcomingClip = StoredFile::Recall($u_pl['playlistId']);
return array( return array(
'current' => $c_clip ? 1 : 0, 'current' => $c_clip ? 1 : 0,
'current.title' => addcslashes($c_clip['title'], "'"), 'current.title' => addcslashes($c_clip['title'], "'"),
'current.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($c_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"), //'current.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($c_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"),
'current.elapsed.h' => $c_clip['elapsed']['h'], 'current.pltitle' => addcslashes($pl->getName(), "'"),
'current.elapsed.h' => $c_clip['elapsed']['h'],
'current.elapsed.m' => $c_clip['elapsed']['m'], 'current.elapsed.m' => $c_clip['elapsed']['m'],
'current.elapsed.s' => $c_clip['elapsed']['s'], 'current.elapsed.s' => $c_clip['elapsed']['s'],
'current.duration.h' => $c_clip['duration']['h'], 'current.duration.h' => $c_clip['duration']['h'],
@ -731,15 +718,17 @@ class uiScheduler extends uiCalendar {
'next' => $n_clip ? 1 : 0, 'next' => $n_clip ? 1 : 0,
'next.title' => $n_clip ? addcslashes($n_clip['title'], "'") : "", 'next.title' => $n_clip ? addcslashes($n_clip['title'], "'") : "",
'next.pltitle' => addcslashes($this->Base->getMetadataValue($n_clip, UI_MDATA_KEY_TITLE), "'"), //'next.pltitle' => addcslashes($this->Base->getMetadataValue($n_clip, UI_MDATA_KEY_TITLE), "'"),
'next.duration.h' => $n_clip ? $n_clip['duration']['h'] : 0, 'next.pltitle' => addcslashes($nextClip->getTitle(), "'"),
'next.duration.h' => $n_clip ? $n_clip['duration']['h'] : 0,
'next.duration.m' => $n_clip ? $n_clip['duration']['m'] : 0, 'next.duration.m' => $n_clip ? $n_clip['duration']['m'] : 0,
'next.duration.s' => $n_clip ? $n_clip['duration']['s'] : 0, 'next.duration.s' => $n_clip ? $n_clip['duration']['s'] : 0,
'upcoming' => $u_pl ? 1 : 0, 'upcoming' => $u_pl ? 1 : 0,
'upcoming.title' => addcslashes($u_clip['title'], "'"), 'upcoming.title' => addcslashes($u_clip['title'], "'"),
'upcoming.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($u_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"), //'upcoming.pltitle' => addcslashes($this->Base->getMetadataValue(BasicStor::IdFromGunid($u_pl['playlistId']), UI_MDATA_KEY_TITLE), "'"),
'upcoming.duration.h' => $u_clip['duration']['h'], 'upcoming.pltitle' => addcslashes($upcomingClip->getName(), "'"),
'upcoming.duration.h' => $u_clip['duration']['h'],
'upcoming.duration.m' => $u_clip['duration']['m'], 'upcoming.duration.m' => $u_clip['duration']['m'],
'upcoming.duration.s' => $u_clip['duration']['s'], 'upcoming.duration.s' => $u_clip['duration']['s'],
'upcoming.plstart.h' => $u_pl_start[0], 'upcoming.plstart.h' => $u_pl_start[0],

View File

@ -77,12 +77,12 @@ class uiScratchPad
// get the scratchpad list // get the scratchpad list
$arr = explode(' ', $spData); $arr = explode(' ', $spData);
$maxLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY]; $maxLength = $this->Base->STATIONPREFS[UI_SCRATCHPAD_MAXLENGTH_KEY];
$arr = array_slice($arr, 0, $maxLength); $arr = array_slice($arr, 0, $maxLength);
foreach ($arr as $item) { foreach ($arr as $item) {
//for audiofiles. //for audiofiles.
list($type, $savedId) = explode(":", $item); list($type, $savedId) = explode(":", $item);
if($type === 'pl') { if($type === 'pl') {
$id = $savedId; $id = $savedId;
if ($i = $this->Base->getPLMetaInfo($id)) { if ($i = $this->Base->getPLMetaInfo($id)) {
$this->items[] = $i; $this->items[] = $i;
@ -91,9 +91,10 @@ class uiScratchPad
else { else {
$gunid = $savedId; $gunid = $savedId;
if (preg_match('/[0-9]{1,20}/', $gunid)) { if (preg_match('/[0-9]{1,20}/', $gunid)) {
$id = BasicStor::IdFromGunid($this->Base->toHex($gunid)); $f = StoredFile::RecallByGunid($gunid);
if ($id != FALSE) { //$id = BasicStor::IdFromGunid($this->Base->toHex($gunid));
if ($i = $this->Base->getMetaInfo($id)) { if (!PEAR::isError($f)) {
if ($i = $this->Base->getMetaInfo($f->getId())) {
$this->items[] = $i; $this->items[] = $i;
} }
} }
@ -115,7 +116,7 @@ class uiScratchPad
$str .= 'pl:'.$val['id'].' '; $str .= 'pl:'.$val['id'].' ';
} }
else { else {
$str .= 'ac:'.$this->Base->toInt8($val['gunid']).' '; $str .= 'ac:'.$val['gunid'].' ';
} }
} }
$this->Base->gb->savePref($this->Base->sessid, UI_SCRATCHPAD_KEY, $str); $this->Base->gb->savePref($this->Base->sessid, UI_SCRATCHPAD_KEY, $str);
@ -264,7 +265,7 @@ class uiScratchPad
$this->items[$key] = $this->Base->getMetaInfo($val['id']); $this->items[$key] = $this->Base->getMetaInfo($val['id']);
} }
} }
public function reloadActivePLMetadata($id) public function reloadActivePLMetadata($id)
{ {
foreach ($this->items as $key => $val) { foreach ($this->items as $key => $val) {
@ -274,6 +275,6 @@ class uiScratchPad
} }
} }
} }
} // class uiScratchPad } // class uiScratchPad
?> ?>

View File

@ -155,8 +155,9 @@ class uiTransfers
function upload2Hub($id) function upload2Hub($id)
{ {
$gunid = BasicStor::GunidFromId($id); $media = StoredFile::Recall($id);
$type = BasicStor::GetType($gunid); $gunid = $media->getGunid();
$type = $media->getType();
switch ($type) { switch ($type) {
case 'audioClip': case 'audioClip':

View File

@ -365,10 +365,12 @@ class uiTwitter {
return FALSE; return FALSE;
} }
$f = StoredFile::RecallByGunid($clip['gunid']);
$pl = Playlist::Recall($pl['playlistId']);
return array( return array(
'tracktitle' => $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_TITLE, $this->Base->sessid), 'tracktitle' => $f->getMetadataValue(UI_MDATA_KEY_TITLE), //$this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_TITLE, $this->Base->sessid),
'trackartist' => $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_CREATOR, $this->Base->sessid), 'trackartist' => $f->getMetadataValue(UI_MDATA_KEY_CREATOR), // $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($clip['gunid']), UI_MDATA_KEY_CREATOR, $this->Base->sessid),
'playlisttitle' => $this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($pl['playlistId']), UI_MDATA_KEY_TITLE, $this->Base->sessid), 'playlisttitle' => $pl->getName() //$this->Base->gb->getMetadataValue(BasicStor::IdFromGunid($pl['playlistId']), UI_MDATA_KEY_TITLE, $this->Base->sessid),
); );
} }

View File

@ -26,16 +26,9 @@ function admDumpFolder(&$bs, $fid, $ind='')
// echo $name->getMessage(); // echo $name->getMessage();
// exit; // exit;
// } // }
$type = BasicStor::GetObjType($fid); $media = StoredFile::Recall($fid);
if (PEAR::isError($type)) { $type = $media->getType();
echo $type->getMessage(); $gunid = $media->getGunid();
exit;
}
$gunid = BasicStor::GunidFromId($fid);
if (PEAR::isError($gunid)) {
echo $gunid->getMessage();
exit;
}
$pars = array(); $pars = array();
if ($gunid) { if ($gunid) {
$pars['id']="$gunid"; $pars['id']="$gunid";

View File

@ -209,9 +209,9 @@ function camp_import_audio_file($p_filepath, $p_importMode = null, $p_testOnly =
"filepath" => $p_filepath, "filepath" => $p_filepath,
"md5" => $md5sum, "md5" => $md5sum,
); );
$storedFile = $greenbox->bsPutFile($values, $doCopyFiles); $storedFile = StoredFile::Insert($values, $doCopyFiles);
if (PEAR::isError($storedFile)) { if (PEAR::isError($storedFile)) {
import_err($storedFile, "Error in bsPutFile()"); import_err($storedFile, "Error in StoredFile::Insert()");
echo var_export($metadata)."\n"; echo var_export($metadata)."\n";
return; return;
} }

View File

@ -70,7 +70,7 @@ function ls_restore_restoreObject($obj, /*$parid,*/ $reallyInsert=TRUE){
"gunid" => $obj['gunid'], "gunid" => $obj['gunid'],
"filetype" => strtolower($obj['type']) "filetype" => strtolower($obj['type'])
); );
$r = $bs->bsPutFile($values); $r = StoredFile::Insert($values);
ls_restore_checkErr($r, __LINE__); ls_restore_checkErr($r, __LINE__);
} }
break; break;