client.py 25 KB

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