예제 #1
0
    def __init__(self,
                 server=None,
                 lower_port=8056,
                 upper_port=8057,
                 testing=False):
        self.server_details = dict()
        self.freeswitch_simulator_url = "http://localhost:1611/originate_call/1111"
        self.testing = testing
        self.redis_wanpipe_key = "wan_pipes"
        self.server_details["server_private_address"] = server
        self.server = server
        self.server_public_address = ""
        self.server_host_name = ""
        self.lower_port = lower_port
        self.upper_port = upper_port
        self.destination_number = "XXXXXXXXXX"

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.server, **settings.SERVERS[self.server])

        if self.server is None:
            raise Exception("Server not defined while initiating object")

        # necessary commands
        self.check_running_kombu_dialer_command = \
            "ps aux|grep kombu"

        try:
            # preparing logger for redirecting output
            self.error_logger = logger.Logger("pri_tester_error_log",
                                              file_handler=True,
                                              stream_handler=True)
            self.debug_logger = logger.Logger("pri_tester_debug_log",
                                              file_handler=True,
                                              stream_handler=True)
            self.error_logger = self.error_logger.logger
            self.debug_logger = self.debug_logger.logger

            # preparing freeswitch connection objects
            self.lower_pris_con = ESL.ESLconnection(self.server, lower_port,
                                                    "ClueCon")

            self.upper_pris_con = ESL.ESLconnection(self.server, upper_port,
                                                    "ClueCon")

        except Exception as err:
            self.error_logger.error(err.message + "PRITester::init")
예제 #2
0
 def connect(self, host=None, port=None, auth=None):
     """Reconnect if disconnected
     """
     host = host or self.host
     port = port or self.port
     auth = auth or self.auth
     if not self.connected():
         # XXX: try a few times since connections seem to be flaky
         # We should probably try to fix this in the _ESL.so
         for _ in range(5):
             self._con = ESL.ESLconnection(*map(str, (host, port, auth)))
             time.sleep(0.05)
             if check_con(self._con):
                 break
             else:
                 self._con = False
     if not check_con(self._con):
         raise ESLError(
             "Failed to connect to server at '{}:{}'\n"
             "Please check that FreeSWITCH is running and "
             "accepting ESL connections.".format(host, port))
     # on success change our contact info
     self.host = host
     self.port = port
     self.auth = auth
예제 #3
0
def get_connection(ip, port, passwd):
    import ESL
    assert ESL, "No module named 'ESL'"
    con = ESL.ESLconnection(ip, port, passwd)
    if not con.connected():
        return None
    return con
예제 #4
0
 def monitor_feed(self):
     data={}
     sub = Subscriber()
     data['mp']=config['internal_prefix']
     data['o']=sub.get_online()
     data['r']=sub.get_roaming()
     data['pa']=sub.get_paid_subscription()
     data['sp']=self.get_sms_pending()
     data['spr']=self.get_sms_pending_not_local()
     data['sf']=self.get_sms_pending_five()
     data['lt']=self.get_recent_call_count('10 mins')
     data['ld']=self.get_recent_call_count('1 hour')
     data['ls']=self.get_recent_call_count('24 hours')
     data['ss']=self.get_recent_sms_count('1 hour')
     data['sa']=round(self.get_recent_sms_avg('hour', '6 hours'), 2)
     data['hu']=self.get_common_recent_hup_cause()
     data['ut']=self.get_uptime()
     data['la']=os.getloadavg()
     data['kl']=os.uname()[2]
     data['v']=self.get_linev()
     data['lat']=self.get_latency()
     data['p']=self.get_puppet_lr()
     data['yy']=datetime.datetime.now().year
     data['mm']=datetime.datetime.now().month
     fs_con=ESL.ESLconnection("127.0.0.1", "8021", "ClueCon")
     data['c']=self.get_fs_calls(fs_con)
     data['gw']=self.get_fs_status(fs_con)
     data['trx']=self.get_trxOK()
     data['ns']=self.get_gprs_ns()
     data['pdp']=self.get_pdp_contexts()
     if 'dids' in globals():
         data['dids']=dids
     fs_con.disconnect()
     return data
