Exemplo n.º 1
0
    def send_message(self, message="", **kwargs):
        """Send an SMS to target users."""
        from asterisk.ami import AMIClient
        from asterisk.ami.action import SimpleAction

        client = AMIClient(address=self._address, port=self._port)
        future = client.login(username=self._user, secret=self._password)
        if future.response.is_error():
            _LOGGER.error("Can't connect to Asterisk AMI: %s", " ".join(str(future.response).splitlines()))
            return

        targets = kwargs.get(ATTR_TARGET)

        if targets is None:
            _LOGGER.error("No SMS targets, as 'target' is not defined")
            return

        # TODO: add quota per day
        for target in targets:
            _LOGGER.debug("Sending SMS to %s", target)
            action = SimpleAction(
                'DongleSendSMS',
                Device=self._dongle,
                Number=target,
                Message=message,
            )
            client.send_action(action, callback=lambda r: self._on_message(target, r))
            _LOGGER.debug("SMS to %s sent", target)

        client.logoff()
Exemplo n.º 2
0
def run_call(ext, to):
    sip = 'SIP/{}'.format(ext)
    tel = '9{}'.format(to)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(3)
    ats1 = 'f1.ats.com'
    ats2 = 'f2.ats.com'
    host = ats1
    try:
        sock.connect((ats1, 5038))
    except socket.error:
        host = ats2
    sock.close()
    client = AMIClient(address=host, port=5038)
    client.login(username='******', secret='pass')
    action = SimpleAction(
        'Originate',
        Channel=sip,
        Exten=tel,
        Priority=1,
        Context='from-internal',
        CallerID='crmdancer',
    )
    client.send_action(action, callback=None)
    client.logoff()
def call_initiation(transaction_id,
                    mobile_no,
                    product_type,
                    prefix,
                    context="0009"):
    try:
        client = AMIClient(address='10.101.1.184', port=5038)
        client.login(username='******', secret='gihosp123')

        action = SimpleAction('Originate',
                              Channel="local/" + "6" + mobile_no +
                              "@from-internal",
                              Context="GIVoice",
                              Exten=context,
                              Priority=1,
                              Account=product_type,
                              CallerID=transaction_id,
                              Async="yes",
                              Timeout=50000)
        future = client.send_action(action)
        response = future.response

        update_channel_detail_call_initiated()
        return True
    except Exception as ex:
        raise Exception(
            "SIP server is down .. please check eject error {}".format(
                str(ex)))
        return True
Exemplo n.º 4
0
def CallSip(exten, ponebind, callid):
    client = AMIClient(address='192.168.200.220', port=5060)
    client.login(username='******', secret='pbx6002')
    sip = 'SIP/%s' % ponebind
    print(sip)
    action = SimpleAction(
        'Originate',
        Channel=sip,
        Exten=callid,  # 目标电话
        Priority=1,
        Context='MAIN_OUTGOING',  # 呼叫规则
        CallerID=exten,  # 来自电话
    )
    client.send_action(action)
    future = client.send_action(action)
    response = future.response
Exemplo n.º 5
0
def Listen(request, num):
    print(request.user.aduser.telephoneNumber)
    PBXClient = AMIClient(address=settings.JSON_SETTINGS['asteriskServer'],
                          port=5038)
    PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'],
                    secret=settings.JSON_SETTINGS['AMIPassword'])
    print(PBXClient)
    action = SimpleAction(
        'Originate',
        Channel=('SIP/%s' % request.user.aduser.telephoneNumber),
        CallerID=('Spy%s' % num),
        #Exten = '6670',
        #Application = 'Playback',
        Application='ChanSpy',
        #Data = '/var/spool/asterisk/monitor/2017/10/03/out-1694-6666-20171003-103712-1507016232.189',
        Data=('SIP/%s,qx' % num),
        Timeout='30000',
        #Priority = '1',
        #Async = 'yes'
    )
    print(action)
    ans = PBXClient.send_action(action)
    print(ans.response)
    PBXClient.logoff()
    return HttpResponse(ans.response)
