Format code using black
This commit is contained in:
parent
efe4fa027e
commit
c27f020d73
85 changed files with 3238 additions and 2243 deletions
|
@ -9,7 +9,7 @@ import json
|
|||
import shutil
|
||||
import commands
|
||||
|
||||
#sys.path.append('/usr/lib/airtime/media-monitor/mm2/')
|
||||
# sys.path.append('/usr/lib/airtime/media-monitor/mm2/')
|
||||
from mm2.media.monitor.pure import is_file_supported
|
||||
|
||||
# create logger
|
||||
|
@ -22,86 +22,97 @@ logging.disable(50)
|
|||
# add ch to logger
|
||||
logger.addHandler(ch)
|
||||
|
||||
if (os.geteuid() != 0):
|
||||
print 'Must be a root user.'
|
||||
if os.geteuid() != 0:
|
||||
print "Must be a root user."
|
||||
sys.exit()
|
||||
|
||||
# loading config file
|
||||
try:
|
||||
config = ConfigObj('/etc/airtime/airtime.conf')
|
||||
config = ConfigObj("/etc/airtime/airtime.conf")
|
||||
except Exception, e:
|
||||
print('Error loading config file: %s', e)
|
||||
print ("Error loading config file: %s", e)
|
||||
sys.exit()
|
||||
|
||||
api_client = apc.AirtimeApiClient(config)
|
||||
|
||||
#helper functions
|
||||
# helper functions
|
||||
# copy or move files
|
||||
# flag should be 'copy' or 'move'
|
||||
def copy_or_move_files_to(paths, dest, flag):
|
||||
try:
|
||||
for path in paths:
|
||||
if (path[0] == "/" or path[0] == "~"):
|
||||
if path[0] == "/" or path[0] == "~":
|
||||
path = os.path.realpath(path)
|
||||
else:
|
||||
path = currentDir+path
|
||||
path = apc.encode_to(path, 'utf-8')
|
||||
dest = apc.encode_to(dest, 'utf-8')
|
||||
if(os.path.exists(path)):
|
||||
if(os.path.isdir(path)):
|
||||
path = currentDir + path
|
||||
path = apc.encode_to(path, "utf-8")
|
||||
dest = apc.encode_to(dest, "utf-8")
|
||||
if os.path.exists(path):
|
||||
if os.path.isdir(path):
|
||||
path = format_dir_string(path)
|
||||
#construct full path
|
||||
# construct full path
|
||||
sub_path = []
|
||||
for temp in os.listdir(path):
|
||||
sub_path.append(path+temp)
|
||||
sub_path.append(path + temp)
|
||||
copy_or_move_files_to(sub_path, dest, flag)
|
||||
elif(os.path.isfile(path)):
|
||||
#copy file to dest
|
||||
if(is_file_supported(path)):
|
||||
destfile = dest+os.path.basename(path)
|
||||
if(flag == 'copy'):
|
||||
print "Copying %(src)s to %(dest)s..." % {'src':path, 'dest':destfile}
|
||||
elif os.path.isfile(path):
|
||||
# copy file to dest
|
||||
if is_file_supported(path):
|
||||
destfile = dest + os.path.basename(path)
|
||||
if flag == "copy":
|
||||
print "Copying %(src)s to %(dest)s..." % {
|
||||
"src": path,
|
||||
"dest": destfile,
|
||||
}
|
||||
shutil.copyfile(path, destfile)
|
||||
elif(flag == 'move'):
|
||||
print "Moving %(src)s to %(dest)s..." % {'src':path, 'dest':destfile}
|
||||
elif flag == "move":
|
||||
print "Moving %(src)s to %(dest)s..." % {
|
||||
"src": path,
|
||||
"dest": destfile,
|
||||
}
|
||||
shutil.move(path, destfile)
|
||||
else:
|
||||
print "Cannot find file or path: %s" % path
|
||||
except Exception as e:
|
||||
print "Error: ", e
|
||||
print "Error: ", e
|
||||
|
||||
|
||||
def format_dir_string(path):
|
||||
if(path[-1] != '/'):
|
||||
path = path+'/'
|
||||
if path[-1] != "/":
|
||||
path = path + "/"
|
||||
return path
|
||||
|
||||
|
||||
def helper_get_stor_dir():
|
||||
try:
|
||||
res = api_client.list_all_watched_dirs()
|
||||
except Exception, e:
|
||||
return res
|
||||
|
||||
if(res['dirs']['1'][-1] != '/'):
|
||||
out = res['dirs']['1']+'/'
|
||||
if res["dirs"]["1"][-1] != "/":
|
||||
out = res["dirs"]["1"] + "/"
|
||||
return out
|
||||
else:
|
||||
return res['dirs']['1']
|
||||
return res["dirs"]["1"]
|
||||
|
||||
|
||||
def checkOtherOption(args):
|
||||
for i in args:
|
||||
if(i[0] == '-'):
|
||||
if i[0] == "-":
|
||||
return True
|
||||
|
||||
def errorIfMultipleOption(args, msg=''):
|
||||
if(checkOtherOption(args)):
|
||||
if(msg != ''):
|
||||
|
||||
def errorIfMultipleOption(args, msg=""):
|
||||
if checkOtherOption(args):
|
||||
if msg != "":
|
||||
raise OptionValueError(msg)
|
||||
else:
|
||||
raise OptionValueError("This option cannot be combined with other options")
|
||||
|
||||
|
||||
def printHelp():
|
||||
storage_dir = helper_get_stor_dir()
|
||||
if(storage_dir is None):
|
||||
if storage_dir is None:
|
||||
storage_dir = "Unknown"
|
||||
else:
|
||||
storage_dir += "imported/"
|
||||
|
@ -129,58 +140,70 @@ There are two ways to import audio files into Airtime:
|
|||
parser.print_help()
|
||||
print ""
|
||||
|
||||
|
||||
def CopyAction(option, opt, value, parser):
|
||||
errorIfMultipleOption(parser.rargs)
|
||||
if(len(parser.rargs) == 0 ):
|
||||
raise OptionValueError("No argument found. This option requires at least one argument.")
|
||||
if len(parser.rargs) == 0:
|
||||
raise OptionValueError(
|
||||
"No argument found. This option requires at least one argument."
|
||||
)
|
||||
stor = helper_get_stor_dir()
|
||||
if(stor is None):
|
||||
if stor is None:
|
||||
print "Unable to connect to the Airtime server."
|
||||
return
|
||||
dest = stor+"organize/"
|
||||
copy_or_move_files_to(parser.rargs, dest, 'copy')
|
||||
dest = stor + "organize/"
|
||||
copy_or_move_files_to(parser.rargs, dest, "copy")
|
||||
|
||||
|
||||
def MoveAction(option, opt, value, parser):
|
||||
errorIfMultipleOption(parser.rargs)
|
||||
if(len(parser.rargs) == 0 ):
|
||||
raise OptionValueError("No argument found. This option requires at least one argument.")
|
||||
if len(parser.rargs) == 0:
|
||||
raise OptionValueError(
|
||||
"No argument found. This option requires at least one argument."
|
||||
)
|
||||
stor = helper_get_stor_dir()
|
||||
if(stor is None):
|
||||
if stor is None:
|
||||
exit("Unable to connect to the Airtime server.")
|
||||
dest = stor+"organize/"
|
||||
copy_or_move_files_to(parser.rargs, dest, 'move')
|
||||
dest = stor + "organize/"
|
||||
copy_or_move_files_to(parser.rargs, dest, "move")
|
||||
|
||||
|
||||
def WatchAddAction(option, opt, value, parser):
|
||||
errorIfMultipleOption(parser.rargs)
|
||||
if(len(parser.rargs) > 1):
|
||||
raise OptionValueError("Too many arguments. This option requires exactly one argument.")
|
||||
elif(len(parser.rargs) == 0 ):
|
||||
raise OptionValueError("No argument found. This option requires exactly one argument.")
|
||||
if len(parser.rargs) > 1:
|
||||
raise OptionValueError(
|
||||
"Too many arguments. This option requires exactly one argument."
|
||||
)
|
||||
elif len(parser.rargs) == 0:
|
||||
raise OptionValueError(
|
||||
"No argument found. This option requires exactly one argument."
|
||||
)
|
||||
path = parser.rargs[0]
|
||||
if (path[0] == "/" or path[0] == "~"):
|
||||
if path[0] == "/" or path[0] == "~":
|
||||
path = os.path.realpath(path)
|
||||
else:
|
||||
path = currentDir+path
|
||||
path = apc.encode_to(path, 'utf-8')
|
||||
if(os.path.isdir(path)):
|
||||
#os.chmod(path, 0765)
|
||||
path = currentDir + path
|
||||
path = apc.encode_to(path, "utf-8")
|
||||
if os.path.isdir(path):
|
||||
# os.chmod(path, 0765)
|
||||
try:
|
||||
res = api_client.add_watched_dir(path)
|
||||
except Exception, e:
|
||||
exit("Unable to connect to the server.")
|
||||
# success
|
||||
if(res['msg']['code'] == 0):
|
||||
if res["msg"]["code"] == 0:
|
||||
print "%s added to watched folder list successfully" % path
|
||||
else:
|
||||
print "Adding a watched folder failed: %s" % res['msg']['error']
|
||||
print "Adding a watched folder failed: %s" % res["msg"]["error"]
|
||||
print "This error most likely caused by wrong permissions"
|
||||
print "Try fixing this error by chmodding the parent directory(ies)"
|
||||
else:
|
||||
print "Given path is not a directory: %s" % path
|
||||
|
||||
|
||||
def WatchListAction(option, opt, value, parser):
|
||||
errorIfMultipleOption(parser.rargs)
|
||||
if(len(parser.rargs) > 0):
|
||||
if len(parser.rargs) > 0:
|
||||
raise OptionValueError("This option doesn't take any arguments.")
|
||||
try:
|
||||
res = api_client.list_all_watched_dirs()
|
||||
|
@ -188,120 +211,184 @@ def WatchListAction(option, opt, value, parser):
|
|||
exit("Unable to connect to the Airtime server.")
|
||||
dirs = res["dirs"].items()
|
||||
# there will be always 1 which is storage folder
|
||||
if(len(dirs) == 1):
|
||||
print "No watch folders found"
|
||||
if len(dirs) == 1:
|
||||
print "No watch folders found"
|
||||
else:
|
||||
for key, v in dirs:
|
||||
if(key != '1'):
|
||||
if key != "1":
|
||||
print v
|
||||
|
||||
|
||||
def WatchRemoveAction(option, opt, value, parser):
|
||||
errorIfMultipleOption(parser.rargs)
|
||||
if(len(parser.rargs) > 1):
|
||||
raise OptionValueError("Too many arguments. This option requires exactly one argument.")
|
||||
elif(len(parser.rargs) == 0 ):
|
||||
raise OptionValueError("No argument found. This option requires exactly one argument.")
|
||||
if len(parser.rargs) > 1:
|
||||
raise OptionValueError(
|
||||
"Too many arguments. This option requires exactly one argument."
|
||||
)
|
||||
elif len(parser.rargs) == 0:
|
||||
raise OptionValueError(
|
||||
"No argument found. This option requires exactly one argument."
|
||||
)
|
||||
path = parser.rargs[0]
|
||||
if (path[0] == "/" or path[0] == "~"):
|
||||
if path[0] == "/" or path[0] == "~":
|
||||
path = os.path.realpath(path)
|
||||
else:
|
||||
path = currentDir+path
|
||||
path = apc.encode_to(path, 'utf-8')
|
||||
if(os.path.isdir(path)):
|
||||
path = currentDir + path
|
||||
path = apc.encode_to(path, "utf-8")
|
||||
if os.path.isdir(path):
|
||||
try:
|
||||
res = api_client.remove_watched_dir(path)
|
||||
except Exception, e:
|
||||
exit("Unable to connect to the Airtime server.")
|
||||
# success
|
||||
if(res['msg']['code'] == 0):
|
||||
if res["msg"]["code"] == 0:
|
||||
print "%s removed from watch folder list successfully." % path
|
||||
else:
|
||||
print "Removing the watch folder failed: %s" % res['msg']['error']
|
||||
print "Removing the watch folder failed: %s" % res["msg"]["error"]
|
||||
else:
|
||||
print "The given path is not a directory: %s" % path
|
||||
|
||||
|
||||
def StorageSetAction(option, opt, value, parser):
|
||||
bypass = False
|
||||
isF = '-f' in parser.rargs
|
||||
isForce = '--force' in parser.rargs
|
||||
if(isF or isForce ):
|
||||
isF = "-f" in parser.rargs
|
||||
isForce = "--force" in parser.rargs
|
||||
if isF or isForce:
|
||||
bypass = True
|
||||
if(isF):
|
||||
parser.rargs.remove('-f')
|
||||
if(isForce):
|
||||
parser.rargs.remove('--force')
|
||||
if(not bypass):
|
||||
errorIfMultipleOption(parser.rargs, "Only [-f] and [--force] option is allowed with this option.")
|
||||
possibleInput = ['y','Y','n','N']
|
||||
confirm = raw_input("Are you sure you want to change the storage directory? (y/N)")
|
||||
confirm = confirm or 'N'
|
||||
while(confirm not in possibleInput):
|
||||
if isF:
|
||||
parser.rargs.remove("-f")
|
||||
if isForce:
|
||||
parser.rargs.remove("--force")
|
||||
if not bypass:
|
||||
errorIfMultipleOption(
|
||||
parser.rargs, "Only [-f] and [--force] option is allowed with this option."
|
||||
)
|
||||
possibleInput = ["y", "Y", "n", "N"]
|
||||
confirm = raw_input(
|
||||
"Are you sure you want to change the storage directory? (y/N)"
|
||||
)
|
||||
confirm = confirm or "N"
|
||||
while confirm not in possibleInput:
|
||||
print "Not an acceptable input: %s\n" % confirm
|
||||
confirm = raw_input("Are you sure you want to change the storage directory? (y/N) ")
|
||||
confirm = confirm or 'N'
|
||||
if(confirm == 'n' or confirm =='N'):
|
||||
confirm = raw_input(
|
||||
"Are you sure you want to change the storage directory? (y/N) "
|
||||
)
|
||||
confirm = confirm or "N"
|
||||
if confirm == "n" or confirm == "N":
|
||||
sys.exit(1)
|
||||
|
||||
if(len(parser.rargs) > 1):
|
||||
raise OptionValueError("Too many arguments. This option requires exactly one argument.")
|
||||
elif(len(parser.rargs) == 0 ):
|
||||
raise OptionValueError("No argument found. This option requires exactly one argument.")
|
||||
if len(parser.rargs) > 1:
|
||||
raise OptionValueError(
|
||||
"Too many arguments. This option requires exactly one argument."
|
||||
)
|
||||
elif len(parser.rargs) == 0:
|
||||
raise OptionValueError(
|
||||
"No argument found. This option requires exactly one argument."
|
||||
)
|
||||
|
||||
path = parser.rargs[0]
|
||||
if (path[0] == "/" or path[0] == "~"):
|
||||
if path[0] == "/" or path[0] == "~":
|
||||
path = os.path.realpath(path)
|
||||
else:
|
||||
path = currentDir+path
|
||||
path = apc.encode_to(path, 'utf-8')
|
||||
if(os.path.isdir(path)):
|
||||
path = currentDir + path
|
||||
path = apc.encode_to(path, "utf-8")
|
||||
if os.path.isdir(path):
|
||||
try:
|
||||
res = api_client.set_storage_dir(path)
|
||||
except Exception, e:
|
||||
exit("Unable to connect to the Airtime server.")
|
||||
# success
|
||||
if(res['msg']['code'] == 0):
|
||||
if res["msg"]["code"] == 0:
|
||||
print "Successfully set storage folder to %s" % path
|
||||
else:
|
||||
print "Setting storage folder failed: %s" % res['msg']['error']
|
||||
print "Setting storage folder failed: %s" % res["msg"]["error"]
|
||||
else:
|
||||
print "The given path is not a directory: %s" % path
|
||||
|
||||
|
||||
def StorageGetAction(option, opt, value, parser):
|
||||
errorIfMultipleOption(parser.rargs)
|
||||
if(len(parser.rargs) > 0):
|
||||
if len(parser.rargs) > 0:
|
||||
raise OptionValueError("This option does not take any arguments.")
|
||||
print helper_get_stor_dir()
|
||||
|
||||
|
||||
class OptionValueError(RuntimeError):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
|
||||
usage = """[-c|--copy FILE/DIR [FILE/DIR...]] [-m|--move FILE/DIR [FILE/DIR...]]
|
||||
[--watch-add DIR] [--watch-list] [--watch-remove DIR]
|
||||
[--storage-dir-set DIR] [--storage-dir-get]"""
|
||||
|
||||
parser = OptionParser(usage=usage, add_help_option=False)
|
||||
parser.add_option('-c','--copy', action='callback', callback=CopyAction, metavar='FILE', help='Copy FILE(s) into the storage directory.\nYou can specify multiple files or directories.')
|
||||
parser.add_option('-m','--move', action='callback', callback=MoveAction, metavar='FILE', help='Move FILE(s) into the storage directory.\nYou can specify multiple files or directories.')
|
||||
parser.add_option('--watch-add', action='callback', callback=WatchAddAction, help='Add DIR to the watched folders list.')
|
||||
parser.add_option('--watch-list', action='callback', callback=WatchListAction, help='Show the list of folders that are watched.')
|
||||
parser.add_option('--watch-remove', action='callback', callback=WatchRemoveAction, help='Remove DIR from the watched folders list.')
|
||||
parser.add_option('--storage-dir-set', action='callback', callback=StorageSetAction, help='Set storage dir to DIR.')
|
||||
parser.add_option('--storage-dir-get', action='callback', callback=StorageGetAction, help='Show the current storage dir.')
|
||||
parser.add_option('-h', '--help', dest='help', action='store_true', help='show this help message and exit')
|
||||
parser.add_option(
|
||||
"-c",
|
||||
"--copy",
|
||||
action="callback",
|
||||
callback=CopyAction,
|
||||
metavar="FILE",
|
||||
help="Copy FILE(s) into the storage directory.\nYou can specify multiple files or directories.",
|
||||
)
|
||||
parser.add_option(
|
||||
"-m",
|
||||
"--move",
|
||||
action="callback",
|
||||
callback=MoveAction,
|
||||
metavar="FILE",
|
||||
help="Move FILE(s) into the storage directory.\nYou can specify multiple files or directories.",
|
||||
)
|
||||
parser.add_option(
|
||||
"--watch-add",
|
||||
action="callback",
|
||||
callback=WatchAddAction,
|
||||
help="Add DIR to the watched folders list.",
|
||||
)
|
||||
parser.add_option(
|
||||
"--watch-list",
|
||||
action="callback",
|
||||
callback=WatchListAction,
|
||||
help="Show the list of folders that are watched.",
|
||||
)
|
||||
parser.add_option(
|
||||
"--watch-remove",
|
||||
action="callback",
|
||||
callback=WatchRemoveAction,
|
||||
help="Remove DIR from the watched folders list.",
|
||||
)
|
||||
parser.add_option(
|
||||
"--storage-dir-set",
|
||||
action="callback",
|
||||
callback=StorageSetAction,
|
||||
help="Set storage dir to DIR.",
|
||||
)
|
||||
parser.add_option(
|
||||
"--storage-dir-get",
|
||||
action="callback",
|
||||
callback=StorageGetAction,
|
||||
help="Show the current storage dir.",
|
||||
)
|
||||
parser.add_option(
|
||||
"-h",
|
||||
"--help",
|
||||
dest="help",
|
||||
action="store_true",
|
||||
help="show this help message and exit",
|
||||
)
|
||||
|
||||
# pop "--dir"
|
||||
#sys.argv.pop(1)
|
||||
# sys.argv.pop(1)
|
||||
# pop "invoked pwd"
|
||||
currentDir = os.getcwd() #sys.argv.pop(1)+'/'
|
||||
currentDir = os.getcwd() # sys.argv.pop(1)+'/'
|
||||
|
||||
if('-l' in sys.argv or '--link' in sys.argv):
|
||||
if "-l" in sys.argv or "--link" in sys.argv:
|
||||
print "\nThe [-l][--link] option is deprecated. Please use the --watch-add option.\nTry 'airtime-import -h' for more detail.\n"
|
||||
sys.exit()
|
||||
if('-h' in sys.argv):
|
||||
if "-h" in sys.argv:
|
||||
printHelp()
|
||||
sys.exit()
|
||||
if(len(sys.argv) == 1 or '-' not in sys.argv[1]):
|
||||
if len(sys.argv) == 1 or "-" not in sys.argv[1]:
|
||||
printHelp()
|
||||
sys.exit()
|
||||
|
||||
|
@ -309,10 +396,10 @@ try:
|
|||
(option, args) = parser.parse_args()
|
||||
except Exception, e:
|
||||
printHelp()
|
||||
if hasattr(e, 'msg'):
|
||||
print "Error: "+e.msg
|
||||
if hasattr(e, "msg"):
|
||||
print "Error: " + e.msg
|
||||
else:
|
||||
print "Error: ",e
|
||||
print "Error: ", e
|
||||
sys.exit()
|
||||
except SystemExit:
|
||||
printHelp()
|
||||
|
@ -321,7 +408,3 @@ except SystemExit:
|
|||
if option.help:
|
||||
printHelp()
|
||||
sys.exit()
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -21,14 +21,14 @@ logging.disable(50)
|
|||
logger.addHandler(ch)
|
||||
|
||||
if os.geteuid() != 0:
|
||||
print 'Must be a root user.'
|
||||
print "Must be a root user."
|
||||
sys.exit(1)
|
||||
|
||||
# loading config file
|
||||
try:
|
||||
config = ConfigObj('/etc/airtime/airtime.conf')
|
||||
config = ConfigObj("/etc/airtime/airtime.conf")
|
||||
except Exception, e:
|
||||
print('Error loading config file: %s', e)
|
||||
print ("Error loading config file: %s", e)
|
||||
sys.exit(1)
|
||||
|
||||
api_client = apc.AirtimeApiClient(config)
|
||||
|
@ -43,25 +43,29 @@ try:
|
|||
# filepath
|
||||
files = api_client.get_files_without_silan_value()
|
||||
total_files = len(files)
|
||||
if total_files == 0: break
|
||||
if total_files == 0:
|
||||
break
|
||||
processed_data = []
|
||||
total = 0
|
||||
for f in files:
|
||||
full_path = f['fp']
|
||||
full_path = f["fp"]
|
||||
# silence detect(set default queue in and out)
|
||||
try:
|
||||
command = ['silan', '-b' '-f', 'JSON', full_path]
|
||||
command = ["silan", "-b" "-f", "JSON", full_path]
|
||||
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
|
||||
out = proc.communicate()[0].strip('\r\n')
|
||||
out = proc.communicate()[0].strip("\r\n")
|
||||
info = json.loads(out)
|
||||
data = {}
|
||||
data['cuein'] = str('{0:f}'.format(info['sound'][0][0]))
|
||||
data['cueout'] = str('{0:f}'.format(info['sound'][-1][1]))
|
||||
data['length'] = str('{0:f}'.format(info['file duration']))
|
||||
processed_data.append((f['id'], data))
|
||||
data["cuein"] = str("{0:f}".format(info["sound"][0][0]))
|
||||
data["cueout"] = str("{0:f}".format(info["sound"][-1][1]))
|
||||
data["length"] = str("{0:f}".format(info["file duration"]))
|
||||
processed_data.append((f["id"], data))
|
||||
total += 1
|
||||
if total % 5 == 0:
|
||||
print "Total %s / %s files has been processed.." % (total, total_files)
|
||||
print "Total %s / %s files has been processed.." % (
|
||||
total,
|
||||
total_files,
|
||||
)
|
||||
except Exception, e:
|
||||
print e
|
||||
print traceback.format_exc()
|
||||
|
@ -70,7 +74,7 @@ try:
|
|||
|
||||
try:
|
||||
print api_client.update_cue_values_by_silan(processed_data)
|
||||
except Exception ,e:
|
||||
except Exception, e:
|
||||
print e
|
||||
print traceback.format_exc()
|
||||
print "Total %d songs Processed" % subtotal
|
||||
|
|
|
@ -16,32 +16,35 @@ if os.geteuid() == 0:
|
|||
print "Please run this program as non-root"
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def printUsage():
|
||||
print "airtime-test-soundcard [-v] [-o alsa | ao | oss | portaudio | pulseaudio ] [-h]"
|
||||
print " Where: "
|
||||
print " -v verbose mode"
|
||||
print " -o Linux Sound API (default: alsa)"
|
||||
print " -h show help menu "
|
||||
|
||||
|
||||
|
||||
def find_liquidsoap_binary():
|
||||
"""
|
||||
Starting with Airtime 2.0, we don't know the exact location of the Liquidsoap
|
||||
binary because it may have been installed through a debian package. Let's find
|
||||
the location of this binary.
|
||||
"""
|
||||
|
||||
|
||||
rv = subprocess.call("which airtime-liquidsoap > /dev/null", shell=True)
|
||||
if rv == 0:
|
||||
return "airtime-liquidsoap"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
try:
|
||||
optlist, args = getopt.getopt(sys.argv[1:], 'hvo:')
|
||||
optlist, args = getopt.getopt(sys.argv[1:], "hvo:")
|
||||
except getopt.GetoptError, g:
|
||||
printUsage()
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
sound_api_types = set(["alsa", "ao", "oss", "portaudio", "pulseaudio"])
|
||||
|
||||
verbose = False
|
||||
|
@ -63,26 +66,25 @@ for o, a in optlist:
|
|||
try:
|
||||
print "Sound API: %s" % sound_api
|
||||
print "Outputting to soundcard. You should be able to hear a monotonous tone. Press ctrl-c to quit."
|
||||
|
||||
|
||||
liquidsoap_exe = find_liquidsoap_binary()
|
||||
|
||||
|
||||
if liquidsoap_exe is None:
|
||||
raise Exception("Liquidsoap not found!")
|
||||
|
||||
|
||||
command = "%s 'output.%s(sine())'" % (liquidsoap_exe, sound_api)
|
||||
|
||||
|
||||
if not verbose:
|
||||
command += " > /dev/null"
|
||||
|
||||
#print command
|
||||
|
||||
# print command
|
||||
rv = subprocess.call(command, shell=True)
|
||||
|
||||
#if we reach this point, it means that our subprocess exited without the user
|
||||
#doing a keyboard interrupt. This means there was a problem outputting to the
|
||||
#soundcard. Print appropriate message.
|
||||
print "There was an error using the selected sound API. Please select a different API " + \
|
||||
"and run this program again. Use the -h option for help"
|
||||
|
||||
|
||||
# if we reach this point, it means that our subprocess exited without the user
|
||||
# doing a keyboard interrupt. This means there was a problem outputting to the
|
||||
# soundcard. Print appropriate message.
|
||||
print "There was an error using the selected sound API. Please select a different API " + "and run this program again. Use the -h option for help"
|
||||
|
||||
except KeyboardInterrupt, ki:
|
||||
print "\nExiting"
|
||||
except Exception, e:
|
||||
|
|
|
@ -16,6 +16,7 @@ if os.geteuid() == 0:
|
|||
print "Please run this program as non-root"
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def printUsage():
|
||||
print "airtime-test-stream [-v] [-o icecast | shoutcast ] [-H hostname] [-P port] [-u username] [-p password] [-m mount]"
|
||||
print " Where: "
|
||||
|
@ -42,7 +43,8 @@ def find_liquidsoap_binary():
|
|||
|
||||
return None
|
||||
|
||||
optlist, args = getopt.getopt(sys.argv[1:], 'hvo:H:P:u:p:m:')
|
||||
|
||||
optlist, args = getopt.getopt(sys.argv[1:], "hvo:H:P:u:p:m:")
|
||||
stream_types = set(["shoutcast", "icecast"])
|
||||
|
||||
verbose = False
|
||||
|
@ -89,31 +91,38 @@ try:
|
|||
print "Mount: %s\n" % mount
|
||||
|
||||
url = "http://%s:%s/%s" % (host, port, mount)
|
||||
print "Outputting to %s streaming server. You should be able to hear a monotonous tone on '%s'. Press ctrl-c to quit." % (stream_type, url)
|
||||
print "Outputting to %s streaming server. You should be able to hear a monotonous tone on '%s'. Press ctrl-c to quit." % (
|
||||
stream_type,
|
||||
url,
|
||||
)
|
||||
|
||||
liquidsoap_exe = find_liquidsoap_binary()
|
||||
if liquidsoap_exe is None:
|
||||
raise Exception("Liquidsoap not found!")
|
||||
|
||||
if stream_type == "icecast":
|
||||
command = "%s 'output.icecast(%%vorbis, host = \"%s\", port = %s, user= \"%s\", password = \"%s\", mount=\"%s\", sine())'" % (liquidsoap_exe, host, port, user, password, mount)
|
||||
command = (
|
||||
'%s \'output.icecast(%%vorbis, host = "%s", port = %s, user= "%s", password = "%s", mount="%s", sine())\''
|
||||
% (liquidsoap_exe, host, port, user, password, mount)
|
||||
)
|
||||
else:
|
||||
command = "%s 'output.shoutcast(%%mp3, host=\"%s\", port = %s, user= \"%s\", password = \"%s\", sine())'" \
|
||||
% (liquidsoap_exe, host, port, user, password)
|
||||
command = (
|
||||
'%s \'output.shoutcast(%%mp3, host="%s", port = %s, user= "%s", password = "%s", sine())\''
|
||||
% (liquidsoap_exe, host, port, user, password)
|
||||
)
|
||||
|
||||
if not verbose:
|
||||
command += " 2>/dev/null | grep \"failed\""
|
||||
command += ' 2>/dev/null | grep "failed"'
|
||||
else:
|
||||
print command
|
||||
|
||||
#print command
|
||||
# print command
|
||||
rv = subprocess.call(command, shell=True)
|
||||
|
||||
#if we reach this point, it means that our subprocess exited without the user
|
||||
#doing a keyboard interrupt. This means there was a problem outputting to the
|
||||
#stream server. Print appropriate message.
|
||||
print "There was an error with your stream configuration. Please review your configuration " + \
|
||||
"and run this program again. Use the -h option for help"
|
||||
# if we reach this point, it means that our subprocess exited without the user
|
||||
# doing a keyboard interrupt. This means there was a problem outputting to the
|
||||
# stream server. Print appropriate message.
|
||||
print "There was an error with your stream configuration. Please review your configuration " + "and run this program again. Use the -h option for help"
|
||||
|
||||
except KeyboardInterrupt, ki:
|
||||
print "\nExiting"
|
||||
|
|
|
@ -7,39 +7,45 @@ import requests
|
|||
from urlparse import urlparse
|
||||
import sys
|
||||
|
||||
CONFIG_PATH='/etc/airtime/airtime.conf'
|
||||
CONFIG_PATH = "/etc/airtime/airtime.conf"
|
||||
GENERAL_CONFIG_SECTION = "general"
|
||||
|
||||
|
||||
def read_config_file(config_path):
|
||||
"""Parse the application's config file located at config_path."""
|
||||
config = ConfigParser.SafeConfigParser()
|
||||
try:
|
||||
config.readfp(open(config_path))
|
||||
except IOError as e:
|
||||
print "Failed to open config file at " + config_path + ": " + e.strerror
|
||||
print "Failed to open config file at " + config_path + ": " + e.strerror
|
||||
exit(-1)
|
||||
except Exception:
|
||||
print e.strerror
|
||||
print e.strerror
|
||||
exit(-1)
|
||||
|
||||
return config
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = read_config_file(CONFIG_PATH)
|
||||
api_key = config.get(GENERAL_CONFIG_SECTION, 'api_key')
|
||||
base_url = config.get(GENERAL_CONFIG_SECTION, 'base_url')
|
||||
base_dir = config.get(GENERAL_CONFIG_SECTION, 'base_dir')
|
||||
base_port = config.get(GENERAL_CONFIG_SECTION, 'base_port', 80)
|
||||
api_key = config.get(GENERAL_CONFIG_SECTION, "api_key")
|
||||
base_url = config.get(GENERAL_CONFIG_SECTION, "base_url")
|
||||
base_dir = config.get(GENERAL_CONFIG_SECTION, "base_dir")
|
||||
base_port = config.get(GENERAL_CONFIG_SECTION, "base_port", 80)
|
||||
action = "upgrade"
|
||||
station_url = ""
|
||||
|
||||
default_url = "http://%s:%s%s" % (base_url, base_port, base_dir)
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--downgrade', help='Downgrade the station', action="store_true")
|
||||
parser.add_argument('station_url', help='station URL', nargs='?', default=default_url)
|
||||
parser.add_argument(
|
||||
"--downgrade", help="Downgrade the station", action="store_true"
|
||||
)
|
||||
parser.add_argument(
|
||||
"station_url", help="station URL", nargs="?", default=default_url
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
if args.downgrade:
|
||||
action = "downgrade"
|
||||
|
||||
|
@ -47,12 +53,11 @@ if __name__ == '__main__':
|
|||
station_url = args.station_url
|
||||
|
||||
# Add http:// if you were lazy and didn't pass a scheme to this script
|
||||
url = urlparse(station_url)
|
||||
url = urlparse(station_url)
|
||||
if not url.scheme:
|
||||
station_url = "http://%s" % station_url
|
||||
|
||||
print "Requesting %s..." % action
|
||||
r = requests.get("%s/%s" % (station_url, action), auth=(api_key, ''))
|
||||
r = requests.get("%s/%s" % (station_url, action), auth=(api_key, ""))
|
||||
print r.text
|
||||
r.raise_for_status()
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue