client.py 29 KB

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