Exemplo n.º 6
0
def call():

    call_message = "call in progress"
    client = AMIClient(address='172.16.1.254', port=5038)
    client.login(username='******', secret='9787474')
    action = SimpleAction(
        'Originate',
        Channel='DAHDI/i1/09385255833',
        Exten='698',
        Priority=1,
        Context='from-internal',
        CallerID="Channel",
    )
    client.send_action(action)

    client.logoff()

    flash("success call", 'success')
    return render_template('home.html', message=call_message)
Exemplo n.º 7
0
def ami_event(peer, action):

# Part of dialplan to generate AMI UserEvent:    
# exten => 881,2,UserEvent(Channel: SIP, Peername: ${CALLERID(num)}, DND: enabled)
# exten => 882,2,UserEvent(Channel: SIP, Peername: ${CALLERID(num)}, DND: disabled)
    
    # channel - just a variable for MonAst
    channel = 'SIP/'+str(peer)

    # AMI connection. username and secret create in /etc/asterisk/manager.conf:
    client = AMIClient(address=aster_server, port=ami_port)
    client.login(username=ami_user, secret=ami_pass)
   
    if action == 'enabled':
        action = SimpleAction('UserEvent', UserEvent='UserEvent', peername=peer, dnd='enabled', channel=channel, status='DND enabled',)
    elif action == 'disabled':
        action = SimpleAction('UserEvent', UserEvent='UserEvent', peername=peer, dnd='disabled', channel=channel, status='DND disabled',)
    
    client.send_action(action)
    client.logoff()
Exemplo n.º 8
0
def ami_action(number, shablon, cursor, db, id):
	Channel = trunk+number
	logging.debug("Channel - {}".format(Channel) )
	#logging.info("Channel - {}".format(Channel) )
	# Variable=id=3
	var = "VAR="+str(shablon)+str(id)
	# Connect to AMI
	client = AMIClient(address=aster_server, port=ami_port)
	client.login(username=ami_user, secret=ami_pass)

	action = SimpleAction(
			'Originate',
			 Channel=Channel,
			 Exten=exten,
			 Context=context,
			 Priority=1,
			 CallerID=number,
			 Variable=var,)
	try:
		client.send_action(action)
		client.logoff()
	except Exception as ex:
		print(ex)
Exemplo n.º 9
0
 def originate(self, ext, target):
     logging.info("Originating call from %s to %s", str(ext), str(target))
     client = AMIClient(address=AMI_HOST, port=AMI_PORT)
     client.login(username=AMI_USERNAME, secret=AMI_SECRET)
     action = SimpleAction('Originate',
                           Channel='SIP/{0}'.format(ext),
                           Exten=target,
                           Priority=1,
                           Context='from-internal',
                           CallerID=ext,
                           Async='No',
                           WaitTime=5)
     x = client.send_action(action)
     print(x)
Exemplo n.º 10
0
def reload_queues():
    try:
        client = AMIClient(address=ami_ip, port=ami_port)
        client.login(username=ami_user, secret=ami_secret)
        command = SimpleAction('QueueReload',
                               Members='yes',
                               Rules='no',
                               Parametes='yes')
        result = str(client.send_action(command).response).replace(
            "\r", "").split("\n")
        if isinstance(result, list):
            if 'Response: Success' in result:
                return True
            else:
                return False

    except Exception as e:
        return str(e)
Exemplo n.º 11
0
def dev_dial(action):
    """Function that actually makes the asterisk call."""

    try:
        client = AMIClient(address=AUTH_CREDS['address'],
                           port=AUTH_CREDS['port'])
        client.login(username=AUTH_CREDS['username'],
                     secret=AUTH_CREDS['secret'])

        future = client.send_action(action)
        if VERBOSE:
            print(future.response or "None")

        client.logoff()

    except Exception as e:
        print("Error: %s" % e.strerror)
        sys.exit(1)
Exemplo n.º 12
0
def Originate(Extension,
              phoneNumber,
              CallerID='python',
              Context='from-internal'):
    client = AMIClient(**config.AMIClientAddress)
    client.login(**config.AMIClientUser)
    logger = logging.getLogger("bot.ClinicaWeb")
    action = SimpleAction(
        'Originate',
        Channel='SIP/' + str(Extension),
        Exten=phoneNumber,
        Priority=1,
        Context=Context,
        CallerID=CallerID,
    )
    logger.info("Start originate from %s to %s" % (Extension, phoneNumber))
    if client.send_action(action).response.status == 'Success':
        logger.info("Start call from %s to %s" % (Extension, phoneNumber))
    else:
        logger.info("Cancel originate from %s to %s" %
                    (Extension, phoneNumber))
    client.logoff()