예제 #5
0
    def GET(self):
        con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon')
        if not con.connected():
            # Unable to connect FreeSWITCH
            print("Unable to connect FreeSWITCH")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"active call list error\"}")

        #Sending command to FreeSWITCH
        print("Sending command to FreeSWITCH for call list")
        e = con.api("show calls as json")
        if e:
            # Found active calls. Prasing and makeing list of call uuid. Sending response 200 - ok with list of call uuids in JSON
            print("Active calls found")
            web.header('Content-Type', 'application/json','unique=True')
            calls_str = json.loads(e.getBody())

            arr_call_uuids = []
            if calls_str['row_count'] > 0:
                for call in calls_str['rows']:
                    arr_call_uuids.append(call['call_uuid'])
            raise web.ok(json.dumps(arr_call_uuids))
        else:
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"active call list error\"}")
예제 #6
0
def getConferenceIP(room):
    dbcon = db.ncbDB()
    rip = ""
    sql = "SELECT ip FROM servers"
    result = dbcon.ncb_getQuery(sql)
    logging.critical(result)
    if result:
        for ip in result:
            logging.critical(ip['ip'])
            con = ESL.ESLconnection(str(ip['ip']), "8021", "ClueCon")
            if con.connected():
                exe = con.api("conference conf_{} xml_list".format(room))
                out = exe.getBody()
    # Maybe I need to move xml parsing to next part: for example if exe: break
                try:
                    xmlp = etree.fromstring(out)
                except TypeError, XMLSyntaxError:
                    logging.critical("There is no such conference")
                    return False
                element = xmlp.find("conference").get("member-count")
                if element:
                    rip = str(ip['ip'])
        if rip == "":
            logging.critical("Error getting XML data from FS Server...")
            return False
        return {"ip": rip, "body": out}
예제 #7
0
 def connected(self):
     conn = ESL.ESLconnection(self.host, self.port, self.password)
     if conn.connected():
         log_event = logger.Logger('connected ESL API!')
         log_event.esl_logged(conn)
         return conn
     else:
         log_event = logger.Logger('Log')
         log_event.log_logged('Error connected ESL API!')
def create_freeswitch_connection():
    freeswitch_connection = ESL.ESLconnection(config.server, config.port,
                                              config.password)
    if not freeswitch_connection.connected():
        print('Not Connected')
        sys.exit(2)
    freeswitch_connection.events('plain', 'all')
    #freeswitch_connection.events('plain', 'BACKGROUND_JOB')
    return freeswitch_connection
예제 #9
0
 def get(self, room, uuid):
     user = getUserIDbyUUID(room, uuid)
     con = ESL.ESLconnection(user['ip'], '8021', 'ClueCon')
     exe = con.api("conference conf_{} tmute {}".format(room, user['id']))
     out = exe.getBody()
     pattern = 'Ok'
     if re.search(pattern, out):
         return {"result": True, "what": out}
     return {"result": False, "what": out}
