Beispiel #1
0
    def kick_member(self, confno, usernumber):

        if not (IsInt(confno)):
            return None

        try:
            manager = Manager(*Config().get_connection())
            print "meetme kick " + str(confno) + " " + str(usernumber)
            action_result = manager.Command("meetme kick " + str(confno) +
                                            " " + str(usernumber))
        except:
            return None
Beispiel #2
0
    def invite_member(self, invite_callerid, invite_route, confno,
                      phonenumber):

        if not (IsInt(confno)):
            return None

        if not (IsInt(phonenumber)):
            return None

        channel = invite_route + phonenumber
        context = "meetme_context"
        extension = confno
        priority = "1"
        application = None
        data = None
        #application = "MeetMe";
        #data = confno+",dT";
        timeout = "30000"
        variable = ""
        account = ""
        async = True

        try:
            manager = Manager(*Config().get_connection())
            action_result = manager.Originate(channel, context, extension,
                                              priority, application, data,
                                              timeout, invite_callerid,
                                              variable, account, async)
        except:
            raise
Beispiel #3
0
 def connect_ami(self):
     try:
         manager = Manager((self.host, self.port),
                           self.user, self.password)
         return manager
     except BaseException:
         return None
Beispiel #4
0
    def conference_member(self, confno):

        if (sample):
            obj_list = []

            for i in range(1, random.randrange(9, 10)):
                obj_conf_list = self.create_member(i)
                obj_list.append(obj_conf_list)

            return obj_list

        if not (IsInt(confno)):
            return None

        try:
            manager = Manager(*Config().get_connection())
            conflist = manager.Command("meetme list " + str(confno) +
                                       " concise")
        except:
            #print "There is an error!"
            return None
        else:

            obj_list = []
            for x, val in enumerate(conflist):
                if (val.find('!') <> -1):
                    sp_list = val.split('!')
                    obj_conf_list = dict()
                    obj_conf_list['callerno'] = sp_list[0]
                    obj_conf_list['cid_number'] = sp_list[1]
                    obj_conf_list['cid_name'] = sp_list[2]
                    obj_conf_list['channel'] = sp_list[3]
                    obj_conf_list['user_type'] = sp_list[4]
                    obj_conf_list['monitor'] = sp_list[5]
                    obj_conf_list['muted'] = sp_list[6]
                    obj_conf_list['floor'] = sp_list[7]
                    obj_conf_list['istalking'] = sp_list[8]
                    obj_conf_list['callduration'] = sp_list[9]

                    obj_list.append(obj_conf_list)

            return obj_list
Beispiel #5
0
 def loop(self):
     while True:
         try:
             # Create PBX connection
             self.pbx = Manager((self.host, int(self.port)), self.username,
                                self.password)
             _logger.info('Connected to {}'.format(self.host))
             self.register(self.pbx)
             self.pbx.serve_forever()
         except socket.error as e:
             _logger.error('Server {} socket error: {}.'.format(
                 self.host, e.strerror))
         except Asterisk.BaseException as e:
             _logger.error('Server {} error, {}.'.format(self.host, e))
         except ConnectionError as e:
             _logger.error('Server {} connection error, {}.'.format(
                 self.host, e))
         except:
             raise
         _logger.info(
             'Reconnecting in {} seconds...'.format(AMI_RECONNECT_TIMEOUT))
         gevent.sleep(AMI_RECONNECT_TIMEOUT)
Beispiel #6
0
    def conference_list(self):

        if (sample):
            obj_list = []

            obj_conf_list = dict()
            obj_conf_list['confno'] = '400'
            obj_conf_list['member'] = str(random.randrange(1, 10))
            obj_conf_list['activity'] = '1'
            obj_list.append(obj_conf_list)

            obj_conf_list = dict()
            obj_conf_list['confno'] = '5000'
            obj_conf_list['member'] = str(random.randrange(1, 10))
            obj_conf_list['activity'] = '1'
            obj_list.append(obj_conf_list)

            return obj_list

        try:
            manager = Manager(*Config().get_connection())
            conflist = manager.Command("meetme list concise")
        except:
            #print "There is an error!"
            return None
        else:

            obj_list = []
            for x, val in enumerate(conflist):
                if (val.find('!') <> -1):
                    sp_list = val.split('!')
                    obj_conf_list = dict()
                    obj_conf_list['confno'] = sp_list[0]
                    obj_conf_list['member'] = sp_list[1]
                    obj_conf_list['activity'] = sp_list[1]

                    obj_list.append(obj_conf_list)

            return obj_list
