Exemplo n.º 1
0
def page_channel(feature_code):

    try:
        # connect to the manager
        try:
            manager.connect(CONNECT_IP)
            manager.login(LOGIN_UN, LOGIN_PW)

            # get a status report
            response = manager.status()
            #print(response)
            # Logic to do the dialing
            response = manager.command(
                'channel originate Local/*{0}@app-miscapps extension {1}@ext-paging'
                .format(feature_code, PAGING_GROUP))
            #print(response.data)

            manager.logoff()
        except asterisk.manager.ManagerSocketException as e:
            print("Error connecting to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerAuthException as e:
            print("Error logging in to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerException as e:
            print("Error: %s") % e.strerror
            sys.exit(1)

    finally:
        # remember to clean up
        manager.close()
Exemplo n.º 2
0
def _do_command_safety(manager: asterisk.manager.Manager,
                       command_to_asterisk: str) -> tuple:
    """
    Trying send command to an asterisk and receiving an answer,
        if got error will create new connection to the asterisk and do same

    :return: tuple : where
        0 - asterisk.manager.Manager;
        1 - result of executing command by asterisk
    """
    while True:
        try:
            if manager.connected():
                response = manager.command(command_to_asterisk)

                return manager, response

        except asterisk.manager.ManagerException as e:
            logger.error("command safety Error: %s" % e)
            try:
                manager.logoff()
            except asterisk.manager.ManagerException as e:
                logger.error("logoff Error: %s" % e)
            finally:
                manager.close()
                logger.info('manager.close()')
                manager = _connect_to_ami()
                logger.info('new manager')
Exemplo n.º 3
0
def _do_command_safety(manager: asterisk.manager.Manager,
                       command_to_asterisk: str) -> tuple:
    """
    Trying send command to an asterisk and receiving an answer,
        if got error will create new connection to the asterisk and do same

    :return: tuple : where
        0 - asterisk.manager.Manager;
        1 - result of executing command by asterisk
    """
    while True:
        try:
            if manager.connected():
                response = manager.command(command_to_asterisk)

                return manager, response

        except asterisk.manager.ManagerException as e:
            logger.error("command safety Error: %s" % e)
            try:
                manager.logoff()
            except asterisk.manager.ManagerException as e:
                logger.error("logoff Error: %s" % e)
            finally:
                manager.close()
                logger.info('manager.close()')
                manager = _connect_to_ami()
                logger.info('new manager')
Exemplo n.º 4
0
def page_channel(feature_code):

    try:
        # connect to the manager
        try:
            manager.connect(CONNECT_IP)
            manager.login(LOGIN_UN, LOGIN_PW)

            # get a status report
            response = manager.status()
            # print(response)
            # Logic to do the dialing
            response = manager.command(
                "channel originate Local/*{0}@app-miscapps extension {1}@ext-paging".format(feature_code, PAGING_GROUP)
            )
            # print(response.data)

            manager.logoff()
        except asterisk.manager.ManagerSocketException as e:
            print("Error connecting to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerAuthException as e:
            print("Error logging in to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerException as e:
            print("Error: %s") % e.strerror
            sys.exit(1)

    finally:
        # remember to clean up
        manager.close()
Exemplo n.º 5
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
                      item.service, item.target)

    host = item.config['host']
    port = item.config['port']
    username = item.config['username']
    password = item.config['password']
    extension = item.config['extension']
    context = item.config['context']

    gateway = item.addrs[0]
    number = item.addrs[1]
    title = item.title
    message = item.message

    try:
        manager = asterisk.manager.Manager()
        manager.connect(host, port)
        response = manager.login(username, password)
        srv.logging.debug("Authentication {}".format(response))
        channel = gateway + number
        channel_vars = {'text': message}
        # originate the call
        response = manager.originate(channel,
                                     extension,
                                     context=context,
                                     priority='1',
                                     caller_id=extension,
                                     variables=channel_vars)
        srv.logging.info("Call {}".format(response))
        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        srv.logging.error("Error connecting to the manager: {}".format(e))
        return False
    except asterisk.manager.ManagerAuthException as e:
        srv.logging.error("Error logging in to the manager: {}".format(e))
        return False
    except asterisk.manager.ManagerException as e:
        srv.logging.error("Error: {}".format(e))
        return False

    # Remember to clean up
    finally:
        try:
            manager.close()
        except asterisk.manager.ManagerSocketException:  # pragma: no cover
            pass

    return True
Exemplo n.º 6
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    host     = item.config['host']
    port = item.config['port']
    username = item.config['username']
    password = item.config['password']
    extension = item.config['extension']
    context  = item.config['context']
 
    gateway  = item.addrs[0]
    number   = item.addrs[1]    
    title    = item.title
    message  = item.message

    try:
        manager = asterisk.manager.Manager()
        manager.connect(host, port)
        response = manager.login(username, password)
        srv.logging.debug("Authentication {}".format(response))
        channel = gateway + number
        channel_vars = {'text': message}
        # originate the call
        response = manager.originate(channel, extension, context=context, priority='1', caller_id=extension, variables=channel_vars)
        srv.logging.info("Call {}".format(response))
        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        srv.logging.error("Error connecting to the manage: {}".format(e))
    except asterisk.manager.ManagerAuthException as e:
        srv.logging.error("Error logging in to the manager: {}".format(e))
    except asterisk.manager.ManagerException as e:
        srv.logging.error("Error: {}".format(e))

    finally:
    # remember to clean up
        try:
            manager.close()
        except asterisk.manager.ManagerSocketException:
            pass
    
    return True
Exemplo n.º 7
0
def handle_shutdown(event, manager):
    print "Recieved shutdown event"
    manager.close()
Exemplo n.º 8
0
try:
    try:
        manager.connect(config.get('AMI', 'host'))
        manager.login(config.get('AMI', 'username'),
                      config.get('AMI', 'password'))

        manager.register_event('Shutdown', handle_shutdown)
        manager.register_event('Newstate', handle_newstate)
        manager.register_event('Hangup', handle_hangup)
        manager.register_event('Link', handle_link)
        manager.register_event('Unlink', handle_unlink)
        manager.register_event('Dial', handle_dial)
        #manager.register_event('Newstate', handle_newstate)
        #manager.register_event('*', handle_event)

        manager.message_loop()

        manager.logoff()

    except asterisk.manager.ManagerSocketException, (errno, reason):
        print "Error connecting to the manager: %s" % reason

    except asterisk.manager.ManagerAuthException, reason:
        print "Error logging in to the manager: %s" % reason

    except asterisk.manager.ManagerException, reason:
        print "Error: %s" % reason

finally:
    manager.close()
Exemplo n.º 9
0
	def handle_shutdown(self, event, manager):
		print "Received shutdown event"
		manager.close()
Exemplo n.º 10
0
def send_sms(*args, **kwargs):
    sms_pk = kwargs.get('sms_pk')

    try:
        print('sms_pk: ', sms_pk)
        sms = SMS.objects.get(pk=sms_pk, is_send=False, )
    except SMS.DoesNotExist:
        return False

    manager = asterisk.manager.Manager()

    try:
        # connect to the manager
        try:
            manager.connect(proj.settings.ASTERISK_HOST)
            manager.login(*proj.settings.ASTERISK_AUTH)

            # get a status report
            response = manager.status()
            print('response: ', response)

            response = manager.command('core show channels concise')
            print('response.data: ', response.data)

            response = manager.command('dongle show version')
            print('response.data: ', response.data)

            response = manager.command('dongle show devices')
            print('response.data: ', response.data)

            response = manager.command('dongle ussd Vodafone1 *161#')
            print('response.data: ', response.data)

            response = manager.command('dongle show device settings')
            print('response.data: ', response.data)

            response = manager.command('dongle show device state')
            print('response.data: ', response.data)

            response = manager.command('dongle show device statistics')
            print('response.data: ', response.data)

            manager.logoff()

        except asterisk.manager.ManagerSocketException as e:
            print "Error connecting to the manager: %s" % e
        except asterisk.manager.ManagerAuthException as e:
            print "Error logging in to the manager: %s" % e
        except asterisk.manager.ManagerException as e:
            print "Error: %s" % e

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print e

    sms.task_id = None
    sms.is_send = True
    sms.send_at = timezone.now()
    sms.save(skip_super_save=True, )

    print('increase_send_sms(): ', increase_send_sms())

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 11
0
def send_template_sms(*args, **kwargs):

    to_phone_char = kwargs.pop('sms_to_phone_char', False, )
    print('sms_to_phone_char: ', to_phone_char)
    if not to_phone_char:
        return False

    template_name = kwargs.pop('sms_template_name', False, )
    try:
        print('template_name: ', template_name)
        teplate = Template.objects.get(name=template_name, )
    except Template.DoesNotExist:
        return False

    template_dict = {}
    print '203', template_dict
    for key, value in kwargs.iteritems():
        print '205', key, value
        if key.startswith('sms_'):
            print '207', "key.lstrip('sms_')", key.lstrip('sms_')
            print '208', template_dict
            template_dict.update({key.lstrip('sms_'): value})
            print '210', template_dict

    message = teplate.template.format(**template_dict)
    print message

    manager = asterisk.manager.Manager()

    try:
        # connect to the manager
        try:
            manager.connect(proj.settings.ASTERISK_HOST)
            manager.login(*proj.settings.ASTERISK_AUTH)

            # get a status report
            response = manager.status()
            print('response: ', response)

            response = manager.command('core show channels concise')
            print('response.data: ', response.data)

            response = manager.command('dongle show version')
            print('response.data: ', response.data)

            response = manager.command('dongle show devices')
            print('response.data: ', response.data)

            response = manager.command('dongle ussd Vodafone1 *161#')
            print('response.data: ', response.data)

            response = manager.command('dongle show device settings')
            print('response.data: ', response.data)

            response = manager.command('dongle show device state')
            print('response.data: ', response.data)

            response = manager.command('dongle show device statistics')
            print('response.data: ', response.data)

            response = manager.command(u'dongle sms {device} {to_phone_char} {message}'
                                       .format(
                                            device='Vodafone2',
                                            to_phone_char=to_phone_char,
                                            message=message,
                                        ),
            )
            print('response.data: ', response.data)

            manager.logoff()

        except asterisk.manager.ManagerSocketException as e:
            print "Error connecting to the manager: %s" % e
        except asterisk.manager.ManagerAuthException as e:
            print "Error logging in to the manager: %s" % e
        except asterisk.manager.ManagerException as e:
            print "Error: %s" % e

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print e

    sms = SMS(template=teplate,
              direction=2,
              task_id=None,
              is_send=True,
              to_phone_char=to_phone_char,
              message=message,
              send_at=timezone.now(),
              )
    sms.save(skip_super_save=True, )

    print('increase_send_sms(): ', increase_send_sms())

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 12
0
def handle_shutdown(event, manager):
   manager.close()
Exemplo n.º 13
0
def handle_shutdown(event, manager):
    print "Recieved shutdown event"
    manager.close()
Exemplo n.º 14
0
def send_sms(*args, **kwargs):
    sms_pk = kwargs.get('sms_pk')

    try:
        sms_inst = SMS.objects.get(
            pk=sms_pk,
            is_send=False,
        )
    except SMS.DoesNotExist:
        return False

    manager = asterisk.manager.Manager()

    # connect to the manager
    try:
        manager.connect(settings.ASTERISK_HOST)
        manager.login(*settings.ASTERISK_AUTH)

        # get a status report
        response = manager.status()
        print('print: response: ', response)
        logger.info('logger: response: %s' % response)
        # Success
        number = '+380{code}{phone}'\
            .format(
                code=sms_inst.to_code,
                phone=sms_inst.to_phone,
            )

        sms_to_pdu = SmsSubmit(
            number=number,
            text=sms_inst.message,
        )

        sms_to_pdu.request_status = True
        sms_to_pdu.validity = timedelta(days=2)
        sms_list = sms_to_pdu.to_pdu()

        # last_loop = len(sms_list) - 1
        for i, pdu_sms in enumerate(sms_list):
            time.sleep(0.5)
            response = manager.command(
                'dongle pdu {device} {pdu}'.format(
                    device='Vodafone1',
                    pdu=pdu_sms.pdu,
                ), )
            print('print: response.data: ', response.data)
            logger.info('logger: response.data: %s' % response.data)
            # [Vodafone1] SMS queued for send with id 0x7f98c8004420\n--END COMMAND--\r\n
            sended_sms = increase_send_sms()
            print('print: sended SMS: ', sended_sms)
            logger.info('logger: sended SMS: %s' % sended_sms)
            # if i != last_loop:
            #     time.sleep(1.5)
            time.sleep(0.5)

        manager.logoff()

    except asterisk.manager.ManagerSocketException as e:
        print("Error connecting to the manager: %s" % e, )
    except asterisk.manager.ManagerAuthException as e:
        print("Error logging in to the manager: %s" % e, )
    except asterisk.manager.ManagerException as e:
        print("Error: %s" % e, )

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print('print: sms_ussd/task.py: e: ', e)
            logger.info('logger: sms_ussd/task.py: e: %s' % e)

    sms_inst.task_id = None
    sms_inst.is_send = True
    sms_inst.send_at = timezone.now()
    sms_inst.save(skip_super_save=True, )

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 15
0
def send_template_sms(*args, **kwargs):

    phone = kwargs.pop(
        'sms_to_phone_char',
        False,
    )
    if not phone:
        return False

    phone = phone.replace(' ', '').strip('+') \
        .replace('(', '').replace(')', '').replace('-', '') \
        .lstrip('380').lstrip('38').lstrip('80').lstrip('0')

    try:
        int_phone = int(phone[2:])
        int_code = int(phone[:2])
    except ValueError:
        return False

    template_name = kwargs.pop(
        'sms_template_name',
        False,
    )
    try:
        template = Template.objects.get(name=template_name, )
    except Template.DoesNotExist:
        return False

    template_dict = {}

    for key, value in kwargs.items():

        if key.startswith('sms_'):

            template_dict.update({key.lstrip('sms_'): value})

    message = template.template.format(**template_dict)

    sms_inst = SMS(
        template=template,
        direction=2,
        task_id=None,
        sim_id=255016140761290,
        is_send=True,
        message=message,
        to_phone_char=phone,
        to_code=int_code,
        to_phone=int_phone,
        send_at=timezone.now(),
    )

    manager = asterisk.manager.Manager()

    # connect to the manager
    try:
        manager.connect(settings.ASTERISK_HOST)
        manager.login(*settings.ASTERISK_AUTH)

        # get a status report
        response = manager.status()
        print('response: ', response)

        number = '+380{code}{phone}'\
            .format(
                code=sms_inst.to_code,
                phone=sms_inst.to_phone,
            )

        sms_to_pdu = SmsSubmit(
            number=number,
            text=sms_inst.message,
        )

        sms_to_pdu.request_status = False
        sms_to_pdu.validity = timedelta(days=2)
        sms_list = sms_to_pdu.to_pdu()

        # last_loop = len(sms_list) - 1
        for i, pdu_sms in enumerate(sms_list):
            time.sleep(0.5)
            response = manager.command(
                'dongle pdu {device} {pdu}'.format(
                    device='Vodafone1',
                    pdu=pdu_sms.pdu,
                ), )
            print('print: response.data: ', response.data)
            logger.info('logger: response.data: %s' % response.data)
            # [Vodafone1] SMS queued for send with id 0x7f98c8004420\n--END COMMAND--\r\n
            sended_sms = increase_send_sms()
            print('print: sended SMS: ', sended_sms)
            logger.info('logger: sended SMS: %s' % sended_sms)
            # if i != last_loop:
            #     time.sleep(1.5)
            time.sleep(0.5)

        manager.logoff()

    except asterisk.manager.ManagerSocketException as e:
        print("Error connecting to the manager: %s" % e, )
    except asterisk.manager.ManagerAuthException as e:
        print("Error logging in to the manager: %s" % e, )
    except asterisk.manager.ManagerException as e:
        print("Error: %s" % e, )

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print(
                'sms_ussd/tasks.py: e: ',
                e,
            )

    sms_inst.save(skip_super_save=True, )

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 16
0
def handle_shutdown(event, manager):
    manager.close()
Exemplo n.º 17
0
manager = asterisk.manager.Manager()

try:
    # connect to the manager
    try:
        manager.connect('localhost')
        manager.login('user', 'secret')

        # get a status report
        response = manager.status()
        print(response)
        
        response = manager.command('core show channels concise')
        print(response.data)

        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        print "Error connecting to the manager: %s" % e.strerror
        sys.exit(1)
    except asterisk.manager.ManagerAuthException as e:
        print "Error logging in to the manager: %s" % e.strerror
        sys.exit(1)
    except asterisk.manager.ManagerException as e:
        print "Error: %s" % e.strerror
        sys.exit(1)

finally:
    # remember to clean up
    manager.close()

Exemplo n.º 18
0
 def handle_shutdown(self, event, manager):
     print "Received shutdown event"
     manager.close()