Exemplo n.º 13
0
class asterisk_reconnect:
    def __init__(self, logger, config):

        self.logger = logger
        self.config = config
        self.clients = self.config['clients']

        self.check_interval = config['intervals']['check_interval']
        self.reconnect_interval = config['intervals']['reconnect_interval']
        self.ping_interval = config['intervals']['ping_interval']

        self.ami_host = config['ami']['host']
        self.ami_port = int(config['ami']['port'])
        self.ami_username = config['ami']['username']
        self.ami_password = config['ami']['password']

        self.ami_client = AMIClient(address=self.ami_host, port=self.ami_port)
        self.channels = []
        self.last_check = time.time()
        self.last_ping = time.time()
        self.last_login = time.time()
        self.connected = False

        self.kill_received = False
        self.thread = threading.Thread(target=self.reconnect_loop, args=())
        self.thread.daemon = True
        self.thread.start()

    def login(self):

        self.last_login = time.time()

        self.ami_client = AMIClient(address=self.ami_host, port=self.ami_port)

        try:
            self.ami_client.login(username=self.ami_username,
                                  secret=self.ami_password)
            self.connected = True
            self.logger.info("Successfully logged into AMI")
            return True

        except Exception as e:

            error = self.handle_ami_exception(e)
            self.logger.error("Unable to login to AMI: %s" % error)

    def logoff(self):

        try:
            self.ami_client.logoff()
            self.connected = True

        except Exception as e:

            error = self.handle_ami_exception(e)
            self.logger.error("Unable to logoff from AMI: %s" % error)

    def send_ping(self):

        self.logger.debug("Sending Ping")
        self.last_ping = time.time()

        try:
            action = SimpleAction('ping')
            self.ami_client.send_action(action)

        except Exception as e:
            error = self.handle_ami_exception(e)
            self.logger.error("Sending Ping Failed: %s" % error)

    def get_channels(self):

        command = ("core show channels concise")

        action = SimpleAction('Command', Command=command)

        try:
            future = self.ami_client.send_action(action)

            response = future.response.follows
            chan_len = len(response) - 1
            response = response[:chan_len]

            self.channels = []

            for channel in response:

                match = re.match(
                    "((.*?)\/.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)!(.*?)$",
                    channel)

                if match:
                    chan_type = match.group(2)
                    chan = match.group(1)
                    context = match.group(3)
                    extension = match.group(4)
                    priority = match.group(5)
                    state = match.group(6)
                    app = match.group(7)
                    data = match.group(8)
                    clid = match.group(9)
                    duration = match.group(12)
                    bridged_to = match.group(13)

                    parsed_chan = {
                        "chan_type": chan_type,
                        "chan": chan,
                        "context": context,
                        "extension": extension,
                        "priority": priority,
                        "state": state,
                        "app": app,
                        "data": data,
                        "clid": clid,
                        "duration": duration,
                        "bridged_to": bridged_to
                    }

                    self.channels.append(parsed_chan)

                else:
                    self.logger.error("Unable to parse channel: %s " % channel)

            return self.channels

        except Exception as e:
            error = self.handle_ami_exception(e)
            self.logger.error("Unable to get channels: %s" % error)
            self.channels = []

    def handle_ami_exception(self, exception):

        if exception.errno == errno.ECONNREFUSED:
            self.connected = False
            return ("Unable to connect to AMI (Connection Refused)")

        elif exception.errno == errno.EPIPE:
            self.connected = False
            return ("No longer connected to AMI (Broken Pipe)")

        elif exception.errno == errno.EBADF:
            self.connected = False
            return ("No longer connected to AMI (Bad File Descriptor)")

        else:
            self.connected = False
            raise exception

    def check_clients(self):

        for client, params in self.clients.items():

            context = params['context']
            extension = params['extension']
            uri = params['uri']

            if not self.chan_connected(context, extension, uri):
                self.logger.info("Client \'%s\' not connected" % client)
                self.connect_client(client, context, extension, uri)

    def chan_connected(self, context, extension, uri):

        for channel in self.channels:

            if (context == channel['context']
                    and extension == channel['extension']
                    and self.uri_comp(channel['chan'], uri)):

                return True

        return False

    def uri_comp(self, chan_uri, client_uri):

        chan_match = re.match("(.*?)(?:$|-)", chan_uri)

        client_match = re.match("(.*?):(?:.*)@(.*)$", client_uri)

        if chan_match and client_match:

            chan_parsed = chan_match.group(1)

            client_scheme = client_match.group(1).upper()
            client_host = client_match.group(2)

            client_parsed = ("%s/%s" % (client_scheme, client_host))

            # self.logger.debug("Comparing %s and %s" % (client_parsed,
            #                                            chan_parsed))

            if chan_parsed == client_parsed:
                return True

        elif chan_match:

            self.logger.info("Error parsing client URI: %s" % client_uri)
            return False

        elif client_match:

            self.logger.info("Error parsing chan URI: %s" % chan_uri)
            return False

        else:
            self.logger.info("Error parsing client URI: %s" % client_uri)
            self.logger.info("Error parsing chan URI: %s" % chan_uri)
            return False

    def connect_client(self, client, context, extension, uri):

        match = re.match("(.*?):(.*)$", uri)

        if match:

            scheme = match.group(1)
            uri = match.group(2)

            if scheme == "sip":
                scheme = "SIP"
            elif scheme == "iax":
                scheme = "IAX"

            channel = ("%s/%s" % (scheme, uri))

            self.logger.info("Connecting to %s  (%s)" % (client, channel))

            action = SimpleAction(
                'Originate',
                Channel=channel,
                Exten=extension,
                Priority=1,
                Context=context,
                CallerID='AutoDialler',
            )

            try:
                self.ami_client.send_action(action)
            except Exception as e:
                error = self.handle_ami_exception(e)
                self.logger.info("Unable to connect to %s: %s" %
                                 (client, error))

    def run_check(self):

        self.logger.debug("Checking Connected Clients")
        self.last_check = time.time()
        self.last_ping = time.time()
        self.get_channels()
        self.check_clients()

    def reconnect_loop(self):

        self.login()

        if self.connected:
            self.run_check()
            self.last_check = time.time()
            self.last_ping = time.time()

        while not self.kill_received:

            current_time = time.time()

            if not self.connected and current_time - self.last_login > self.reconnect_interval:
                self.logger.info("Reattempting Login")
                self.login()

            elif self.connected:

                if current_time - self.last_check > self.check_interval:
                    self.run_check()

                if current_time - self.last_ping > self.ping_interval:
                    self.send_ping()

            time.sleep(1)

        self.logger.info("Terminating Thread")
        self.logoff()
