Fix record_message.py script

This commit is contained in:
Benjamin Renard 2019-06-07 16:12:46 +02:00 committed by root
parent 9939dbd41a
commit 1b83b247df
2 changed files with 39 additions and 23 deletions

View file

@ -41,6 +41,13 @@ def get_var(asterisk_agi, varname):
result = asterisk_agi.get_full_variable(varname)
return result
def get_env_var(asterisk_agi, varname):
if check_simulate_mode():
result = raw_input('Simulate mode : please enter "%s" environnement variable value =>> ' % varname)
else:
result = asterisk_agi.env.get(varname)
return result
def set_var(asterisk_agi, varname, value):
if check_simulate_mode():
print('Simulate mode : set variable %s to "%s"' % (varname, value))
@ -132,4 +139,5 @@ def record_file(asterisk_agi, filepath, fileformat='wav', escape_digits='#', max
except Exception, e:
logging.warning('Fail to record %s file', filepath, exc_info=True)
else:
logging.debug("Record %s file '%s' until user press [%s] key", fileformat, filepath, escape_digits)
return asterisk_agi.record_file(filepath, format=fileformat, escape_digits=escape_digits, timeout=max_duration)

View file

@ -13,16 +13,17 @@ from asterisk import agi
from optparse import OptionParser
from picotts import PicoTTS
from helpers import playback, enable_simulate_mode, get_var, set_var, hangup, check_answered, beep, record_file
from helpers import playback, enable_simulate_mode, get_var, get_env_var, set_var, hangup, check_answered, beep, record_file
default_logfile = '/var/log/asterisk/record_message.agi.log'
default_lang = 'fr-FR'
default_intkey = "any"
default_speed = 1.1
default_cachedir = '/var/cache/asterisk/picotts'
default_outputdir = '/var/lib/asterisk/sounds/records/'
default_outputdir = '/var/lib/asterisk/sounds/records'
default_fileformat = 'wav'
default_nameformat = '{datetime}-{CALLERID(num)}.{fileformat}'
default_nameformat = '{datetime}-{calleridname}'
default_endmessage = u"Au revoir"
#######
# RUN #
@ -114,13 +115,19 @@ parser.add_option('-O', '--output-dir',
parser.add_option('-n', '--name-format',
action="store", type="string",
dest="nameformat", default=default_nameformat,
help="Record file name format composed using channel variables and specials 'date' and 'datetime' and 'fileformat' variables (Default : %s)" % default_outputdir)
help="Record file name format composed using channel variables and some specials variables : 'date', 'datetime', 'callerid', 'calleridname' (Default : %s)" % default_outputdir)
parser.add_option('-m', '--max-duration',
action="store", type="int",
dest="maxduration", default=-1,
help="Max duration (in seconds, Default : no limit)")
parser.add_option('-e', '--end-message',
action="store", type="string",
dest="endmessage", default=default_endmessage,
help="End message that will be read to user at the end (Default : %s)" % default_endmessage)
(options, args) = parser.parse_args()
# Enable logs
@ -158,12 +165,13 @@ logging.debug('Call parameters (lang = {lang}, intkey = {intkey}, speed = {speed
# Functions #
#############
def clean_tmp():
def clean_exit(exit_code):
if 'picotts' in globals():
global picotts
picotts.clean_tmp()
global asterisk_agi
hangup(asterisk_agi)
sys.exit(exit_code)
def play_msg(msg):
global asterisk_agi, options
@ -180,14 +188,12 @@ def play_file(filepath):
playback(asterisk_agi, filepath, simulate_play=options.simulate_play,
intkey=options.intkey)
def play_msg_and_hangup(msg=None):
def play_msg_and_hangup(msg=None, exit_code=1):
global asterisk_agi
if not msg:
msg = u"Une erreur empêche ce service de fonctionner correctement. Si le problème persiste, merci de prendre contact avec le support."
play_msg(msg)
clean_tmp()
hangup(asterisk_agi)
sys.exit(0)
clean_exit(exit_code)
try:
picotts_args = {}
@ -213,14 +219,16 @@ try:
variables = {}
for var in re.findall('\{([^\}]+)\}', options.nameformat):
if var == 'date':
variables['date'] = datetime.datetime.now().strftime('%Y%m%d')
value = datetime.datetime.now().strftime('%Y-%m-%d')
elif var == 'datetime':
variables['datetime'] = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
elif var == 'fileformat':
variables['fileformat'] = options.fileformat
value = datetime.datetime.now().strftime('%Y-%m-%d-%Hh%Mm%Ss')
elif var in ['callerid', 'calleridname']:
value = get_env_var(asterisk_agi, 'agi_%s' % var)
else:
variables[var] = get_var(asterisk_agi, var)
filename = options.nameformat.format(**variables)
value = get_var(asterisk_agi, var)
logging.debug('%s = "%s"', var, value)
variables[var] = value
filename = options.nameformat.format(**variables).replace(' ', '-')
logging.debug(u"Output file name : '%s'", filename)
filepath = "{0}/{1}".format(options.outputdir, filename)
@ -240,16 +248,15 @@ try:
# Intro
play_msg(u"Vous allez pouvoir enregistrer un message après le bip sonore. Une fois votre message enregistré, appuyer sur la touche dièse pour terminer l'enregistrement.")
beep(asterisk_agi)
# Record file
record_file(asterisk_agi, filepath, options.fileformat, escape_digits='#', max_duration=options.maxduration, simulate_record=options.simulate_record)
beep(asterisk_agi)
# Check destination file now exist
if not os.path.exists(filepath):
logging.warning("Output file '%s' does not exists after the record !", filepath)
full_filepath = "{0}.{1}".format(filepath, options.fileformat.lower())
if not os.path.exists(full_filepath):
logging.warning("Output file '%s' does not exists after the record !", full_filepath)
play_msg_and_hangup(u"Une erreur est survenue durant l'enregistrement de votre message. Si le problème persiste, merci de prendre contact avec le support.")
# Replay message to the caller
@ -261,13 +268,14 @@ try:
beep(asterisk_agi)
play_msg_and_hangup(u"Au revoir")
sys.exit(0)
if options.endmessage:
play_msg(options.endmessage)
clean_exit(0)
except agi.AGIAppError:
logging.info('An AGI error stop script', exc_info=True)
play_msg_and_hangup()
except Exception:
logging.error('Unexcepted error occured', exc_info=True)
play_msg_and_hangup()
sys.exit(1)
play_msg_and_hangup(exit_code=1)