Beispiel #1
0
    def parse_grammar(self, element, uri=None):
        Grammar.parse_grammar(self, element, uri)

        # Extract Loop attribute
        loop = int(self.extract_attribute_value("loop"))
        if loop < 0:
            raise RESTFormatException("Play loop must be a positive integer")
        self.loop_times = loop
        # Pull out the text within the element
        audio_path = element.text.strip()

        if audio_path is None:
            raise RESTFormatException("No File for play given!")

        if not is_valid_url(audio_path):
            if file_exists(audio_path):
                self.sound_file_path = audio_path
        else:
            if url_exists(audio_path):
                if audio_path[-4:].lower() != '.mp3':
                    error_msg = "Only mp3 files allowed for remote file play"
                    print error_msg
                if audio_path[:7].lower() == "http://":
                    audio_path = audio_path[7:]
                elif audio_path[:8].lower() == "https://":
                    audio_path = audio_path[8:]
                elif audio_path[:6].lower() == "ftp://":
                    audio_path = audio_path[6:]
                else:
                    pass
                self.sound_file_path = "shout://%s" % audio_path
Beispiel #2
0
    def parse_element(self, element, uri=None):
        Element.parse_element(self, element, uri)
        # Extract Loop attribute
        try:
            loop = int(self.extract_attribute_value("loop", 1))
        except ValueError:
            loop = 1
        if loop < 0:
            raise RESTFormatException("Play 'loop' must be a positive integer or 0")
        self.loop_times = loop
        # Pull out the text within the element
        audio_path = element.text.strip()

        if not audio_path:
            raise RESTFormatException("No File to play set !")

        if not is_valid_url(audio_path):
            if file_exists(audio_path):
                self.sound_file_path = audio_path
        else:
            if url_exists(audio_path):
                if audio_path[-4:].lower() != '.mp3':
                    raise RESTFormatException("Only mp3 files allowed for remote file play")
                if audio_path[:7].lower() == "http://":
                    audio_path = audio_path[7:]
                elif audio_path[:8].lower() == "https://":
                    audio_path = audio_path[8:]
                elif audio_path[:6].lower() == "ftp://":
                    audio_path = audio_path[6:]
                else:
                    pass
                self.sound_file_path = "shout://%s" % audio_path
