def __init__(self, host='127.0.0.1', port=defaultESLport, secret="ClueCon", autoInit=True): """Initialize connection to FreeSWITCH ESL Interface. @param host: FreeSWITCH Host @param port: FreeSWITCH ESL Port @param secret: FreeSWITCH ESL Secret @param autoInit: If True connect to FreeSWITCH ESL Interface on instantiation. >>> fs = FSinfo(host='127.0.0.1', port=defaultESLport, secret="ClueCon") >>> print fs.getChannelCount() 0 >>> print fs.getReloadGateway() """ # Set Connection Parameters self._eslconn = None self._eslhost = host or '127.0.0.1' self._eslport = int(port or defaultESLport) self._eslpass = secret or defaultESLsecret ESL.eslSetLogLevel(0) if autoInit: self._connect()
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")
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
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
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\"}")
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
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}
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}
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
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)
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
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()
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}
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!')
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()
def __init__(self, host='127.0.0.1', port=8021, secret="ClueCon", autoInit=True): """Initialize connection to FreeSWITCH ESL Interface. @param host: FreeSWITCH Host @param port: FreeSWITCH ESL Port @param secret: FreeSWITCH ESL Secret @param autoInit: If True connect to FreeSWITCH ESL Interface on instantiation. """ # Set Connection Parameters self._eslhost = host or '127.0.0.1' self._eslport = port or 8021 self._eslpass = secret or "ClueCon" self._eslconn = None ESL.eslSetLogLevel(0) if autoInit: self._connect()
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))
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')
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}
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}
def webphone_sms(self, source, destination, text, coding): if not ('webphone_prefix' in globals() and isinstance(webphone_prefix, list) and isinstance(sip_central_ip_address, list)): sms_log.warning('SMS for Webphone but required config missing.') return False if not self.destination[:5] in webphone_prefix: sms_log.warning('WEBPHONE SMS for non webphone extension?') return False sms_log.debug('WEBPHONE SMS from %s for %s [%s] [%s]', (source, destination, text, coding)) self.source = source + '@sip.rhizomatica.org' self.destination = destination self.text = text simple_dest = self.destination + '@' + sip_central_ip_address[0] sip_profile = 'outgoing' try: event = ESL.ESLevent("CUSTOM", "SMS::SEND_MESSAGE") sms_log.debug('SMS to SIP: Source is %s' % self.source) sms_log.debug('SMS to SIP: Dest: %s' % simple_dest) sms_log.debug('Text: %s' % self.text.decode(self.charset, 'replace')) event.addHeader("from", self.source) event.addHeader("to", simple_dest) event.addHeader("sip_profile", sip_profile) event.addHeader("dest_proto", "sip") event.addHeader("type", "text/plain") # Todo, see how we can actually get the result of this back here? #event.addHeader("blocking", "true") event.addBody(text.encode(self.charset, 'replace')) con = ESL.ESLconnection("127.0.0.1", "8021", "ClueCon") ret = con.sendEvent(event) con.disconnect() sms_log.info('WEBPHONE SMS SENT Status:[%s]', ret) return True except Exception as excep: sms_log.info('Exception with Webphone SMS or FS Event: %s' % excep) return False
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))
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
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)
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))
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"}
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\"}")
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"}
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))