Exemplo n.º 14
0
r = redis.StrictRedis(**redisConf)
status = {}
active = {}


def event_notification(source, event):
    print(event)


client = AMIClient(**connection)
future = client.login(**login)
if future.response.is_error():
    raise Exception(str(future.response))

action = SimpleAction(
    'Originate',
    Channel='PJSIP/101',
    Exten=ZHENKIN_SIP,
    Priority=1,
    Context='default',
    CallerID='python',
)
client.send_action(action)

client.add_event_listener(event_notification)

try:
    while True:
        time.sleep(3)
except (KeyboardInterrupt, SystemExit):
    client.logoff()
class asterisk_originate:
    def __init__(self, ami_host, ami_port, ami_username, ami_password):

        self.__ami_host = ami_host
        self.__ami_port = int(ami_port)
        self.___ami_username = ami_username
        self.__ami_password = ami_password

        self.__ami_client = AMIClient(address=self.__ami_host,
                                      port=self.__ami_port)

    def _login(self):

        self.__ami_client = AMIClient(address=self.__ami_host,
                                      port=self.__ami_port)

        try:
            self.__ami_client.login(username=self.___ami_username,
                                    secret=self.__ami_password)
            print("Successfully logged into AMI")
            return True

        except Exception as e:

            error = self._handle_ami_exception(e)
            print("Unable to login to AMI: %s" % error)
            return False

    def _logoff(self):

        try:
            self.__ami_client.logoff()
            return True

        except Exception as e:

            error = self._handle_ami_exception(e)
            print("Unable to logoff from AMI: %s" % error)
            return False

    def _handle_ami_exception(self, exception):

        try:
            if exception.errno == errno.ECONNREFUSED:
                return ("Unable to connect to AMI (Connection Refused)")

            elif exception.errno == errno.EPIPE:
                return ("No longer connected to AMI (Broken Pipe)")

            elif exception.errno == errno.EBADF:
                return ("No longer connected to AMI (Bad File Descriptor)")

            else:
                return (exception)

        except Exception as e:
            return (e)

    def _send_originate_context(self,
                                channel,
                                context,
                                extension,
                                priority,
                                callerid,
                                timeout=60,
                                variables=""):

        action = SimpleAction('Originate',
                              Channel=channel,
                              Exten=extension,
                              Priority=priority,
                              Context=context,
                              CallerID=callerid,
                              Timeout=timeout * 1000,
                              Variable=variables,
                              Async="true")

        try:
            self.__ami_client.send_action(action)
            return True

        except Exception as e:
            error = self._handle_ami_exception(e)
            print("Unable to connect to %s: %s" % (channel, error))
            return False

    def _send_originate_application(self, channel, application, data,
                                    callerid):

        action = SimpleAction('Originate',
                              Channel=channel,
                              CallerID=callerid,
                              Application=application,
                              Data=data,
                              Async="true")

        try:
            self.__ami_client.send_action(action)
            return True

        except Exception as e:
            error = self._handle_ami_exception(e)
            print("Unable to connect to %s: %s" % (channel, error))
            return False

    def originate_context(self,
                          channels,
                          context,
                          extension,
                          priority,
                          callerid,
                          timeout=60,
                          variables=""):

        split_channels = channels.split("&")

        if None not in (channels, extension, priority, context, callerid):

            if self._login():

                for channel in split_channels:

                    self._send_originate_context(channel, context, extension,
                                                 priority, callerid, timeout,
                                                 variables)

                if self._logoff():

                    return True

                else:
                    return False

        else:
            raise MissingParams("Failed to parse application parameters")

    def originate_application(self, channels, application, data, callerid):

        split_channels = channels.split("&")

        if None not in (channels, application, data, callerid):

            if self._login():

                for channel in split_channels:

                    self._send_originate_application(channel, application,
                                                     data, callerid)

                if self._logoff():

                    return True

                else:
                    return False

        else:
            raise MissingParams("Failed to parse originate parameters")