Beispiel #3
0
    def __init__(self, configfile, daemon=False,
                        pidfile='/tmp/plivo_rest.pid'):
        """Initialize main properties such as daemon, pidfile, config, etc...

        This will init the http server that will provide the Rest interface,
        the rest server is configured on HTTP_ADDRESS

        Extra:
        * FS_INBOUND_ADDRESS : Define the event_socket interface to connect to
        in order to initialize CallSession with Freeswitch

        * FS_OUTBOUND_ADDRESS : Define where on which address listen to
        initialize event_socket session with Freeswitch in order to control
        new CallSession

        """
        self._daemon = daemon
        self._run = False
        self._pidfile = pidfile
        self.configfile = configfile
        self._wsgi_mode = WSGIServer
        self._ssl_cert = None
        self._ssl = False
        # create flask app
        self.app = Flask(self.name)

        # load config
        self._config = None
        self.load_config()

        # create a cache instance if enabled
        self.cache = None
        if self.cache_path:
            if self.redis_host and self.redis_port and self.redis_db:
                self.cache = helpers.ResourceCache(self.cache_path,
                                            self.redis_host,
                                            int(self.redis_port),
                                            int(self.redis_db))

        # create inbound socket instance
        self._rest_inbound_socket = RESTInboundSocket(server=self)
        # expose API functions to flask app
        for path, func_desc in urls.URLS.iteritems():
            func, methods = func_desc
            fn = getattr(self, func.__name__)
            self.app.add_url_rule(path, func.__name__, fn, methods=methods)
        # create WSGI Server
        if self._ssl and self._ssl_cert and helpers.file_exists(self._ssl_cert):
            self._wsgi_mode = PyWSGIServer
            self.log.info("Listening HTTPS")
            self.log.info("Force %s mode with HTTPS" % str(self._wsgi_mode))
            self.http_server = self._wsgi_mode((self.http_host, self.http_port),
                                               self.app, log=self.log, 
                                               certfile=self._ssl_cert)
        else:
            self.log.info("Listening HTTP")
            self.log.info("%s mode set" % str(self._wsgi_mode))
            self.http_server = self._wsgi_mode((self.http_host, self.http_port),
                                               self.app, log=self.log)
    def __init__(self,
                 configfile,
                 daemon=False,
                 pidfile='/tmp/plivo_rest.pid'):
        """Initialize main properties such as daemon, pidfile, config, etc...

        This will init the http server that will provide the Rest interface,
        the rest server is configured on HTTP_ADDRESS

        Extra:
        * FS_INBOUND_ADDRESS : Define the event_socket interface to connect to
        in order to initialize CallSession with Freeswitch

        * FS_OUTBOUND_ADDRESS : Define where on which address listen to
        initialize event_socket session with Freeswitch in order to control
        new CallSession

        """
        self._daemon = daemon
        self._run = False
        self._pidfile = pidfile
        self.configfile = configfile
        self._wsgi_mode = WSGIServer
        self._ssl_cert = None
        self._ssl = False
        # create flask app
        self.app = Flask(self.name)

        # load config
        self._config = None
        self.cache = {}
        self.load_config()

        # create inbound socket instance
        self._rest_inbound_socket = RESTInboundSocket(server=self)
        # expose API functions to flask app
        for path, func_desc in urls.URLS.iteritems():
            func, methods = func_desc
            fn = getattr(self, func.__name__)
            self.app.add_url_rule(path, func.__name__, fn, methods=methods)
        # create WSGI Server
        if self._ssl and self._ssl_cert and helpers.file_exists(
                self._ssl_cert):
            self._wsgi_mode = PyWSGIServer
            self.log.info("Listening HTTPS")
            self.log.info("Force %s mode with HTTPS" % str(self._wsgi_mode))
            self.http_server = self._wsgi_mode(
                (self.http_host, self.http_port),
                self.app,
                log=self.log,
                certfile=self._ssl_cert)
        else:
            self.log.info("Listening HTTP")
            self.log.info("%s mode set" % str(self._wsgi_mode))
            self.http_server = self._wsgi_mode(
                (self.http_host, self.http_port), self.app, log=self.log)
    def __init__(self, configfile, daemon=False,
                        pidfile='/tmp/plivo_wav_rest.pid'):
        """Initialize main properties such as daemon, pidfile, config, etc...

        This will init the http server that will provide the Rest interface,
        the rest server is configured on HTTP_ADDRESS

        """
        self._daemon = daemon
        self._run = False
        self._pidfile = pidfile
        self.configfile = configfile
        self._wsgi_mode = WSGIServer
        self._ssl_cert = None
        self._ssl = False
        # create flask app
        self.app = Flask(self.name)

        # load config
        self._config = None
        self.cache = {}
        self.load_config()

        # expose API functions to flask app
        for path, func_desc in urls.WAV_URLS.iteritems():
            func, methods = func_desc
            fn = getattr(self, func.__name__)
            self.app.add_url_rule(path, func.__name__, fn, methods=methods)
        # create WSGI Server
        if self._ssl and self._ssl_cert and helpers.file_exists(self._ssl_cert):
            self._wsgi_mode = PyWSGIServer
            self.log.info("Listening HTTPS")
            self.log.info("Force %s mode with HTTPS" % str(self._wsgi_mode))
            self.http_server = self._wsgi_mode((self.http_host, self.http_port),
                                               self.app, log=self.log,
                                               certfile=self._ssl_cert)
        else:
            self.log.info("Listening HTTP")
            self.log.info("%s mode set" % str(self._wsgi_mode))
            self.http_server = self._wsgi_mode((self.http_host, self.http_port),
                                               self.app, log=self.log)
