Esempio n. 1
0
    def __init__(self, script_id, tas_request):
        self.__script_id = script_id
        self.__tas_info = tas_request
        self.__action_id = None

        self.__play_id = None
        self.__say_id = None
        self.__collect_id = None

        self.__session_id = session_context.__generate_session_id()

        self.__cursor = 0
        self.__variables = {}

        block = script.load(script_id)
        self.__actions = block.get_commands()
        self.__triggers = block.get_triggers()
        self.__functions = block.get_functions()

        self.__last_input_message = None

        if (len(self.__actions) == 0):
            logging.warning(
                "Script-file (script id: '%s') does not have any actions for TAS.",
                script_id)

        logging.debug(
            "IVR context is generated (session id: '%s', script id: '%s').",
            self.__session_id, self.__script_id)
        logging.debug(
            "IVR script '%s' info (commands: '%d', triggers: '%d', functions: '%d').",
            self.__script_id, len(self.__actions), len(self.__triggers),
            len(self.__functions))
Esempio n. 2
0
    def exist(session_id):
        with session_manager.__resource_locker:
            logging.debug("Amount of sessions '%d' (search session id '%s').",
                          len(session_manager.__sessions), session_id)

            if (session_id in session_manager.__sessions):
                return True

        return False
Esempio n. 3
0
    def notify(session_id, tas_notification_id, message_payload):
        with session_manager.__resource_locker:
            if (session_manager.exist(session_id)):
                logging.debug(
                    "Convey notifiction to session instance (session id: '%s', sessions '%d').",
                    session_id, len(session_manager.__sessions))

                return session_manager.__sessions[session_id].notify(
                    tas_notification_id, message_payload)

        return None
Esempio n. 4
0
    def delete(session_id, internal=False):
        reply_code = None
        with session_manager.__resource_locker:
            if (internal is False):
                reply_code = session_manager.__sessions[session_id].stop()

            if (session_manager.exist(session_id)):
                session_manager.__sessions.pop(session_id)
                logging.debug(
                    "Delete session instance (session id: '%s', sessions '%d').",
                    session_id, len(session_manager.__sessions))

        return reply_code
Esempio n. 5
0
    def send_request(self, http_method, http_link, json_request):
        response_status = 404
        response_body = None

        connection = httplib.HTTPConnection(self.__address,
                                            self.__port,
                                            timeout=1)

        try:
            logging.debug("Send HTTP request to TAS (%s:%s): '%s' '%s'.",
                          self.__address, self.__port, http_method, http_link)
            logging.debug("JSON payload of the HTTP request to TAS: '%s'.",
                          json_request)

            headers = {
                'Content-Type': 'application/json'
            }

            body = None
            if (json_request is not None):
                body = json_request.encode("utf-8")
                headers['Content-Length'] = len(body)

            statistical.inc_ivr_requests()
            connection.request(http_method, http_link, body, headers)

            logging.debug("Check for HTTP response from TAS.")
            response = connection.getresponse()
            response_status = response.status

            logging.debug("Read body of the HTTP response from TAS.")
            response_body = response.read()

            statistical.inc_ivr_responses()
            logging.debug("HTTP response (code: %d) from TAS:\n%s",
                          response_status, response_body)

        except:
            response_status = 404
            logging.error(
                "Impossible to communicate correctly with TAS using HTTP.")

        finally:
            connection.close()

        return (response_status, response_body)
Esempio n. 6
0
    def __process_wait_command(self, expected_response):
        logging.debug("(IVR session '%s') wait for TAS callback command (response: '%s')...", self.__context.get_id(), expected_response);
        
        while(self.__active is True):
            response = "";
            
            with self.__tas_response_condition:
                while (len(self.__tas_responses) == 0 and self.__active is True):
                    self.__tas_response_condition.wait();

                if (len(self.__tas_responses) > 0):
                    response = self.__tas_responses.pop();
            
            if (response != expected_response):
                logging.warning("(IVR session '%s') unexpected response is received from TAS: '%s' (but expected: '%s'), continue to wait.", self.__context.get_id(), response, expected_response);
                continue;
            
            else:
                logging.debug("(IVR session '%s') expected response is received '%s', stop waiting process.", self.__context.get_id(), response);
                break;