Exemplo n.º 16
0
class AsteriskStatus():
    isconnected = False
    client = None

    def __init__(self):
        self.config = ReadConfig()
        self.mqttc = mqtt.Client()

    def logout(self):
        self.client.logoff()

    # Gets the Caller ID

    def cid_start(self, cid):
        self.cid_response = None
        self.client = AMIClient(address=self.config['asterisk']['ip'],
                                port=self.config['asterisk']['port'])
        self.client.login(username=self.config['asterisk']['user'],
                          secret=self.config['asterisk']['pass'])
        self.client.add_event_listener(self.connection_listener)
        self.client.add_event_listener(self.cid_listener)
        self.sendaction_cid(cid)
        return self.cid_response

    def sendaction_cid(self, cid):
        action = SimpleAction('DBGet',
                              Family=self.config['asterisk']['dbname'],
                              Key=cid)
        future = self.client.send_action(action)
        if future.response.status == 'Success':
            while self.cid_response is None:
                time.sleep(0.001)
        self.logout()

    def cid_listener(self, event, **kwargs):
        if event.name == 'DBGetResponse':
            self.cid_response = event['Val']

    # Starts the main program

    def connection_start(self):
        try:
            self.tmp_events = []
            self.events = []

            self.client = AMIClient(address=self.config['asterisk']['ip'],
                                    port=self.config['asterisk']['port'])
            self.client.login(username=self.config['asterisk']['user'],
                              secret=self.config['asterisk']['pass'])
            self.client.add_event_listener(self.connection_listener)

            self.mqttc.username_pw_set(self.config['mqtt']['user'],
                                       password=self.config['mqtt']['pass'])
            self.mqttc.connect(self.config['mqtt']['ip'])
            self.mqttc.loop_start()

            self.sendaction_status()
        except Exception as e:
            print(e)

    def get_cid(self, cid):
        ass = AsteriskStatus()
        return ass.cid_start(cid)

    def sendaction_status(self):
        try:
            action = SimpleAction('Status')
            future = self.client.send_action(action)
        except Exception as e:
            print(e)

    def connection_listener(self, event, **kwargs):
        try:
            if event.name not in [
                    'PeerStatus', 'RTCPSent', 'VarSet', 'Registry'
            ]:
                print(f"callback: {event.name}")
            if event.name == 'FullyBooted':
                #print("---===Started===---")
                self.isconnected = True
            elif event.name == 'Shutdown':
                #print("This is shuting down!!!")
                self.isconnected = False
            elif event.name == 'Status':
                self.tmp_events.append(event)
            elif event.name == 'StatusComplete':
                for num, event in enumerate(self.tmp_events):
                    self.tmp_events[num]['chan_re'] = event['Channel']
                    ass = re.match(r'\w*\/(\S*)-\w*', event['Channel'])
                    if ass is not None:
                        self.tmp_events[num]['chan_re'] = ass.group(1)
                self.events = self.link_events(self.tmp_events)
                self.tmp_events = []
            elif event.name in [
                    'Newstate', 'HangupRequest', 'DialEnd', 'Hangup',
                    'SoftHangupRequest'
            ]:
                self.sendaction_status()
        except Exception as e:
            print(e)

    def link_events(self, events):
        try:
            filtered_events = [
                event for event in events
                if event['Uniqueid'] == event['Linkedid']
            ]
            linked_events = [
                event for event in events
                if event['Uniqueid'] != event['Linkedid']
            ]
            all_event_prints = []

            for filtered_event in filtered_events:
                lines_status = []
                linked = [
                    event for event in linked_events
                    if event['Linkedid'] == filtered_event['Uniqueid']
                ]

                cid_from = self.get_cid(filtered_event['CallerIDNum'])
                cid_to = self.get_cid(filtered_event['Exten'])
                lines_status.append(
                    f"{filtered_event['chan_re']} ({filtered_event['ChannelStateDesc']})"
                )
                for link in linked:
                    lines_status.append(
                        f"{link['chan_re']} ({link['ChannelStateDesc']})")

                cid_from_txt = cid_from if cid_from is not None else filtered_event[
                    'CallerIDNum']
                cid_to_txt = cid_to if cid_to is not None else filtered_event[
                    'Exten']
                lines_status_txt = ', '.join(lines_status)

                out_print = f"{cid_from_txt}->{cid_to_txt} [{lines_status_txt}]"
                all_event_prints.append(out_print)

            if len(all_event_prints) > 0:
                topublish = ', '.join(all_event_prints)
            else:
                topublish = 'idle'
            print(topublish)
            self.mqttc.publish(self.config['mqtt']['topic'],
                               topublish,
                               retain=True)

        except Exception as e:
            print(e)

        return events