Beispiel #6
0
 def _prepare_moh(self):
     mohs = []
     if not self.dial_music:
         return mohs
     for audio_path in self.dial_music.split(','):
         if not is_valid_url(audio_path):
             if file_exists(audio_path):
                 mohs.append(audio_path)
         else:
             if url_exists(audio_path):
                 if audio_path[-4:].lower() != '.mp3':
                     raise RESTFormatException("Only mp3 files allowed for remote file play")
                 if audio_path[:7].lower() == "http://":
                     audio_path = audio_path[7:]
                 elif audio_path[:8].lower() == "https://":
                     audio_path = audio_path[8:]
                 elif audio_path[:6].lower() == "ftp://":
                     audio_path = audio_path[6:]
                 else:
                     pass
                 mohs.append("shout://%s" % audio_path)
     return mohs
    def play_on_call(self, call_uuid="", sounds_list=[], legs="aleg", length=3600, schedule=0, mix=True, loop=False):
        cmds = []
        error_count = 0
        bleg = None

        # set flags
        if loop:
            aflags = "l"
            bflags = "l"
        else:
            aflags = ""
            bflags = ""
        if mix:
            aflags += "m"
            bflags += "mr"
        else:
            bflags += "r"

        if schedule <= 0:
            name = "Call Play"
        else:
            name = "Call SchedulePlay"
        if not call_uuid:
            self.log.error("%s Failed -- Missing CallUUID" % name)
            return False
        if not sounds_list:
            self.log.error("%s Failed -- Missing Sounds" % name)
            return False
        if not legs in ('aleg', 'bleg', 'both'):
            self.log.error("%s Failed -- Invalid legs arg '%s'" % (name, str(legs)))
            return False

        # get sound files
        sounds_to_play = []
        for sound in sounds_list:
            if is_valid_sound_proto(sound):
                sounds_to_play.append(sound)
            elif not is_valid_url(sound):
                if file_exists(sound):
                    sounds_to_play.append(sound)
                else:
                    self.log.warn("%s -- File %s not found" % (name, sound))
            else:
                url = normalize_url_space(sound)
                sound_file_path = get_resource(self, url)
                if sound_file_path:
                    sounds_to_play.append(sound_file_path)
                else:
                    self.log.warn("%s -- Url %s not found" % (name, url))
        if not sounds_to_play:
            self.log.error("%s Failed -- Sound files not found" % name)
            return False

        # build command
        play_str = '!'.join(sounds_to_play)
        play_aleg = 'file_string://%s' % play_str
        play_bleg = 'file_string://silence_stream://1!%s' % play_str

        # aleg case
        if legs == 'aleg':
            # add displace command
            for displace in self._get_displace_media_list(call_uuid):
                cmd = "uuid_displace %s stop %s" % (call_uuid, displace)
                cmds.append(cmd)
            cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_aleg, length, aflags)
            cmds.append(cmd)
        # bleg case
        elif legs  == 'bleg':
            # get bleg
            bleg = self.get_var("bridge_uuid", uuid=call_uuid)
            # add displace command
            if bleg:
                for displace in self._get_displace_media_list(call_uuid):
                    cmd = "uuid_displace %s stop %s" % (call_uuid, displace)
                    cmds.append(cmd)
                cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_bleg, length, bflags)
                cmds.append(cmd)
            else:
                self.log.error("%s Failed -- No BLeg found" % name)
                return False
        # both legs case
        elif legs == 'both':
            # get bleg
            bleg = self.get_var("bridge_uuid", uuid=call_uuid)
            # add displace commands
            for displace in self._get_displace_media_list(call_uuid):
                cmd = "uuid_displace %s stop %s" % (call_uuid, displace)
                cmds.append(cmd)
            cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_aleg, length, aflags)
            cmds.append(cmd)
            # get the bleg
            if bleg:
                cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_bleg, length, bflags)
                cmds.append(cmd)
            else:
                self.log.warn("%s -- No BLeg found" % name)
        else:
            self.log.error("%s Failed -- Invalid Legs '%s'" % (name, legs))
            return False

        # case no schedule
        if schedule <= 0:
            for cmd in cmds:
                res = self.api(cmd)
                if not res.is_success():
                    self.log.error("%s Failed '%s' -- %s" % (name, cmd, res.get_response()))
                    error_count += 1
            if error_count > 0:
                return False
            return True

        # case schedule
        sched_id = str(uuid.uuid1())
        for cmd in cmds:
            sched_cmd = "sched_api +%d %s %s" % (schedule, sched_id, cmd)
            res = self.api(sched_cmd)
            if res.is_success():
                self.log.info("%s '%s' with SchedPlayId %s" % (name, sched_cmd, sched_id))
            else:
                self.log.error("%s Failed '%s' -- %s" % (name, sched_cmd, res.get_response()))
                error_count += 1
        if error_count > 0:
            return False
        return sched_id
    def play_on_call(self, call_uuid="", sounds_list=[], legs="aleg", length=3600, schedule=0, mix=True, loop=False):
        cmds = []
        error_count = 0
        bleg = None

        # set flags
        if loop:
            aflags = "l"
            bflags = "l"
        else:
            aflags = ""
            bflags = ""
        if mix:
            aflags += "m"
            bflags += "mr"
        else:
            bflags += "r"

        if schedule <= 0:
            name = "Call Play"
        else:
            name = "Call SchedulePlay"
        if not call_uuid:
            self.log.error("%s Failed -- Missing CallUUID" % name)
            return False
        if not sounds_list:
            self.log.error("%s Failed -- Missing Sounds" % name)
            return False
        if not legs in ('aleg', 'bleg', 'both'):
            self.log.error("%s Failed -- Invalid legs arg '%s'" % (name, str(legs)))
            return False

        # get sound files
        sounds_to_play = []
        for sound in sounds_list:
            if is_valid_sound_proto(sound):
                sounds_to_play.append(sound)
            elif not is_valid_url(sound):
                if file_exists(sound):
                    sounds_to_play.append(sound)
                else:
                    self.log.warn("%s -- File %s not found" % (name, sound))
            else:
                url = normalize_url_space(sound)
                sound_file_path = get_resource(self, url)
                if sound_file_path:
                    sounds_to_play.append(sound_file_path)
                else:
                    self.log.warn("%s -- Url %s not found" % (name, url))
        if not sounds_to_play:
            self.log.error("%s Failed -- Sound files not found" % name)
            return False

        # build command
        play_str = '!'.join(sounds_to_play)
        play_aleg = 'file_string://%s' % play_str
        play_bleg = 'file_string://silence_stream://1!%s' % play_str

        # aleg case
        if legs == 'aleg':
            # add displace command
            for displace in self._get_displace_media_list(call_uuid):
                cmd = "uuid_displace %s stop %s" % (call_uuid, displace)
                cmds.append(cmd)
            cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_aleg, length, aflags)
            cmds.append(cmd)
        # bleg case
        elif legs  == 'bleg':
            # get bleg
            bleg = self.get_var("bridge_uuid", uuid=call_uuid)
            # add displace command
            if bleg:
                for displace in self._get_displace_media_list(call_uuid):
                    cmd = "uuid_displace %s stop %s" % (call_uuid, displace)
                    cmds.append(cmd)
                cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_bleg, length, bflags)
                cmds.append(cmd)
            else:
                self.log.error("%s Failed -- No BLeg found" % name)
                return False
        # both legs case
        elif legs == 'both':
            # get bleg
            bleg = self.get_var("bridge_uuid", uuid=call_uuid)
            # add displace commands
            for displace in self._get_displace_media_list(call_uuid):
                cmd = "uuid_displace %s stop %s" % (call_uuid, displace)
                cmds.append(cmd)
            cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_aleg, length, aflags)
            cmds.append(cmd)
            # get the bleg
            if bleg:
                cmd = "uuid_displace %s start %s %d %s" % (call_uuid, play_bleg, length, bflags)
                cmds.append(cmd)
            else:
                self.log.warn("%s -- No BLeg found" % name)
        else:
            self.log.error("%s Failed -- Invalid Legs '%s'" % (name, legs))
            return False

        # case no schedule
        if schedule <= 0:
            for cmd in cmds:
                res = self.api(cmd)
                if not res.is_success():
                    self.log.error("%s Failed '%s' -- %s" % (name, cmd, res.get_response()))
                    error_count += 1
            if error_count > 0:
                return False
            return True

        # case schedule
        sched_id = str(uuid.uuid1())
        for cmd in cmds:
            sched_cmd = "sched_api +%d %s %s" % (schedule, sched_id, cmd)
            res = self.api(sched_cmd)
            if res.is_success():
                self.log.info("%s '%s' with SchedPlayId %s" % (name, sched_cmd, sched_id))
            else:
                self.log.error("%s Failed '%s' -- %s" % (name, sched_cmd, res.get_response()))
                error_count += 1
        if error_count > 0:
            return False
        return sched_id