예제 #10
0
	def setup(self):
		print self.client_address, ' is connected'
		fd = self.request.fileno()
		con = ESL.ESLconnection(fd)
	        if con.connected():
			info = con.getInfo()
			uuid = info.getHeader("unique-id")
			logger.info('the incoming call uuid is: %s', uuid)
			print uuid
			event = con.filter("unique-id", uuid)
			con.events("plain", "all")
			con.execute("answer", "", uuid)
			msg = "{0} {1} 1 5000 # {2} silence_stream://250".format(max_sid_len, max_sid_len, voice_url)
			print msg
			logger.info('play_and_get_digits: %s', msg)
			con.execute("play_and_get_digits", msg)
			digits = []
                        see_playback_stop = False
                        see_server_disconnected = False
			while con.connected():
				e = con.recvEvent()
				if e:
					name = e.getHeader("event-name")
					logger.debug("event-name: %s", name)
                                        print name
					if name == "DTMF":
						digit = e.getHeader("dtmf-digit")
						logger.debug("digit: %s", digit)
						digits.append(digit)
						print digit
                                        elif name == "PLAYBACK_STOP":
                                                see_playback_stop = True
                                        elif name == "SERVER_DISCONNECTED":
                                                see_server_disconnected = True
                                                break
                                        elif name == "CHANNEL_EXECUTE_COMPLETE" and see_playback_stop:
                                                break
				if len(digits) == max_sid_len:
					break

                        if see_server_disconnected:
                                logger.debug("Disconnected")
                                return
                        
			logger.debug('collecting digits: %s', digits)
			if len(digits) == max_sid_len:
				sid = ''.join(digits)
				print sid
				mobile = routing_server.get_mobile(sid)
				if mobile:
					target = "{0} XML default".format(mobile)
					logger.info('transfer the call to %s', target)
					con.execute("transfer", target, uuid)
                        else:
                                print "bridge to the default target ", default_target
                                con.execute("bridge", default_target, uuid)
예제 #11
0
    def setup(self):
        # self.request.sendall(bytes('welcome'.encode('utf-8')))
        print(self.client_address, 'connected!')
        fd = self.request.fileno()
        print fd
        self.con = ESL.ESLconnection(fd)
        if self.con.connected():
            self.info = self.con.getInfo()

        print 'Connected: ', self.con.connected()
예제 #12
0
def create_freeswitch_connection():
    freeswitch_connection = ESL.ESLconnection(configuration.server,
                                              configuration.port,
                                              configuration.password)
    if not freeswitch_connection.connected():
        print('Not Connected')
        sys.exit(2)
    freeswitch_connection.events('plain', 'all')
    # freeswitch_connection.events('myevents', uuid)
    return freeswitch_connection
예제 #13
0
파일: mod_esl.py 프로젝트: rtduty68/axb
 def connect_eslserver(self, mode):
     ''' 因recvEvent是阻塞的,此时若在同一个ESLconnection进行其他操作(如execute),
     会被在阻塞在recvEvent后执行,可以采用recvEventTimed代替或建立多个ESLconnection
     本项目采用建立两个连接的方式'''
     #建立recv连接
     if mode == "both" or mode == "recv":
         self._logger.info('esl(recv) connecting to %s:%s', self._host,self._port)
         if self._con_recv != None:
             self._con_recv.disconnect()
         self._con_recv = ESL.ESLconnection(self._host,self._port,self._password)
         while True:
             if self._con_recv.connected():
                 self._logger.info('esl(recv) connected to %s:%s', self._host,self._port)
                 self.last_msg_time = time.time() 
                 self._con_recv.filter("variable_servicekey", self._service_key)
                 self._con_recv.filter("Event-Name","SHUTDOWN")
                 self._con_recv.filter("Event-Name","HEARTBEAT")
                 self._con_recv.events("plain", "SHUTDOWN HEARTBEAT CHANNEL_PARK CHANNEL_HANGUP_COMPLETE") # SERVER_DISCONNECTED事件不用设置也能收到
                 break
             else:
                 self._logger.warning('esl(recv) connect to %s:%s error.', self._host,self._port)
                 time.sleep(1)
                 self._logger.info('esl(recv) connecting to %s:%s', self._host,self._port)
                 self._con_recv = ESL.ESLconnection(self._host,self._port,self._password)
     #建立send连接
     if mode == "both" or mode == "send":
         self._logger.info('esl(send) connecting to %s:%s', self._host,self._port)
         if self._con_send != None:
             self._con_send.disconnect()
         self._con_send = ESL.ESLconnection(self._host,self._port,self._password)
         while True:
             if self._con_send.connected():
                 self._logger.info('esl(send) connected to %s:%s', self._host,self._port)
                 #self._con_send.events("plain", "") # 默认不接收任何事件,除了SERVER_DISCONNECTED
                 #self._con_send.setAsyncExecute("1")  # 注:对inbound socket 无效
                 break
             else:
                 self._logger.warning('esl(send) connect to %s:%s error.', self._host,self._port)
                 time.sleep(1)
                 self._logger.info('esl(send) connecting to %s:%s', self._host,self._port)
                 self._con_send = ESL.ESLconnection(self._host,self._port,self._password)
     self.event_disconnected.clear()
     self.event_connected.set()