Exemplo n.º 17
0
class Worker(object):

    events = []
    PBXClient = None

    def waitEvent(self, timewait=5):
        while not self.events:
            timewait -= 1
            if timewait == 0:
                break
            time.sleep(1)

    def QueryStat(self):
        self.PBXClient = AMIClient(
            address=settings.JSON_SETTINGS['asteriskServer'], port=5038)
        self.PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'],
                             secret=settings.JSON_SETTINGS['AMIPassword'])
        self.events = []
        action = SimpleAction('QueueStatus', )
        #print('hi')
        self.PBXClient.add_event_listener(self.listener,
                                          white_list=['QueueParams'])
        #self.events = ['QueryStat']
        self.PBXClient.send_action(action)
        self.waitEvent()
        self.PBXClient.logoff()
        return self.events

    def QueueAgent(self, Queue):
        self.PBXClient = AMIClient(
            address=settings.JSON_SETTINGS['asteriskServer'], port=5038)
        self.PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'],
                             secret=settings.JSON_SETTINGS['AMIPassword'])
        self.events = []
        action = SimpleAction('QueueStatus', )
        #print('hi')
        #print("Queue: %s" % Queue)
        #q = "'%s'" % Queue
        #print(q)

        self.PBXClient.add_event_listener(self.listener,
                                          white_list=['QueueMember'],
                                          Queue='%s' % Queue)
        #self.events = ['QueryStat']
        self.PBXClient.send_action(action)
        self.waitEvent()
        self.PBXClient.logoff()
        return self.events

    def Queue(self):
        self.PBXClient = AMIClient(
            address=settings.JSON_SETTINGS['asteriskServer'], port=5038)
        self.PBXClient.login(username=settings.JSON_SETTINGS['AMILogin'],
                             secret=settings.JSON_SETTINGS['AMIPassword'])
        self.events = []
        action = SimpleAction('Queues', )
        #print('hi')
        self.PBXClient.add_event_listener(self.listener)
        #self.events = ['QueryStat']
        ans = self.PBXClient.send_action(action)
        self.waitEvent()
        self.PBXClient.logoff()
        return (self.events, ans)

    def GetQuery(self):
        servers = settings.JSON_SETTINGS['MemcachedServers']
        cServers = []
        for server in servers:
            tmp = server.split(':')
            cServers += [(tmp[0], int(tmp[1]))]
        cl = HashClient(cServers)
        q = cl.get('queue')
        if q is None:
            self.QueryStat()
            queue = []
            for event in self.events:
                queue += [event['Queue']]
            cl.set('queue', ','.join(queue),
                   settings.JSON_SETTINGS['MemcachedExpire'])
            return queue
        else:
            return q.decode("utf-8").split(',')

    def listener(self, event, **kwargs):
        #print(event)
        self.events += [event]

    def __del__(self):
        #print("__del__")
        if not self.PBXClient is None:
            self.PBXClient.logoff()