Esempio n. 7
0
 def __run(self):
     logging.debug("(IVR session '%s') session '%s' is started at '%s'.", self.__context.get_id(), self.__context.get_id(), time.ctime());
     
     with self.__code_block_locker:
         command_container = self.__context.get_next_command();
     
     while( (self.__active is True) and (command_container is not None) ):
         (command, arguments) = command_container;
         
         if (command == command_type.COMMAND_SEND):
             self.__process_send_command(arguments[0], arguments[1], arguments[2]);
         
         elif (command == command_type.COMMAND_TIMEOUT):
             self.__process_timeout_command(arguments[0]);
         
         elif (command == command_type.COMMAND_WAIT):
             self.__process_wait_command(arguments[0]);
         
         elif (command == command_type.COMMAND_PRINT):
             self.__process_print_comand(arguments[0]);
         
         elif (command == command_type.COMMAND_EXIT):
             logging.info("(IVR session '%s') exit command is detected - termination...", self.__context.get_id());
             self.__active = False;
         
         elif (command == command_type.COMMAND_MOVE_JSON):
             self.__process_move_json(arguments[0]);
         
         elif (command == command_type.COMMAND_IF):
             self.__process_conditional_block(arguments[0], arguments[1]);
         
         else:
             logging.error("(IVR session '%s') unexpected command is detected...", self.__context.get_id());
         
         with self.__code_block_locker:
             command_container = self.__context.get_next_command();
     
     self.__manager.delete(self.__context.get_id(), internal = True);
     logging.info("(IVR session '%s') session is terminated at '%s'.", self.__context.get_id(), time.ctime());
Esempio n. 8
0
    def __process_send_command(self, method, tas_content, arguments):
        logging.debug("(IVR session '%s') command SEND is executing...", self.__context.get_id());
        
        tas_link = None;
        tas_method = None;
        
        if (method == "SAY"):
            tas_link = self.__context.get_tas_link_say();
            tas_method = "POST";
        
        elif (method == "STOP_SAY"):
            tas_link = self.__context.get_tas_link_stop_say();
            tas_method = "DELETE";
        
        elif (method == "PLAY"):
            tas_link = self.__context.get_tas_link_play();
            tas_method = "POST";
        
        elif (method == "STOP_PLAY"):
            tas_link = self.__context.get_tas_link_stop_play();
            tas_method = "DELETE";
        
        elif (method == "COLLECT"):
            tas_link = self.__context.get_tas_link_collect();
            tas_method = "POST";
        
        elif (method == "STOP_COLLECT"):
            tas_link = self.__context.get_tas_link_stop_collect();
            tas_method = "DELETE";
        
        elif (method == "FORWARD"):
            tas_link = self.__context.get_tas_link_forward();
            tas_method = "PUT";

        elif (method == "EXCEPTION"):
            tas_link = self.__context.get_tas_link_exception();
            tas_method = "PUT";

        if (len(arguments) > 0):
            tas_link_pattern = arguments[0];
            tas_link = self.__change_tas_link(tas_link, tas_link_pattern);
        
        tas_content = self.__translate_content(tas_content);
        
        logging.info("(IVR session '%s') send command request to TAS ('%s', '%s').", self.__context.get_id(), tas_method, method);
        (status, json_response) = self.__send(tas_method, tas_link, tas_content);
        if ( (status >= 200) and (status <= 299) ):
            if (tas_method == "POST"):
                response = json.loads(json_response);
                if (response.get("id", None) == None):
                    logging.error("(IVR session '%s') TAS reply to '%s' command '%s' without JSON body with 'id' key.", self.__context.get_id(), tas_method, method);
                
                else:
                    action_id = response['id'];
                    
                    if (method == "SAY"): self.__context.set_say_id(action_id);
                    elif (method == "PLAY"): self.__context.set_play_id(action_id);
                    elif (method == "COLLECT"): self.__context.set_collect_id(action_id);
                    
                    logging.info("(IVR session '%s') TAS accepts '%s' command '%s' and return action id: '%s'.", self.__context.get_id(), tas_method, method, action_id)
        
        else:
            logging.warning("(IVR session '%s') TAS reply to '%s' command '%s' by failure status (code: '%d').", self.__context.get_id(), tas_method, method, status);