예제 #14
0
 def __init__(self,
              addr: str = '127.0.0.1',
              port: int = 8021,
              password: str = 'ClueCon',
              run_circles: int = -1):
     self._esl = ESL.ESLconnection(addr, str(port), password)
     self._handlers = []
     self._run_circles = run_circles
     if not self._esl.connected():
         raise Exception('Connection to FreeSWITCH failed!')
예제 #15
0
 def get(self, room):
     conf = getConferenceIP(room)
     con = ESL.ESLconnection(conf['ip'], "8021", "ClueCon")
     if con.connected():
         exe = con.api("conference conf_{} unlock".format(room))
         out = exe.getBody()
     pattern = "OK conf_{} unlocked".format(room)
     if re.search(pattern, out):
         return {"result": True}
     return {"result": False}
예제 #16
0
 def get(self, room, uuid):
     user = getUserIDbyUUID(room, uuid)
     if user:
         con = ESL.ESLconnection(user['ip'], '8021', "ClueCon")
         exe = con.api("conference conf_{} undeaf {}".format(room, user['id']))
         out = exe.getBody()
         pattern = "Ok deaf"
         if re.search(pattern, out):
             return {"result": True}
     logging.critical("Can't connect to conferenct server")
     return {"result": False}
예제 #17
0
 def test_es_connection(self, cr, uid, ids, context=None):
     assert len(ids) == 1, 'Only 1 ID'
     fs_server = self.browse(cr, uid, ids[0], context=context)
     fs_manager = False
     try:
         fs_manager = ESL.ESLconnection(str(fs_server.ip_address),
             str(fs_server.port), str(fs_server.password))
     except Exception, e:
         raise orm.except_orm(
             _("Connection Test Failed!"),
             _("Here is the error message: %s" % e))
예제 #18
0
 def get(self, room):
     conf = getConferenceIP(room)
     con = ESL.ESLconnection(conf['ip'], "8021", "ClueCon")
     if con.connected():
         exe = con.api("conference conf_{} deaf non_moderator".format(room))
         out = exe.getBody()
     pattern = 'OK deaf'
     if re.search(pattern, out):
         return {"result": True}
     else:
         return {"result": False}
예제 #19
0
 def __init__(self, host):
     self.host_id = host.id
     self.line_name = host.line_name
     self.ip = str(host.gateway_ip)
     self.port = 8021
     self.gateway = str(host.gateway_name)
     print '             加载网关:  %s ' % self.gateway
     self.password = '******'
     self.line_max = host.line_num
     self.conn = ESL.ESLconnection(self.ip, self.port, self.password)
     print '             freeswitch esl 连接 %s   %s'%(self.ip,'success' if self.conn.connected() else 'fail')
예제 #20
0
파일: freeswitch.py 프로젝트: trzad/qpanel
 def __init__(self,
              host='127.0.0.1',
              port=defaultESLport,
              password=defaultESLpassword):
     '''
     Initialise a class for Freeswitch
     '''
     self.host = host or '127.0.0.1'
     self.port = int(port or defaultESLport)
     self.password = password or defaultESLpassword
     self.connection = ESL.ESLconnection(self.host, self.port,
                                         self.password)
