client.py 28 KB

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