Beispiel #7
0
def start():
    _logger.info('Starting AMI broker...')
    setproctitle.setproctitle('ami_broker')
    global odoo
    odoo = get_odoo_connection()
    pbx = Manager((conf['host'], int(conf['ami_port'])), conf['ami_username'],
                  conf['ami_password'])
    ami_events = AmiEvents()
    ami_events.register(pbx)
    try:
        h1 = gevent.spawn(pbx.serve_forever)
        _logger.info('AMI broker has been started.')
        gevent.joinall([h1])
    except KeyboardInterrupt, SystemExit:
        _logger.info('AMI broker has been terminated.')
Beispiel #8
0
 def getConnectin(self):
     return Manager((SETTINGS["host"], SETTINGS["port"]),
                    SETTINGS["login"],
                    SETTINGS["password"],
                    listen_events=True)
Beispiel #9
0
try:
    log("Running in background...")
    settings = xbmcaddon.Addon(__addon_id__)
    DEBUG = settings.getSetting("xbmc_debug")
    xbmc_bgservice = settings.getSetting("xbmc_bgservice")
    manager_host_port = settings.getSetting("asterisk_manager_host"),int(settings.getSetting("asterisk_manager_port"))
    manager_user = settings.getSetting("asterisk_manager_user")
    manager_pass = settings.getSetting("asterisk_manager_pass")
    vm = settings.getSetting("asterisk_vm_mailbox") +"@"+ settings.getSetting("asterisk_vm_context")
    arr_timeout = [5,10,15,20,25,30]
    xbmc_vm_notification_timeout = int(arr_timeout[int(settings.getSetting("xbmc_vm_notification_timeout"))])
    del settings
    if (xbmc_bgservice == "true"):
        log(">> Background service is disabled.")
    else:
        pbx = Manager(manager_host_port,manager_user,manager_pass)
        asterisk_version = str(pbx.Command("core show version")[1])
        asterisk_series = asterisk_version[9:12]
        log(">> Asterisk " + asterisk_series)
        if (DEBUG == "true"): log(">> " + asterisk_version)
        vm_count = str(pbx.MailboxCount(vm)[0])
        xbmc_notification = __language__(30053) + vm_count
        xbmc_img = xbmc.translatePath(os.path.join(RESOURCE_PATH,'media','xbmc-pbx-addon.png'))
        log(">> Notification: " + xbmc_notification)
        xbmc.executebuiltin("XBMC.Notification("+ __language__(30052) +","+ xbmc_notification +","+ str(xbmc_vm_notification_timeout*1000) +","+ xbmc_img +")")
        grab = get_incoming_call()
        pbx.events += grab.events
        pbx.serve_forever()
except:
    xbmc_notification = str(sys.exc_info()[1])
    xbmc_img = xbmc.translatePath(os.path.join(RESOURCE_PATH,'media','xbmc-pbx-addon.png'))