예제 #21
0
 def __init__(self, host):
     self.host_id = host[0]
     self.ip = str(host[2])
     self.port = host[3]
     self.area = host[1]
     self.passowrd = str(host[5])
     self.gateway = "sofia/gateway/gw1"
     self.line_max = host[6]
     self.conn = ESL.ESLconnection(self.ip, self.port, self.passowrd)
     conn_status = 'success' if self.conn.connected else 'fail'
     print('Connect fs host: %s at %s:%d,%s' %
           (self.passowrd, self.ip, self.port, conn_status))
예제 #22
0
def esl_work(event, qq):
    con = ESL.ESLconnection('192.168.222.20', '8021', 'ClueCon')
    if con.connected:
        con.events('plain', event)

        n = 0
        print 'Started on %s' % event
        while 1:
            ev = con.recvEvent()
            if ev:
                threading.Thread(target=EventWork, args=(ev, qq, n)).start()
            n += 1
예제 #23
0
 def _connect(self):
     """Connect to FreeSWITCH ESL Interface."""
     try:
         self._eslconn = ESL.ESLconnection(self._eslhost,
                                           str(self._eslport),
                                           self._eslpass)
     except:
         pass
     if not self._eslconn.connected():
         raise Exception(
             "Connection to FreeSWITCH ESL Interface on host %s and port %d failed."
             % (self._eslhost, self._eslport))
예제 #24
0
 def get(self, room_vcb, dnis):
     conf = {}
     print dnis
     conf["ip"] = "65.48.98.217"
     if conf:
         con = ESL.ESLconnection(conf["ip"], '8021', 'ClueCon')
         exe = con.api(
             "originate {{origination_caller_id_name={0},origination_caller_id_number=8000,ignore_early_media=true,room_vcb={0}}}sofia/internal/{1}@65.48.99.135 8000"
             .format(room_vcb, dnis))
         out = exe.getBody()
         print out
         return {"result": True, "body": room_vcb}
     return {"result": False, "why": "Something went wrong"}
예제 #25
0
    def POST(self):
        if not web.data():
            # No data. Return 500 - hangup error
            print("No data found in the request")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"hangup error\"}")
        else:
            data = json.loads(web.data())
            if not data:
                # No JSON. Return 500 - hangup error
                print("No JSON data found in the request")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.InternalError("{\"message\": \"hangup error\"}")
            else:
                # Fetch uuid from JSON
                uuid = data["uuid"]
                if not uuid:
                    # UUID not found in request JSON. Return 500 - hangup error
                    print("UUID not found in JSON")
                    web.header('Content-Type', 'application/json','unique=True')
                    raise web.InternalError("{\"message\": \"hangup error\"}")

        con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon')
        if not con.connected():
            # Unable to connect FreeSWITCH
            print("Unable to connect FreeSWITCH")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"call error\"}")

        # Check if mentioned call exists
        e = con.api(str("uuid_exists "+uuid))
        if (e.getBody() != 'true'):
            # Call does not exists. Return 404 - call not found
            print("Call not found for call uuid:"+uuid)
            web.header('Content-Type', 'application/json','unique=True')
            raise web.notfound("{\"message\": \"call not found\"}")
        else:
            # Call found. Sending command for hangup to FreeSWITCH
            print("Call found. Hanging up..")
            e = con.api(str("uuid_kill "+uuid))

            if (e.getBody().find("OK") != -1):
                # Call hangup Successfully. Return 202 - ok
                print("Call hangup sucessfully. Call UUID:"+uuid)
                web.header('Content-Type', 'application/json','unique=True')
                raise web.accepted("{\"message\": \"ok\"}")
            else:
                # Call hangup failed
                print("Call hangup failed")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.InternalError("{\"message\": \"hangup error\"}")
