<commit_before>import json
import threading
from datetime import datetime

from freeswitchESL.ESL import *
from sqlalchemy.exc import SQLAlchemyError

from cereproc.cereproc_rest_agent import CereprocRestAgent
from rootio.config import DefaultConfig
from rootio.telephony.models import Gateway, Call
from telephony.community_ivr_menu import CommunityIVRMenu


class CallHandler:

    def __init__(self, radio_station):
        self.__radio_station = radio_station
        self.__incoming_call_recipients = dict()
        self.__incoming_dtmf_recipients = dict()
        self.__outgoing_call_recipients = dict()
        self.__host_call_recipients = dict()
        self.__waiting_call_recipients = dict()
        self.__call_hangup_recipients = dict()
        self.__available_calls = dict()
        self.__media_playback_stop_recipients = dict()
        self.__media_playback_start_recipients = dict()
        self.__speech_start_recipients = dict()
        self.__speech_stop_recipients = dict()
        self.__community_menu_sessions = dict()
        self.__community_ivr_number = None

        # get the gateways to be used for telephony
        self.__load_incoming_gateways()
        self.__load_outgoing_gateways()

        # start listener for ESL events
        self.__start_esl_listener()

        # configure cereproc agent
        self._cprc_agent = CereprocRestAgent(DefaultConfig.CEREPROC_SERVER, DefaultConfig.CEREPROC_USERNAME,
                                             DefaultConfig.CEREPROC_PASSWORD)  # ToDo: defaults to English,
        #  male, 1600, wav. Pick args from station attributes.

    def __start_esl_listener(self):
        t = threading.Thread(target=self.__listen_for_esl_events, args=())
        t.daemon = True
        t.start()

    def __connect_esl(self):
        esl_server = DefaultConfig.ESL_SERVER
        esl_port = DefaultConfig.ESL_PORT
        esl_authentication = DefaultConfig.ESL_AUTHENTICATION
        return ESLconnection(esl_server, esl_port, esl_authentication)

    def __load_incoming_gateways(self):
        gws = self.__radio_station.db.query(Gateway).join(Gateway.stations_using_for_incoming).filter_by(
            id=self.__radio_station.station.id).all()
        self.__incoming_gateways = dict()
        self.__available_incoming_gateways = []
        for gw in gws:
            self.__incoming_gateways[str(gw.number_bottom)] = gw
            self.__available_incoming_gateways.append(gw.number_bottom)
            self.__available_incoming_gateways.sort()
            self.__radio_station.logger.info(
                "Got incoming gateways for {0} {1}".format(self.__radio_station.station.name,
                                                           str(self.__available_incoming_gateways)))

    def __load_outgoing_gateways(self):
        gws = self.__radio_station.db.query(Gateway).join(Gateway.stations_using_for_outgoing).filter_by(
            id=self.__radio_station.station.id).all()
        self.__outgoing_gateways = dict()
        self.__outgoing_sip_gateways = dict()
        self.__available_outgoing_gateways = []
        for gw in gws:
            if gw.is_goip:
                self.__outgoing_gateways[str(gw.number_bottom)] = gw
                self.__available_outgoing_gateways.append(gw.number_bottom)
                self.__available_outgoing_gateways.sort()
                self.__radio_station.logger.info(
                    "Got outgoing goip gateways for {0} {1}".format(self.__radio_station.station.name,
                                                                    str(self.__available_outgoing_gateways)))
            else:  # really all you need is one outgoing :-)
                self.__outgoing_sip_gateways[str(gw.number_bottom)] = gw
                self.__radio_station.logger.info(
                    "Got outgoing SIP gateways for {0} {1}".format(self.__radio_station.station.name,
                                                                   str(self.__outgoing_sip_gateways)))

    def __do_esl_command(self, esl_command):
        self.__radio_station.logger.info("Executing ESL Command: {0}".format(esl_command))
        con = self.__connect_esl()
        result = con.api(esl_command)
        try:
            con.disconnect()
            return result.getBody()
        except Exception, e:
            self.__radio_station.logger.error(e.message)
            return None

    def register_for_call_hangup(self, recipient, to_number):
        self.__call_hangup_recipients[to_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to incoming call hangup recipients {1}".format(recipient, str(self.__call_hangup_recipients)))

    def register_for_host_call(self, recipient, host_number):
        self.__host_call_recipients[host_number] = recipient
        self.__radio_station.logger.info(
            "The program {0} is now listening for host calls from {1}".format(recipient, host_number))

    def register_community_ivr_number(self, number):
        self.__community_ivr_number = number

    def register_for_incoming_calls(self, recipient, is_community_menu=False):
        gws = self.__incoming_gateways.keys()
        gws.sort()
        if is_community_menu:  # register only the first gateway, only 9 digits to match various incoming formats
            if len(gws) > 0:
                self.__incoming_call_recipients[gws[0][-9:]] = recipient
        else:
            for x in range(1, len(gws)):  # skip the first, used by community menu
                self.__incoming_call_recipients[gws[x][-9:]] = recipient
                self.__radio_station.logger.info(
                    "Added {0} to incoming call recipients {1}".format(recipient, str(self.__incoming_call_recipients)))

    def register_for_incoming_dtmf(self, recipient, from_number):
        self.__incoming_dtmf_recipients[from_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to incoming dtmf recipients {1}".format(recipient, str(self.__incoming_dtmf_recipients)))

    def deregister_for_incoming_dtmf(self, from_number):
        if from_number in self.__incoming_dtmf_recipients:
            del self.__incoming_dtmf_recipients[from_number]

    def register_for_speak_start(self, recipient, from_number):
        self.__speech_start_recipients[from_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to speak start recipients {1}".format(recipient, str(self.__speech_start_recipients)))

    def deregister_for_speak_start(self, from_number):
        if from_number in self.__speech_start_recipients:
            del self.__speech_start_recipients[from_number]

    def register_for_speak_stop(self, recipient, from_number):
        self.__speech_stop_recipients[from_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to speak stop recipients {1}".format(recipient, str(self.__speech_stop_recipients)))

    def deregister_for_speak_stop(self, from_number):
        if from_number in self.__speech_stop_recipients:
            del self.__speech_stop_recipients[from_number]

    def register_for_media_playback_stop(self, recipient, from_number):
        self.__media_playback_stop_recipients[from_number] = recipient
        self.__radio_station.logger.info("Added {0} to media playback stop recipients {1}".format(recipient, str(
            self.__media_playback_stop_recipients)))

    def register_for_media_playback_start(self, recipient, from_number):
        self.__media_playback_start_recipients[from_number] = recipient
        self.__radio_station.logger.info("Added {0} to media playback start recipients {1}".format(recipient, str(
            self.__media_playback_start_recipients)))

    def deregister_for_incoming_calls(self, recipient):
        self.__incoming_call_recipients = dict()
        self.__radio_station.logger.info(
            "Removed {0} from call hangup recipients {1}".format(recipient, str(self.__incoming_call_recipients)))

    def deregister_for_call_hangup(self, from_number):
        if from_number in self.__call_hangup_recipients:
            del self.__call_hangup_recipients[from_number]
            self.__radio_station.logger.info(
                "Removed {0} from call hangup recipients {1}".format(from_number, str(self.__call_hangup_recipients)))

    def deregister_ivr_menu_session(self, from_number):
        if from_number in self.__community_menu_sessions:
            del self.__community_menu_sessions[from_number]
            self.__radio_station.logger.info(
                "Removed {0} from call hangup recipients {1}".format(from_number, str(self.__community_menu_sessions)))

    def deregister_for_media_playback_stop(self, from_number):
        if from_number in self.__media_playback_stop_recipients:
            del self.__media_playback_stop_recipients[from_number]
            self.__radio_station.logger.info("Removed {0} from media playback stop recipients {1}"
                                             .format(from_number, str(self.__media_playback_stop_recipients)))

    def deregister_for_media_playback_start(self, from_number):
        if from_number in self.__media_playback_start_recipients:
            del self.__media_playback_start_recipients[from_number]
            self.__radio_station.logger.info("Removed {0} from media playback start recipients {1}"
                                             .format(from_number, str(self.__media_playback_start_recipients)))

    def call_exists(self, to_number):
        return self.__available_calls is not None and to_number in self.__available_calls.keys()

    def call(self, program_action, to_number, argument, use_sip=False,<commit_msg>Logging for check of if requested call exists<commit_after>import json
import threading
from datetime import datetime

from freeswitchESL.ESL import *
from sqlalchemy.exc import SQLAlchemyError

from cereproc.cereproc_rest_agent import CereprocRestAgent
from rootio.config import DefaultConfig
from rootio.telephony.models import Gateway, Call
from telephony.community_ivr_menu import CommunityIVRMenu


class CallHandler:

    def __init__(self, radio_station):
        self.__radio_station = radio_station
        self.__incoming_call_recipients = dict()
        self.__incoming_dtmf_recipients = dict()
        self.__outgoing_call_recipients = dict()
        self.__host_call_recipients = dict()
        self.__waiting_call_recipients = dict()
        self.__call_hangup_recipients = dict()
        self.__available_calls = dict()
        self.__media_playback_stop_recipients = dict()
        self.__media_playback_start_recipients = dict()
        self.__speech_start_recipients = dict()
        self.__speech_stop_recipients = dict()
        self.__community_menu_sessions = dict()
        self.__community_ivr_number = None

        # get the gateways to be used for telephony
        self.__load_incoming_gateways()
        self.__load_outgoing_gateways()

        # start listener for ESL events
        self.__start_esl_listener()

        # configure cereproc agent
        self._cprc_agent = CereprocRestAgent(DefaultConfig.CEREPROC_SERVER, DefaultConfig.CEREPROC_USERNAME,
                                             DefaultConfig.CEREPROC_PASSWORD)  # ToDo: defaults to English,
        #  male, 1600, wav. Pick args from station attributes.

    def __start_esl_listener(self):
        t = threading.Thread(target=self.__listen_for_esl_events, args=())
        t.daemon = True
        t.start()

    def __connect_esl(self):
        esl_server = DefaultConfig.ESL_SERVER
        esl_port = DefaultConfig.ESL_PORT
        esl_authentication = DefaultConfig.ESL_AUTHENTICATION
        return ESLconnection(esl_server, esl_port, esl_authentication)

    def __load_incoming_gateways(self):
        gws = self.__radio_station.db.query(Gateway).join(Gateway.stations_using_for_incoming).filter_by(
            id=self.__radio_station.station.id).all()
        self.__incoming_gateways = dict()
        self.__available_incoming_gateways = []
        for gw in gws:
            self.__incoming_gateways[str(gw.number_bottom)] = gw
            self.__available_incoming_gateways.append(gw.number_bottom)
            self.__available_incoming_gateways.sort()
            self.__radio_station.logger.info(
                "Got incoming gateways for {0} {1}".format(self.__radio_station.station.name,
                                                           str(self.__available_incoming_gateways)))

    def __load_outgoing_gateways(self):
        gws = self.__radio_station.db.query(Gateway).join(Gateway.stations_using_for_outgoing).filter_by(
            id=self.__radio_station.station.id).all()
        self.__outgoing_gateways = dict()
        self.__outgoing_sip_gateways = dict()
        self.__available_outgoing_gateways = []
        for gw in gws:
            if gw.is_goip:
                self.__outgoing_gateways[str(gw.number_bottom)] = gw
                self.__available_outgoing_gateways.append(gw.number_bottom)
                self.__available_outgoing_gateways.sort()
                self.__radio_station.logger.info(
                    "Got outgoing goip gateways for {0} {1}".format(self.__radio_station.station.name,
                                                                    str(self.__available_outgoing_gateways)))
            else:  # really all you need is one outgoing :-)
                self.__outgoing_sip_gateways[str(gw.number_bottom)] = gw
                self.__radio_station.logger.info(
                    "Got outgoing SIP gateways for {0} {1}".format(self.__radio_station.station.name,
                                                                   str(self.__outgoing_sip_gateways)))

    def __do_esl_command(self, esl_command):
        self.__radio_station.logger.info("Executing ESL Command: {0}".format(esl_command))
        con = self.__connect_esl()
        result = con.api(esl_command)
        try:
            con.disconnect()
            return result.getBody()
        except Exception, e:
            self.__radio_station.logger.error(e.message)
            return None

    def register_for_call_hangup(self, recipient, to_number):
        self.__call_hangup_recipients[to_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to incoming call hangup recipients {1}".format(recipient, str(self.__call_hangup_recipients)))

    def register_for_host_call(self, recipient, host_number):
        self.__host_call_recipients[host_number] = recipient
        self.__radio_station.logger.info(
            "The program {0} is now listening for host calls from {1}".format(recipient, host_number))

    def register_community_ivr_number(self, number):
        self.__community_ivr_number = number

    def register_for_incoming_calls(self, recipient, is_community_menu=False):
        gws = self.__incoming_gateways.keys()
        gws.sort()
        if is_community_menu:  # register only the first gateway, only 9 digits to match various incoming formats
            if len(gws) > 0:
                self.__incoming_call_recipients[gws[0][-9:]] = recipient
        else:
            for x in range(1, len(gws)):  # skip the first, used by community menu
                self.__incoming_call_recipients[gws[x][-9:]] = recipient
                self.__radio_station.logger.info(
                    "Added {0} to incoming call recipients {1}".format(recipient, str(self.__incoming_call_recipients)))

    def register_for_incoming_dtmf(self, recipient, from_number):
        self.__incoming_dtmf_recipients[from_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to incoming dtmf recipients {1}".format(recipient, str(self.__incoming_dtmf_recipients)))

    def deregister_for_incoming_dtmf(self, from_number):
        if from_number in self.__incoming_dtmf_recipients:
            del self.__incoming_dtmf_recipients[from_number]

    def register_for_speak_start(self, recipient, from_number):
        self.__speech_start_recipients[from_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to speak start recipients {1}".format(recipient, str(self.__speech_start_recipients)))

    def deregister_for_speak_start(self, from_number):
        if from_number in self.__speech_start_recipients:
            del self.__speech_start_recipients[from_number]

    def register_for_speak_stop(self, recipient, from_number):
        self.__speech_stop_recipients[from_number] = recipient
        self.__radio_station.logger.info(
            "Added {0} to speak stop recipients {1}".format(recipient, str(self.__speech_stop_recipients)))

    def deregister_for_speak_stop(self, from_number):
        if from_number in self.__speech_stop_recipients:
            del self.__speech_stop_recipients[from_number]

    def register_for_media_playback_stop(self, recipient, from_number):
        self.__media_playback_stop_recipients[from_number] = recipient
        self.__radio_station.logger.info("Added {0} to media playback stop recipients {1}".format(recipient, str(
            self.__media_playback_stop_recipients)))

    def register_for_media_playback_start(self, recipient, from_number):
        self.__media_playback_start_recipients[from_number] = recipient
        self.__radio_station.logger.info("Added {0} to media playback start recipients {1}".format(recipient, str(
            self.__media_playback_start_recipients)))

    def deregister_for_incoming_calls(self, recipient):
        self.__incoming_call_recipients = dict()
        self.__radio_station.logger.info(
            "Removed {0} from call hangup recipients {1}".format(recipient, str(self.__incoming_call_recipients)))

    def deregister_for_call_hangup(self, from_number):
        if from_number in self.__call_hangup_recipients:
            del self.__call_hangup_recipients[from_number]
            self.__radio_station.logger.info(
                "Removed {0} from call hangup recipients {1}".format(from_number, str(self.__call_hangup_recipients)))

    def deregister_ivr_menu_session(self, from_number):
        if from_number in self.__community_menu_sessions:
            del self.__community_menu_sessions[from_number]
            self.__radio_station.logger.info(
                "Removed {0} from call hangup recipients {1}".format(from_number, str(self.__community_menu_sessions)))

    def deregister_for_media_playback_stop(self, from_number):
        if from_number in self.__media_playback_stop_recipients:
            del self.__media_playback_stop_recipients[from_number]
            self.__radio_station.logger.info("Removed {0} from media playback stop recipients {1}"
                                             .format(from_number, str(self.__media_playback_stop_recipients)))

    def deregister_for_media_playback_start(self, from_number):
        if from_number in self.__media_playback_start_recipients:
            del self.__media_playback_start_recipients[from_number]
            self.__radio_station.logger.info("Removed {0} from media playback start recipients {1}"
                                             .format(from_number, str(self.__media_playback_start_recipients)))

    def call_exists(self, to_number):
        self.__radio_station.logger.info("Checking for call to {0} in available calls {1}"
                                         .format(to_number, str(self.__available_calls)))
        return self.__available_calls is not None and to_number in self.__available_calls.keys()

    def call(self, program_action, to_number, argument, use_sip=False,
{'fraction_non_alphanumeric': 0.08051644385706298, 'fraction_numerical': 0.004473135769836832, 'mean_word_length': 2.9199043634190076, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1521001', 'n_tokens_mistral': 5859, 'n_tokens_neox': 5559, 'n_words': 1045}