Exemplo n.º 18
0
        return


if __name__ == "__main__":

    def callback_response(event, **kwargs):
        print(event)

    client = AMIClient(address='192.168.0.213', port=5038)
    client.login(username='******', secret='amisecret')

    client.add_event_listener(callback_response,
                              white_list=['CoreShowChannel'])

    action = SimpleAction('CoreShowChannels')
    future = client.send_action(action, callback=callback_response)

    while True:
        time.sleep(1)

    #action = SimpleAction('SIPshowregistry')
    #future = client.send_action(action, callback=callback_response)

    #action = SimpleAction('ExtensionStateList')
    #future = client.send_action(action, callback=callback_response)

#Interessante:
# CoreStatus, CoreSettings
# async: SIPshowregistry
# async: ExtensionStateList
Exemplo n.º 19
0
class AsteriskLogger():
    def __init__(self, host, port, username, secret):
        self.creds = [host, port, username, secret]
        self.plugin_name = "asterisk"
        self.checking_status = False
        self.local_logfile = {}
        self.local_logfile["asterisk-systemstatus"] = {}
        self.init()

    def reinit(self):
        self.init()

    def init(self):
        try:
            self.client = AMIClient(address=self.creds[0], port=self.creds[1])
            self.client.login(username=self.creds[2],
                              secret=self.creds[3])  # TODO: Sicherheitskonzept
            self.push_to_logfile_system_state("status", 1)
        except Exception as e:
            self.push_to_logfile_system_state("status", 0)
            print("Could not init: " + self.plugin_name, e)
            return
        self.client.add_event_listener(self.event_listener_registry,
                                       white_list=['RegistryEntry'])
        self.client.add_event_listener(self.event_listener_extension_status,
                                       white_list=['ExtensionStatus'])
        self.client.add_event_listener(self.general_debug_eventlistener)
        self.checking_status = True
        self.worker = threading.Thread(target=self.worker_loop)
        self.worker.start()

    def worker_loop(self):
        print("Asterisk logging Started!")
        i = 299  # force to save the first
        while (self.checking_status):
            action = SimpleAction('CoreStatus')
            self.client.send_action(action,
                                    callback=self.callback_response_status)
            action = SimpleAction('CoreSettings')
            self.client.send_action(action,
                                    callback=self.callback_response_settings)
            action = SimpleAction('SIPshowregistry')
            self.client.send_action(action)
            time.sleep(0.5)
            action = SimpleAction('ExtensionStateList')
            self.client.send_action(action)
            time.sleep(0.5)

    def get_logfile(self):
        if "running-asterisk-version" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("running-asterisk-version", "-")
        if "running-manager-version" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("running-manager-version", "-")
        if "act-current-calls" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("act-current-calls", "-")
        if "last-core-reload" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("last-core-reload", "-")
        if "last-core-restart" not in self.local_logfile[
                "asterisk-systemstatus"]:
            self.push_to_logfile_system_state("last-core-restart", "-")

        return self.local_logfile

    def create_timestamp_from_strings(self, date, time):
        date_parts = date.split("-")
        time_parts = time.split(":")
        return datetime.datetime(int(date_parts[0]), int(date_parts[1]),
                                 int(date_parts[2]), int(time_parts[0]),
                                 int(time_parts[1]),
                                 int(time_parts[2])).timestamp()

    def callback_response_status(self, response):
        reload_time = response.keys.get("CoreReloadTime", None)
        reload_date = response.keys.get("CoreReloadDate", None)
        if reload_date is not None and reload_time is not None:
            self.push_to_logfile_system_state(
                "last-core-reload",
                self.create_timestamp_from_strings(reload_date, reload_time))

        startup_time = response.keys.get("CoreStartupTime", None)
        startup_date = response.keys.get("CoreStartupDate", None)
        if startup_time is not None and startup_date is not None:
            self.push_to_logfile_system_state(
                "last-core-restart",
                self.create_timestamp_from_strings(startup_date, startup_time))

        current_calls = response.keys.get("CoreCurrentCalls", None)
        if current_calls is not None:
            self.push_to_logfile_system_state("act-current-calls",
                                              current_calls)

    def callback_response_settings(self, response):
        version = response.keys.get("AsteriskVersion", None)
        if version is not None:
            self.push_to_logfile_system_state("running-asterisk-version",
                                              version)

        ami_version = response.keys.get("AMIversion", None)
        if ami_version is not None:
            self.push_to_logfile_system_state("running-manager-version",
                                              ami_version)

    def push_to_logfile_trunk(self, trunkname, user, state):
        self.local_logfile["timestamp"] = time.time()
        if self.local_logfile["trunk-status"].get(trunkname + "-" + user,
                                                  None) is None:
            self.local_logfile["trunk-status"][trunkname + "-" + user] = {}
        if state == "Registered":
            self.local_logfile["trunk-status"][trunkname + "-" +
                                               user]["status"] = 1
        else:
            self.local_logfile["trunk-status"][trunkname + "-" +
                                               user]["status"] = 0

        self.local_logfile["trunk-status"][trunkname + "-" +
                                           user]["trunkname"] = trunkname
        self.local_logfile["trunk-status"][trunkname + "-" +
                                           user]["user"] = user

    def push_to_logfile_system_state(self, varname, state):
        self.local_logfile["timestamp"] = time.time()
        self.local_logfile["asterisk-systemstatus"][varname] = state

    def push_to_logfile_user(self, exten, status, hint):
        self.local_logfile["timestamp"] = time.time()
        if self.local_logfile["trunk-status"].get(exten, None) is None:
            self.local_logfile["asterisk-user-status"][exten] = {}
        self.local_logfile["asterisk-user-status"][exten]["status"] = status
        self.local_logfile["asterisk-user-status"][exten]["hint"] = hint

    def event_listener_registry(self, event, **kwargs):
        trunk_domain = event.keys.get("Domain", None)
        trunk_user = event.keys.get("Username", None)
        trunk_status = event.keys.get("State", None)
        if trunk_domain is not None and trunk_user is not None and trunk_status is not None:
            self.push_to_logfile_trunk(trunk_domain, trunk_user, trunk_status)

    def event_listener_extension_status(self, event, **kwargs):
        status = event.keys.get("Status", None)
        exten = event.keys.get("Exten", None)
        hint = event.keys.get("Hint", None)
        if status is not None and exten is not None and hint is not None:
            self.push_to_logfile_user(exten, status, hint)

    def general_debug_eventlistener(self, event, **kwargs):
        return