예제 #26
0
 def get(self, room, dnis, ani):
     conf = getConferenceIP(room)
     room = 'conf_' + room
     if conf:
         con = ESL.ESLconnection(conf["ip"], '8021', 'ClueCon')
         if con.connected:
             exe = con.api("originate {{origination_caller_id_name={},origination_caller_id_number={}}}sofia/internal/{}@65.48.99.135 '&lua(confadd.lua {})'".format(ani, ani, dnis, room))
             if exe:
                 out = exe.getBody()
                 pattern = "OK"
                 if re.search(pattern, out):
                     return {"result": True, "dialresult": out}
     logging.critical("Can't get any info")
     return {"result": False, "dialresult": "Couldnt connect to conference server"}
예제 #27
0
 def __init__(self, host):
     self.host_id = host.id
     self.ip = str(host.ip)
     self.port = host.port
     self.area = host.city
     # print ('-*-*-*-*-*-'+self.area)
     self.passowrd = str(host.relay_password)
     self.gateway = "sofia/gateway/gw1"
     self.line_max = host.line_num
     # self.conn = ESLDummy()  # dummy
     self.conn = ESL.ESLconnection(self.ip, self.port, self.passowrd)
     # todo host.line_use = 0 重启后主机已用线数设置为 0
     conn_status = 'success' if self.conn.connected else 'fail'
     # print(self.host_id, self.ip, self.port, self.passowrd, self.gateway, self.line_max)
     print('Connect fs host: %s at %s:%d,%s' %
           (self.passowrd, self.ip, self.port, conn_status))
예제 #28
0
 def __init__(self, host):
     self.host_id = host.id
     self.line_name = host.line_name
     self.province = host.province
     self.city = host.city
     self.ip = str(host.ip)
     self.port = host.port
     self.gateway = str(host.relay_account)
     print '[ gateway ----> %s ] ' % self.gateway
     self.password = str(host.relay_password)
     self.line_max = host.line_num
     self.conn = ESL.ESLconnection(self.ip, self.port, self.password)
     print '%s  conn.connected %s' % (self.ip, self.conn.connected)
     conn_status = 'success' if self.conn.connected else 'fail'
     print('Connect fs host: %s at %s:%d,%s' %
           (self.password, self.ip, self.port, conn_status))
예제 #29
0
    def setup(self):
        print self.client_address, 'connected!'

        fd = self.request.fileno()
        print fd

        con = ESL.ESLconnection(fd)
        print 'Connected: ', con.connected()
        if con.connected():

            info = con.getInfo()

            uuid = info.getHeader("unique-id")
            print uuid
            con.execute("answer", "", uuid)
            con.execute("playback", "/ram/swimp.raw", uuid)
예제 #30
0
    def POST(self):
        if not web.data():
            # No data. Return 500 - call error
            print("No data found in the request")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"call error\"}")
        else:
            data = json.loads(web.data())
            if not data:
                # No JSON. Return 500 - call error
                print("No JSON data found in the request")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.InternalError("{\"message\": \"call error\"}")
            else:
                # Fetch destination from JSON
                destination = data["destination"]
                print("Destination: "+destination)
                if not destination:
                    # Destination not found in request JSON. Return 500 - call error
                    web.header('Content-Type', 'application/json','unique=True')
                    raise web.InternalError("{\"message\": \"call error\"}")

        con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon')
        if not con.connected():
            # Unable to connect FreeSWITCH
            print("Unable to connect FreeSWITCH")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"call error\"}")

        temp = "{'origination_caller_id_number=3024561011'}user/"+destination+" &playback(http://s3.amazonaws.com/plivocloud/music.mp3)" 
        cmd = str(temp) 
        
        # Sending command to FreeSWITCH
        print("Initiating Call.. ")
        e = con.api("originate", cmd)
        if e:
            res = e.getBody()
            if (res.find("OK") != -1):
                # Call Successful. Return 201 -ok
                print("Call Successful")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.created("{\"message\": \"ok\"}")
            else:
                # Call Failed. Return 500 - call error
                print("Call Failed")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.InternalError("{\"message\": \"call error\"}")