client.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. #!/usr/bin/env python3
  2. # encoding:utf-8
  3. import json
  4. import random
  5. import socketserver
  6. import sys
  7. import ESL
  8. import time
  9. import mmh3
  10. import threading
  11. import traceback
  12. import concurrent.futures
  13. from apscheduler.schedulers.background import BackgroundScheduler
  14. from src.core.callcenter.cache import Cache
  15. from src.core.callcenter.api import MakeCallContext, DelayAction, CallInfo, DeviceInfo, NextCommand
  16. from src.core.callcenter.constant import SK, EMPTY, CTI_ENGINE_DELAY_ACTION_LOCK, HOLD_MUSIC_PATH, saasId
  17. from src.core.callcenter.esl.constant.esl_constant import BRIDGE_VARIABLES, BRIDGE, HANGUP, NORMAL_CLEARING, SIP_HEADER, SPACE, SPLIT, SOFIA, \
  18. ORIGINATE, PARK, SET, EAVESDROP, SMF_ALEG, EXECUTE, PLAYBACK, PAUSE, TRANSFER, UUID_TRANSFER, UUID_BROADCAST, UUID_BREAK, UUID_HOLD, \
  19. UUID_RECORD, UUID_SETVAR, UUID_GETVAR
  20. import src.core.callcenter.esl.utils.esl_event_util as EslEventUtil
  21. import src.core.callcenter.esl.handler as event_handler
  22. from src.core.callcenter.esl.constant.sip_header_constant import sipHeaderHoldMusic, profile1, profile2, sipHeaderCallId
  23. from src.core.callcenter.enumeration import CallCause, DeviceType, DelayActionEnum, HangupDir, CallType, NextType, \
  24. Direction, CdrType
  25. from src.core.callcenter.esl.handler.default_esl_event_handler import DefaultEslEventHandler
  26. from src.core.callcenter.snowflake import Snowflake
  27. from src.core.datasource import SERVE_HOST
  28. from src.core.voip.constant import *
  29. from src.core.callcenter.data_handler import *
  30. class InboundClient:
  31. def __init__(self, agent, app):
  32. self.con = None
  33. self.thread_num = 12
  34. self.is_stopping = False
  35. self.app = app
  36. self.logger = app.logger
  37. self.bot_agent = agent
  38. self.cache = Cache(app)
  39. self.handler_table = self.scan_esl_event_handlers()
  40. self.default_event_handler = DefaultEslEventHandler(self, self.bot_agent)
  41. self.host, self.port, self.password = SERVE_HOST, '8021', '4918257983818884358'
  42. self.executors = {x: concurrent.futures.ThreadPoolExecutor(max_workers=1) for x in range(self.thread_num)}
  43. self.delay_action_executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
  44. self.delay_action_scheduler = BackgroundScheduler()
  45. # self.delay_action_scheduler.add_job(self.submit_delay_action, 'interval', seconds=1, max_instances=1)
  46. # self.delay_action_scheduler.start()
  47. threading.Thread(target=self.start, args=()).start()
  48. def submit_delay_action(self):
  49. for name, member in DelayActionEnum.__members__.items():
  50. action_messages = self.cache.get_delay_message(name)
  51. for action_message in action_messages:
  52. self.delay_action_executor.submit(self.do_delay_action, name, action_message)
  53. def scan_esl_event_handlers(self):
  54. import inspect
  55. import importlib
  56. import pkgutil
  57. classes = []
  58. # 遍历包中的模块
  59. for module_info in pkgutil.iter_modules(event_handler.__path__):
  60. module = importlib.import_module(f"{event_handler.__name__}.{module_info.name}")
  61. for _name, _cls in inspect.getmembers(module, inspect.isclass):
  62. if hasattr(_cls, '_esl_event_name'):
  63. classes.append(_cls)
  64. handlers = {}
  65. for _cls in classes:
  66. items = handlers.get(_cls._esl_event_name, [])
  67. items.append(_cls(self, self.bot_agent))
  68. handlers[_cls._esl_event_name] = items
  69. return handlers
  70. def start(self):
  71. self.logger.info('inbound.start')
  72. self.con = ESL.ESLconnection(self.host, self.port, self.password)
  73. if self.con.connected():
  74. self.logger.info('inbound esl connected ... ')
  75. self.con.events('plain', 'all') #CHANNEL_ORIGINATE,CHANNEL_PROGRESS,CHANNEL_PROGRESS_MEDIA,CHANNEL_ANSWER,CHANNEL_HANGUP,CUSTOM,PLAYBACK_START,PLAYBACK_STOP,DETECTED_TONE
  76. while not self.is_stopping:
  77. e = self.con.recvEvent()
  78. # if e:
  79. # self.logger.info(json.loads(e.serialize('json')))
  80. event_name = e.getHeader("Event-Name")
  81. if event_name == "SERVER_DISCONNECTED":
  82. self.logger.info('come in SERVER_DISCONNECTED case')
  83. self.con.disconnect()
  84. time.sleep(3)
  85. self.start()
  86. else:
  87. # threading.Thread(target=self.process_esl_event, args=(e,)).start()
  88. self.choose_thread_pool_executor(e).submit(self.process_esl_event, e)
  89. def choose_thread_pool_executor(self, e):
  90. call_id = EslEventUtil.getCallId(e)
  91. device_id = EslEventUtil.getUniqueId(e)
  92. wdh_device_id = EslEventUtil.getDeviceId(e)
  93. random_id = call_id if call_id else device_id
  94. if random_id:
  95. random_index = abs(mmh3.hash(random_id)) % len(self.executors)
  96. else:
  97. random_index = random.randint(0, len(self.executors) - 1) if self.executors else 0
  98. # print('choose_thread_pool_executor.index=', random_index, call_id, device_id, wdh_device_id)
  99. return self.executors.get(random_index)
  100. def process_esl_event(self, e):
  101. # print(json.loads(e.serialize('json')))
  102. event_name = EslEventUtil.getEventName(e)
  103. coreUUID = EslEventUtil.getCoreUuid(e)
  104. address = self.host + ':' + self.port
  105. # self.logger.info("process_esl_event.event_name=%s,coreUUID=%s", event_name, coreUUID)
  106. try:
  107. if event_name in self.handler_table:
  108. items = self.handler_table.get(event_name)
  109. for x in items:
  110. try:
  111. x.handle(address, e, coreUUID)
  112. except:
  113. traceback.print_exc()
  114. else:
  115. self.default_event_handler.handle(address, e, coreUUID)
  116. except:
  117. traceback.print_exc()
  118. def do_delay_action(self, action, message):
  119. delay_action = DelayAction.from_json(message)
  120. flag = self.cache.lock_delay_action(delay_action.uuid)
  121. if not flag:
  122. self.logger.info("异步延迟执行操作重复 action:%s msg:%s", action, message)
  123. return
  124. delay_action_enum = DelayActionEnum.get_by_code(action)
  125. if not delay_action_enum:
  126. self.logger.info("异步延迟执行 delayActionEnum为空 action:%s msg:%s", action, message)
  127. return
  128. if DelayActionEnum.CALL_TIMEOUT_HANGUP == delay_action_enum:
  129. self.exec_when_call_timeout(delay_action.call_id, delay_action.device_id)
  130. elif DelayActionEnum.PLAY_TIMEOUT_HANGUP == delay_action_enum:
  131. self.exec_when_play_timeout(delay_action.call_id)
  132. elif DelayActionEnum.ACD_TIMEOUT_PLAY == delay_action_enum:
  133. self.exec_when_acd_timeout(delay_action.call_id)
  134. def exec_when_call_timeout(self, call_id, device_id):
  135. call_info = self.cache.get_call_info(call_id)
  136. if not call_info or not (device_id in call_info.device_list):
  137. return
  138. device_info = call_info.device_info_map.get(device_id)
  139. if device_info and device_info.answer_time is None:
  140. self.logger.info("call:%s deviceId:%s execWhenCallTimeOut", call_id, device_id)
  141. device_info.hangup_cause = CallCause.CALL_TIMEOUT.name
  142. call_info.next_commands = []
  143. if device_info.device_type <= DeviceType.ROBOT.code:
  144. call_info.hangup_dir = HangupDir.PLATFORM_HANGUP.code
  145. call_info.hangup_code = CallCause.CALL_TIMEOUT.code
  146. # if device_info.device_type.code == DeviceType.CUSTOMER.code:
  147. # call_info.user_no_answer_end_call = True
  148. if not device_info.end_time and device_info.device_type.code == DeviceType.CUSTOMER.code:
  149. channel = self.show_channel(device_id)
  150. if channel:
  151. delay_action = DelayAction(call_id=call_id, device_id=device_id)
  152. self.cache.add_delay_message(DelayActionEnum.CALL_TIMEOUT_DECR, delay_action, timeouts=20)
  153. self.cache.add_call_info(call_info)
  154. self.hangup_call(call_id, device_id, CallCause.CALL_TIMEOUT)
  155. def exec_when_play_timeout(self, call_id):
  156. call_info = self.cache.get_call_info(call_id)
  157. if not call_info or not call_info.next_commands:
  158. return
  159. self.logger.debug("播放结束音乐失败,进行挂机 callId:%s", call_id)
  160. next_types = [x.next_type for x in call_info.next_commands]
  161. if NextType.NEXT_HANGUP.code in next_types:
  162. for device_id in call_info.device_list:
  163. self.hangup_call(call_id, device_id, CallCause.PLAY_TIMEOUT)
  164. def exec_when_acd_timeout(self, call_id):
  165. call_info = self.cache.get_call_info(call_id)
  166. if not call_info:
  167. self.logger.info("exec_when_acd_timeout callInfo为空 callId: {}", call_id)
  168. return
  169. device_list = [v for k,v in call_info.device_info_map.items() if v.device_type == DeviceType.CUSTOMER]
  170. if device_list and len(device_list) == 1:
  171. device_id = device_list[0].device_id
  172. self.bridge_break(device_id)
  173. self.hold_play(device_id, HOLD_MUSIC_PATH)
  174. self.play_timeout(call_id, timeout=30)
  175. self.cache.add_call_info(call_info)
  176. self.logger.info("waitingTimeOut 开始播放结束音乐 callId:%s customerDeviceId:%s playFile:%s", call_id,
  177. device_id, HOLD_MUSIC_PATH)
  178. def make_call_new(self, context: MakeCallContext):
  179. called = context.get_called()
  180. params = {'gateway': context.route_gateway_name, 'called': called, 'realm': context.get_realm()}
  181. builder = [
  182. '{', context.get_sip_header(), '}'
  183. ]
  184. if context.device_type == DeviceType.CUSTOMER.code:
  185. profile = self.expression(profile1, params)
  186. builder.append(f"{SOFIA}{SK}{profile}{SK}{called}{PARK}")
  187. else:
  188. profile = self.expression(profile2, params)
  189. builder.append(f"{profile}{PARK}")
  190. cmd = "".join(builder)
  191. print(cmd, flush=True)
  192. self.con.bgapi(ORIGINATE, cmd)
  193. def call_timeout(self, call_id, device_id, timeout):
  194. """呼叫超时主动挂机"""
  195. delay_action = DelayAction(call_id=call_id, device_id=device_id)
  196. self.cache.add_delay_message(DelayActionEnum.CALL_TIMEOUT_HANGUP.code, delay_action, timeouts=timeout)
  197. def send_args(self, device_id, name, arg, con=None):
  198. msg = ESL.ESLevent("sendmsg", device_id)
  199. msg.addHeader("call-command", EXECUTE)
  200. msg.addHeader("execute-app-name", name)
  201. msg.addHeader("execute-app-arg", arg)
  202. if con:
  203. con.sendEvent(msg)
  204. else:
  205. self.con.sendEvent(msg)
  206. def bridge_call(self, call_id, device_id1, device_id2):
  207. """桥接电话"""
  208. self.multi_set_var(device_id1, BRIDGE_VARIABLES)
  209. self.multi_set_var(device_id2, BRIDGE_VARIABLES)
  210. self.con.bgapi(BRIDGE, device_id1 + SPACE + device_id2)
  211. def transfer_call(self, _from, _to):
  212. """转接"""
  213. builder = [
  214. _from,
  215. " -both 'set:hangup_after_bridge=false,set:park_after_bridge=true,park:' inline "
  216. ]
  217. arg = ''.join(builder)
  218. self.con.bgapi(TRANSFER, arg)
  219. def answer(self, device_id):
  220. """应答"""
  221. self.con.bgapi('uuid_phone_event', device_id + ' talk')
  222. def hangup_call(self, call_id, device_id, case_enum=CallCause.DEFAULT):
  223. """挂机"""
  224. msg = ESL.ESLevent("sendmsg", device_id)
  225. msg.addHeader("call-command", EXECUTE)
  226. msg.addHeader("execute-app-name", HANGUP)
  227. msg.addHeader("execute-app-arg", NORMAL_CLEARING)
  228. msg.addHeader("async", "true")
  229. _con = None
  230. try:
  231. _con = ESL.ESLconnection(self.host, self.port, self.password)
  232. if _con.connected():
  233. print("hangup_call挂机1 hangup call: %s, device: %s, ctiCauseEnum: %s" % (call_id, device_id, case_enum), flush=True)
  234. arg = ''.join([EslEventUtil.SIP_H_P_LIBRA_HANGUP_CAUSE, "=", case_enum.description])
  235. print("hangup_call挂机2 hangup call: %s, device: %s, arg: %s" % (call_id, device_id, arg), flush=True)
  236. self.send_args(device_id, SET, arg, con=_con)
  237. print("hangup_call挂机3 hangup call: %s, device: %s, arg: %s" % (call_id, device_id, arg), flush=True)
  238. _con.sendEvent(msg)
  239. print("hangup_call挂机4 hangup call: %s, device: %s, arg: %s" % (call_id, device_id, arg), flush=True)
  240. except:
  241. traceback.print_exc()
  242. finally:
  243. if _con:
  244. _con.disconnect()
  245. def broadcast(self, uuid, path, smf):
  246. builder = [
  247. UUID_BROADCAST,
  248. uuid,
  249. path,
  250. smf
  251. ]
  252. command = ' '.join(builder)
  253. self.con.bgapi(command, EMPTY)
  254. def break0(self, uuid, all=False, sync=True):
  255. builder = [
  256. UUID_BREAK,
  257. uuid
  258. ]
  259. if all:
  260. builder.append("all")
  261. command = ' '.join(builder)
  262. if sync:
  263. self.con.api(command, EMPTY)
  264. else:
  265. self.con.bgapi(command, EMPTY)
  266. def hold(self, smf, uuid, display):
  267. builder = [
  268. UUID_HOLD,
  269. smf,
  270. uuid,
  271. display
  272. ]
  273. if display:
  274. builder.append("all")
  275. else:
  276. builder.append(EMPTY)
  277. command = ' '.join(builder)
  278. self.con.bgapi(command, EMPTY)
  279. def get_var(self, uuid, var):
  280. builder = [
  281. UUID_GETVAR,
  282. uuid,
  283. var
  284. ]
  285. command = ' '.join(builder)
  286. self.con.bgapi(command, EMPTY)
  287. def set_var(self, uuid, var, val):
  288. builder = [
  289. UUID_SETVAR,
  290. uuid,
  291. var,
  292. val
  293. ]
  294. command = ' '.join(builder)
  295. self.bgapi(command, desc ="bridge_break")
  296. def multi_set_var(self, uuid, params):
  297. builder = [
  298. "uuid_setvar_multi " + uuid + " "
  299. ]
  300. builder1 = []
  301. for k, v in params.items():
  302. builder1.append(k + "="+v)
  303. builder.append(';'.join(builder1))
  304. command = ''.join(builder)
  305. self.con.bgapi(command, EMPTY)
  306. def record(self, uuid, action, path, limit):
  307. builder = [
  308. UUID_RECORD,
  309. uuid,
  310. action,
  311. path,
  312. str(limit)
  313. ]
  314. command = ' '.join(builder)
  315. self.con.bgapi(command, EMPTY)
  316. def transfer(self, uuid, smf, dest, dialplan, context):
  317. builder = [
  318. UUID_TRANSFER,
  319. uuid,
  320. smf,
  321. dest,
  322. dialplan,
  323. context
  324. ]
  325. command = ' '.join(builder)
  326. self.con.bgapi(command, EMPTY)
  327. def insert(self, device_id):
  328. """强插"""
  329. builder = [
  330. device_id,
  331. " -both 'set:hangup_after_bridge=false,set:park_after_bridge=true,park:' inline "
  332. ]
  333. arg = ''.join(builder)
  334. self.con.api(TRANSFER, arg)
  335. def bridge_break(self, call_id, device_id):
  336. """拆线"""
  337. builder = [
  338. device_id,
  339. f" -both 'set:hangup_after_bridge=false,set:park_after_bridge=true,set:{SIP_HEADER}{sipHeaderHoldMusic}={call_id},park:' inline "
  340. ]
  341. arg = ''.join(builder)
  342. self.api(TRANSFER, arg, "bridge_break")
  343. def play_file(self, call_id, device_id, file, sync):
  344. """放音"""
  345. if sync:
  346. return self.hold_play(device_id, file)
  347. else:
  348. msg = ESL.ESLevent("sendmsg", device_id)
  349. msg.addHeader("call-command", EXECUTE)
  350. msg.addHeader("execute-app-name", PLAYBACK)
  351. msg.addHeader("execute-app-arg", file)
  352. msg.addHeader("async", "true")
  353. self.con.sendEvent(msg)
  354. def stop_play(self, device_id):
  355. """关闭播放音乐"""
  356. builder = [
  357. device_id,
  358. " on"
  359. ]
  360. arg = ''.join(builder)
  361. self.con.api(PAUSE, arg)
  362. def hold_play(self, device_id, play):
  363. """向a-leg插播tts音乐(无限播放)"""
  364. builder = [
  365. device_id,
  366. " playback::",
  367. play,
  368. " ",
  369. SMF_ALEG
  370. ]
  371. arg = ''.join(builder)
  372. self.api(UUID_BROADCAST, arg, "hold_play")
  373. def api(self, command, arg=EMPTY, desc=""):
  374. _con = None
  375. try:
  376. _con = ESL.ESLconnection(self.host, self.port, self.password)
  377. if _con.connected():
  378. e = _con.api(command, arg)
  379. print('debugger::%s success, arg=%s, event=%s' % (desc, command + ' ' + arg, e.serialize('json')),
  380. flush=True)
  381. except:
  382. traceback.print_exc()
  383. finally:
  384. if _con:
  385. _con.disconnect()
  386. def bgapi(self, command, arg=EMPTY, desc=""):
  387. _con = None
  388. try:
  389. _con = ESL.ESLconnection(self.host, self.port, self.password)
  390. if _con.connected():
  391. e = _con.bgapi(command, arg)
  392. print('debugger::%s success, arg=%s, event=%s' % (desc, command + ' '+arg, e.serialize('json')), flush=True)
  393. except:
  394. traceback.print_exc()
  395. finally:
  396. if _con:
  397. _con.disconnect()
  398. def play_timeout(self, call_id, timeout):
  399. """播放超时主动挂机"""
  400. delay_action = DelayAction(call_id=call_id)
  401. self.cache.add_delay_message(DelayActionEnum.PLAY_TIMEOUT_HANGUP.code, delay_action, timeouts=timeout)
  402. def listen(self, device_id1, device_id2, aleg=True, bleg=True):
  403. """监听"""
  404. if aleg:
  405. self.send_args(device_id1, SET, "eavesdrop_bridge_aleg=true")
  406. if bleg:
  407. self.send_args(device_id1, SET, "eavesdrop_bridge_bleg=true")
  408. self.send_args(device_id1, EAVESDROP, device_id2)
  409. def show_channel(self, device_id):
  410. msg = self.con.api("show", " channels like " + device_id + " as json")
  411. print('show_channel::', msg)
  412. return msg
  413. def expression(self, template, params):
  414. for key, value in params.items():
  415. template = template.replace("#{["+key+"]}", str(value))
  416. return template
  417. def stop(self):
  418. for k, v in self.executors.items():
  419. v.shutdown()
  420. self.con.disconnect()
  421. self.is_stopping = True
  422. class OutboundClient:
  423. def __init__(self, agent, app):
  424. self.app = app
  425. self.logger = app.logger
  426. self.whitelist = []
  427. self.update_whitelist() # 初始化加载白名单
  428. # 定时更新白名单
  429. threading.Thread(target=self.refresh_whitelist, daemon=True).start()
  430. self.dataHandleServer = DataHandleServer(app)
  431. #threading.Thread(target=self.start, args=('0.0.0.0', 8084, agent, logger)).start()
  432. server_thread = threading.Thread(target=self.start, args=('0.0.0.0', 8084, agent))
  433. server_thread.daemon = True # 设置守护线程
  434. server_thread.start()
  435. def update_whitelist(self):
  436. with self.app.app_context():
  437. phones = Whitelist.query.filter_by(del_flag=0).all()
  438. self.whitelist = [phone.phone for phone in phones]
  439. self.logger.info("Whitelist updated: %s", self.whitelist)
  440. def refresh_whitelist(self):
  441. while True:
  442. time.sleep(3600) # 每 1小时 更新一次
  443. self.update_whitelist()
  444. def load_whitelist(self):
  445. return self.whitelist
  446. def load_agent_monitor(self):
  447. with self.app.app_context():
  448. agents = AgentMonitor.query.filter_by(check_state=0,service_state=2).all()
  449. agent_nums = [agent.agent_num for agent in agents]
  450. return agent_nums
  451. class ESLRequestHandler(socketserver.BaseRequestHandler):
  452. def setup(self):
  453. try:
  454. self.server.logger.info('%s connected!', self.client_address)
  455. fd = self.request.fileno()
  456. con = ESL.ESLconnection(fd)
  457. self.server.logger.info('Connected: %s', con.connected())
  458. if con.connected():
  459. info = con.getInfo()
  460. # print(json.loads(info.serialize('json')))
  461. event_name = info.getHeader("Event-Name")
  462. device_id = info.getHeader("unique-id")
  463. caller_number = info.getHeader("Caller-Caller-ID-Number") # 获取来电号码
  464. whitelist = self.server.load_whitelist()
  465. call_id = 'C' + str(Snowflake().next_id())
  466. new_device_id = 'D' + str(Snowflake().next_id())
  467. kwargs = json.loads(info.serialize('json'))
  468. kwargs['variable_sip_h_P-LIBRA-CallId'] = call_id
  469. kwargs['variable_sip_h_P-LIBRA-DeviceId'] = new_device_id
  470. call_info = {
  471. "session_id": call_id,
  472. "time_begin": datetime.utcnow(),
  473. "category": 0,
  474. "phone": caller_number
  475. }
  476. # 检查白名单
  477. if caller_number in whitelist:
  478. agents = self.server.load_agent_monitor()
  479. destination = random.choice(agents) # 随机取一个坐席号
  480. # 直接转接到人工坐席
  481. self.server.logger.info( "Caller %s is in whitelist, agents: %s, destination: %s", caller_number, agents, destination)
  482. call_info['type']= 0
  483. call_info['agent_num'] = destination
  484. else:
  485. #转到ai机器人
  486. destination = self.server.agent.register(**kwargs)
  487. self.server.logger.info("debugger::device_id=%s, destination=%s, new_device_id=%s", device_id, destination, new_device_id)
  488. call_info['type'] = 1
  489. call_info['service_category'] = 1
  490. call_info['user_id'] = destination
  491. call_info['user_name'] = f"机器人{destination}"
  492. self.build_call_info(call_id, device_id, new_device_id, str(destination), **kwargs)
  493. self.server.cache.add_device_user_part(device_id, destination)
  494. con.execute("bridge", "{sip_h_P-LIBRA-CallId=%s,sip_h_P-LIBRA-DeviceId=%s,origination_uuid=%s}user/%s"%(call_id, new_device_id, new_device_id, destination), device_id)
  495. self.server.dataHandleServer.create_record(call_info)
  496. # destination = "user/1001"
  497. # msg = ESL.ESLevent("sendmsg", uuid)
  498. # msg.addHeader("call-command", "execute")
  499. # msg.addHeader("execute-app-name", "bridge")
  500. # msg.addHeader("execute-app-arg", destination)
  501. # # 发送消息以执行 bridge 操作
  502. # con.sendEvent(msg)
  503. # print(f"Call {uuid} is bridged to {destination}")
  504. # con.execute("answer", "", uuid)
  505. # con.execute("transfer", "1001 XML default", uuid)
  506. # try:
  507. # con.disconnect()
  508. # except:
  509. # print('come in ')
  510. # traceback.print_exc()
  511. else:
  512. self.server.logger.info("Failed to connect to FreeSWITCH")
  513. except:
  514. traceback.print_exc()
  515. def build_call_info(self, call_id, device_id, new_device_id, destination, **kwargs):
  516. caller = kwargs.get('Channel-Caller-ID-Number')
  517. called = destination
  518. now = datetime.utcnow().timestamp()
  519. call_info = CallInfo(call_id=call_id, agent_key=destination,
  520. caller=caller, called=called, direction=Direction.INBOUND.code,
  521. call_type=CallType.BOOT_CALL.code, call_time=now,
  522. uuid1=call_id, uuid2=device_id, saas_id=saasId)
  523. device_custom = DeviceInfo(device_id=device_id, call_time=now,
  524. call_id=call_id, device_type=DeviceType.CUSTOMER.code,
  525. agent_key=destination, cdr_type=CdrType.TRANSFER.code)
  526. device_bot = DeviceInfo(device_id=new_device_id, call_time=now,
  527. call_id=call_id, device_type=DeviceType.ROBOT.code,
  528. agent_key=destination, cdr_type=CdrType.INBOUND.code)
  529. call_info.device_list.append(device_id)
  530. call_info.device_list.append(new_device_id)
  531. # call_info.next_commands.append(NextCommand(device_id, NextType.NEXT_CALL_BRIDGE.code, new_device_id))
  532. call_info.device_info_map = {device_id: device_custom, new_device_id: device_bot}
  533. print("lwdebugger::outBound, call_info=%s"%(call_info), flush=True)
  534. self.server.cache.add_call_info(call_info)
  535. class CustomTCPServer(socketserver.TCPServer):
  536. def __init__(self, server_address, RequestHandlerClass, agent, app,whitelist_loader,load_agent_monitor,dataHandleServer):
  537. self.agent = agent
  538. self.cache = Cache(app)
  539. self.logger = app.logger
  540. self.load_whitelist = whitelist_loader
  541. self.load_agent_monitor = load_agent_monitor
  542. self.dataHandleServer = dataHandleServer
  543. super().__init__(server_address, RequestHandlerClass)
  544. def start(self, HOST='0.0.0.0', PORT=8084, agent=None):
  545. # HOST, PORT = "0.0.0.0", 8084
  546. # 创建一个 TCP 服务器
  547. with self.CustomTCPServer((HOST, PORT), self.ESLRequestHandler, agent, self.app, self.load_whitelist, self.load_agent_monitor,self.dataHandleServer) as server:
  548. self.logger.info(f"ESL server listening on {HOST}:{PORT}")
  549. server.serve_forever()