Beispiel #10
0
class ServerAmiManager(object):
    #cmd_Q = Queue()

    def __init__(self, server_id, host, port, username, password):
        self.server_id = server_id
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        # Start the command Q
        # Populate events
        self.events = Asterisk.Util.EventCollection()
        self.events.subscribe('VarSet', self.handle_event)
        self.events.subscribe('Hangup', self.handle_event)
        self.events.subscribe('PeerStatus', self.handle_event)
        self.events.subscribe('Newchannel', self.handle_event)
        self.events.subscribe('NewExten', self.handle_event)
        self.events.subscribe('NewConnectedLine', self.handle_event)
        self.events.subscribe('Newstate', self.handle_event)

    def register(self, pbx):
        pbx.events += self.events

    def unregister(self, pbx):
        pbx.events -= self.events

    def handle_event(self, pbx, event):
        # General method to spawn event handlres.
        # Search for method named on_EventName
        event_handler = getattr(self, 'on_{}'.format(event.get('Event')), None)
        if event_handler:
            gevent.spawn(event_handler, pbx, event)

    """
    def handle_cmd_Q(self):
        while True:
            try:
                msg = self.cmd_Q.get_nowait()
            except Empty:
                gevent.sleep(1)
                continue
            command = msg.get('command')
            method = getattr(self, 'command_' + command, None)
            if method:
                _logger.debug('Q got {}'.format(method))
                method(msg)
            else:
                _logger.error('Method {} not found.'.format(command))
            gevent.sleep(1)
    """

    def loop(self):
        while True:
            try:
                # Create PBX connection
                self.pbx = Manager((self.host, int(self.port)), self.username,
                                   self.password)
                _logger.info('Connected to {}'.format(self.host))
                self.register(self.pbx)
                self.pbx.serve_forever()
            except socket.error as e:
                _logger.error('Server {} socket error: {}.'.format(
                    self.host, e.strerror))
            except Asterisk.BaseException as e:
                _logger.error('Server {} error, {}.'.format(self.host, e))
            except ConnectionError as e:
                _logger.error('Server {} connection error, {}.'.format(
                    self.host, e))
            except:
                raise
            _logger.info(
                'Reconnecting in {} seconds...'.format(AMI_RECONNECT_TIMEOUT))
            gevent.sleep(AMI_RECONNECT_TIMEOUT)

    def update_qos(self, pbx, event):
        # We have to give CDR some time to get into the database.
        # Odoo may not complete a WEB transaction so no record will be found to update.
        gevent.sleep(UPDATE_CDR_DELAY)
        value = event.get('Value')
        pairs = [k for k in value.split(';') if k]
        values = {}
        for pairs in pairs:
            k, v = pairs.split('=')
            values.update({k: v})
        values.update({
            'uniqueid': event.get('Uniqueid'),
            'linkedid': event.get('Linkedid')
        })
        return odoo.env['asterisk.cdr'].update_qos(values)

    def update_channel_state(self, pbx, event):
        gevent.sleep(UPDATE_CHANNEL_DELAY)
        # Take the Channel from the message to make it serializable.
        channel = event.pop('Channel')
        event['Channel'] = '{}'.format(channel)
        return odoo.env['asterisk.channel'].update_channel_state(event)

    def hangup_channel(self, pbx, event):
        gevent.sleep(UPDATE_CHANNEL_DELAY)
        # Take the Channel from the message to make it serializable.
        channel = event.pop('Channel')
        event['Channel'] = '{}'.format(channel)
        return odoo.env['asterisk.channel'].hangup_channel(event)

    def get_call_recording(pbx, event):
        _logger.debug('Get call recording.')
        # Make a delay to let Asterisk close recorded file.
        gevent.sleep(RECORDING_DOWNLOAD_DELAY)
        call_id = event.get('Uniqueid')
        exten = event.get('Exten')
        # Download recording
        url = 'http://{}:{}/static/monitor/{}.wav'.format(
            conf['host'], conf['http_port'], call_id)
        response = requests.get(url)
        if response.status_code == 404:
            _logger.info(
                'Recording for {} not found on the server.'.format(exten))
        elif response.status_code == 200:
            _logger.debug('Recording found, process.')
            file_data = response.content
            upload_complete = False
            try:
                result = odoo.env['asterisk.cdr'].save_call_recording(
                    call_id, base64.encodestring(file_data))
                if not result:
                    _logger.error('Odoo save_call_recording result is False.')
                else:
                    _logger.debug('Call recording saved.')
                    upload_complete = True
            except odoorpc.error.RPCError as e:
                _logger.error('Odoo error: {}'.format(e.message))
            # Delete recording
            url = urlparse.urljoin(
                ASTERISK_HELPER_URL,
                '/delete_recording?filename={}.wav'.format(call_id))
            _logger.debug('Calling {}'.format(url))
            response = requests.get(url)
            if response.content != 'DELETED':
                _logger.warning('Bad response: {}'.format(response.content))
        else:
            _logger.warn(
                'Unhandled status code {} received from the server.'.format(
                    response.status_code))

    def on_Hangup(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        # Spawn call recording handling.
        gevent.spawn(self.hangup_channel, pbx, event)
        gevent.spawn(self.get_call_recording, event)

    def on_VarSet(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        # QoS of CDR
        var = event.get('Variable')
        if var == 'RTPAUDIOQOS':
            return self.update_qos(pbx, event)
        else:
            _logger.debug('Ignoring SetVar {}.'.format(var))

    def on_PeerStatus(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        if event.get('ChannelType') == 'SIP':
            # We only care about SIP registrations
            return odoo.env['asterisk.sip_peer_status'].update_status(event)

    def on_Newchannel(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        # Get channel represenation of Channel object.
        channel = event.pop('Channel')
        event['Channel'] = '{}'.format(channel)
        return odoo.env['asterisk.channel'].new_channel(event)

    def on_Newstate(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        return self.update_channel_state(pbx, event)

    def on_NewExten(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        return self.update_channel_state(pbx, event)

    def on_NewConnectedLine(self, pbx, event):
        _logger.debug('on_{}'.format(event.get('Event')))
        return self.update_channel_state(pbx, event)
Beispiel #11
0
 def on_Event(self, Event):
     # print repr(Event)
     Manager.on_Event(self, Event)
Beispiel #12
0
try:
    log("Running in background...")
    settings = xbmcaddon.Addon(__addon_id__)
    DEBUG = settings.getSetting("xbmc_debug")
    xbmc_bgservice = settings.getSetting("xbmc_bgservice")
    manager_host_port = settings.getSetting("asterisk_manager_host"),int(settings.getSetting("asterisk_manager_port"))
    manager_user = settings.getSetting("asterisk_manager_user")
    manager_pass = settings.getSetting("asterisk_manager_pass")
    vm = settings.getSetting("asterisk_vm_mailbox") +"@"+ settings.getSetting("asterisk_vm_context")
    arr_timeout = [5,10,15,20,25,30]
    xbmc_vm_notification_timeout = int(arr_timeout[int(settings.getSetting("xbmc_vm_notification_timeout"))])
    del settings
    if (xbmc_bgservice == "true"):
        log(">> Background service is disabled.")
    else:
        pbx = Manager(manager_host_port,manager_user,manager_pass)
        asterisk_version = str(pbx.Command("core show version")[1])
        asterisk_series = asterisk_version[9:12]
        log(">> Asterisk " + asterisk_series)
        if (DEBUG == "true"): log(">> " + asterisk_version)
        vm_count = str(pbx.MailboxCount(vm)[0])
        xbmc_notification = unicode(__language__(30053) + vm_count)
        xbmc_img = xbmc.translatePath(os.path.join(RESOURCE_PATH,'media','xbmc-pbx-addon.png'))
        log(">> Notification: " + xbmc_notification)
        xbmc.executebuiltin("XBMC.Notification("+ __language__(30052) +","+ xbmc_notification +","+ str(xbmc_vm_notification_timeout*1000) +","+ xbmc_img +")")
        grab = get_incoming_call()
        pbx.events += grab.events
        while (not xbmc.abortRequested):
            pbx.read()
except:
    xbmc_notification = unicode(str(sys.exc_info()[1]))
Beispiel #13
0
        self.events.subscribe('VarSet', self.new_event)


    def register(self, pbx):
        pbx.events += self.events


    def unregister(self, pbx):
        pbx.events -= self.events



def handle_message(message):
    # We have to give CDR some time to get into the database.
    # Actually we do not hurry at all. We just make a delay
    gevent.sleep(SLEEP)
    logger.debug(message)
    odoo_rpc('asterisk.cdr', 'log_qos', [message], {})



pbx = Manager((conf['pbx_host'], conf['pbx_port']),
              conf['pbx_user'], conf['pbx_password'])


qos_events = QosEvents()
qos_events.register(pbx)
h1 = gevent.spawn(pbx.serve_forever)
gevent.joinall([h1])

Beispiel #14
0
#!/root/venv/odoo/bin/python
from gevent import monkey
monkey.patch_all()
import gevent
import logging
from Asterisk.Manager import Manager
from flask import Flask, jsonify
from gevent.wsgi import WSGIServer

logger = logging.getLogger('broker.py')
app = Flask(__name__)
http_server = WSGIServer(('localhost', 5000), app)
pbx = Manager(('localhost', 5038), 'user', '12341234')


@app.route('/reload')
def asterisk_reload():
    logger.info('running AMI command reload')
    result = pbx.Command('reload')
    return jsonify(result)


if __name__ == '__main__':
    logger.info('Broker started')
    flask_instance = gevent.spawn(http_server.serve_forever)
    #pbx_instance = gevent.spawn(pbx.serve_forever)
    gevent.joinall([flask_instance])