Esempio n. 9
0
 def __process_timeout_command(self, timeout):
     logging.debug("(IVR session '%s') command TIMEOUT is executing (time: '%d')...", self.__context.get_id(), timeout);
     time.sleep(timeout / 1000.0);
Esempio n. 10
0
    def do_POST(self):
        tas_host, tas_port = self.client_address[:2]

        logging.info(
            "Receive HTTP POST request from TAS: '%s' (address: '%s:%s').",
            self.path, tas_host, tas_port)
        request = http_parser.parse(http_method.HTTP_POST, self.path)

        if (request == None):
            self.__send_response(http_code.HTTP_BAD_REQUEST,
                                 "\"Impossible to parse POST request.\"")
            return

        #
        # TAS_IVR_START_REQ
        #
        if (request[struct_field.id] == tas_command_type.IVR_START):
            if (configuration.get_failure_start_ivr_code() is not None):
                self.__send_response(
                    configuration.get_failure_start_ivr_code(), None,
                    configuration.get_failure_start_ivr_message())
                return

            # extract TAS request for session and attach additional information
            json_request = self.rfile.read(int(self.headers['Content-Length']))
            tas_request = json.loads(json_request)
            tas_request["tas_address"] = {
                "ip": tas_host,
                "port": tas_port
            }
            tas_request["account_id"] = request[struct_field.account_id]

            session_id = self.__get_session_manager().create(
                request[struct_field.script_id], tas_request)
            if (session_id is None):
                self.__send_response(
                    http_code.HTTP_NOT_FOUND,
                    "\"Session '" + str(session_id) + "' is not found.\"")
                return

            json_response = json_builder.start_ivr_response(session_id)
            self.__send_response(http_code.HTTP_OK_CREATED, json_response)

            self.__get_session_manager().launch(session_id)
        #
        # RESULT_ACTION
        #
        elif (request[struct_field.id] == tas_command_type.RESULT_COLLECT
              or request[struct_field.id] == tas_command_type.RESULT_PLAY
              or request[struct_field.id] == tas_command_type.RESULT_SAY):

            if (configuration.get_failure_action_result_code() is not None):
                self.__send_response(
                    configuration.get_failure_action_result_code(), None,
                    configuration.get_failure_action_result_message())
                return

            session_id = request[struct_field.session_id]
            message_id = request[struct_field.id]
            # script_id   = request[struct_field.script_id];

            json_result = self.rfile.read(int(self.headers['Content-Length']))

            logging.info("Callback action result is received (id: '%d').",
                         request[struct_field.id])
            logging.debug("Content of the callback result:\n%s", json_result)

            # it is represented by map because most probably other staff may be conveyed to session.
            json_instance = None
            try:
                json_instance = json.loads(json_result)

            except:
                logging.error(
                    "Impossible to parse JSON - corrupted JSON payload is received."
                )
                self.__send_response(
                    http_code.HTTP_BAD_REQUEST,
                    "\"Corrupted JSON payload in POST request.\"")
                return

            message_playload = {
                'json': json_instance
            }

            if (self.__get_session_manager().exist(session_id)):
                reply_code = self.__get_session_manager().notify(
                    session_id, message_id, message_playload)

                reply_message = None
                if (reply_code is None):
                    reply_code = http_code.HTTP_OK
                    reply_message = "\"Success.\""
                else:
                    reply_message = "\"Specified reply code is used.\""

                self.__send_response(reply_code, reply_message)
                return

            self.__send_response(
                http_code.HTTP_NOT_FOUND,
                "\"Session '" + str(session_id) + "' is not found.\"")

        else:
            self.__send_response(
                http_code.HTTP_BAD_REQUEST, "\"Unknown POST type command '" +
                str(request[struct_field.id]) + "'.\"")
            return