CallHandler.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. package com.telerobot.fs.acd;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.telerobot.fs.config.AppContextProvider;
  5. import com.telerobot.fs.config.SystemConfig;
  6. import com.telerobot.fs.entity.bo.ChanneState;
  7. import com.telerobot.fs.entity.bo.ChannelFlag;
  8. import com.telerobot.fs.entity.bo.InboundDetail;
  9. import com.telerobot.fs.entity.dto.CallMonitorInfo;
  10. import com.telerobot.fs.entity.po.CdrDetail;
  11. import com.telerobot.fs.entity.pojo.AgentStatus;
  12. import com.telerobot.fs.global.CdrPush;
  13. import com.telerobot.fs.ivr.IvrEngine;
  14. import com.telerobot.fs.service.AsrResultListener;
  15. import com.telerobot.fs.service.SysService;
  16. import com.telerobot.fs.utils.*;
  17. import com.telerobot.fs.wshandle.*;
  18. import com.telerobot.fs.wshandle.impl.AgentCc;
  19. import com.telerobot.fs.wshandle.impl.CallApi;
  20. import com.telerobot.fs.wshandle.impl.InboundMonitorDataPull;
  21. import link.thingscloud.freeswitch.esl.EslConnectionPool;
  22. import link.thingscloud.freeswitch.esl.EslConnectionUtil;
  23. import link.thingscloud.freeswitch.esl.IEslEventListener;
  24. import link.thingscloud.freeswitch.esl.constant.EventNames;
  25. import link.thingscloud.freeswitch.esl.constant.UuidKeys;
  26. import link.thingscloud.freeswitch.esl.transport.event.EslEvent;
  27. import link.thingscloud.freeswitch.esl.transport.message.EslMessage;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. import java.net.URLDecoder;
  31. import java.util.*;
  32. import java.util.concurrent.ConcurrentHashMap;
  33. import java.util.concurrent.Semaphore;
  34. import java.util.concurrent.ThreadPoolExecutor;
  35. import java.util.concurrent.TimeUnit;
  36. import java.util.concurrent.atomic.AtomicInteger;
  37. import java.util.concurrent.atomic.AtomicLong;
  38. // import java.util.concurrent.atomic.LongAdder;
  39. /**
  40. * 单个呼入电话的处理线程
  41. **/
  42. public class CallHandler {
  43. private static AtomicLong globalQueueCounter = new AtomicLong();
  44. private volatile long queueNo = 0L;
  45. public long getQueueNo(){
  46. return queueNo;
  47. }
  48. private final static Logger log = LoggerFactory.getLogger(CallHandler.class);
  49. private static ConcurrentHashMap<String, CallHandler> callTaskList = new ConcurrentHashMap<>(500);
  50. /**
  51. * 转接电话时,是否隐藏客户号码
  52. */
  53. private static boolean hideInboundNumber = Boolean.parseBoolean(
  54. SystemConfig.getValue("hide-inbound-number", "true")
  55. );
  56. /**
  57. * 转接通话时是否播放工号
  58. */
  59. private static boolean playOpNum = Boolean.parseBoolean(
  60. SystemConfig.getValue("inbound-play-opnum", "true")
  61. );
  62. private static int acdPlayQueueNumInterval =
  63. Integer.parseInt(SystemConfig.getValue("acd_play_queue_num_interval", "25"));
  64. /**
  65. * 呼入者相关信息
  66. */
  67. private volatile InboundDetail inboundDetail;
  68. public InboundDetail getInboundDetail()
  69. {
  70. return inboundDetail;
  71. }
  72. /**
  73. * IVR ID for satisfaction survey
  74. */
  75. private volatile String satisfSurveyIvrId = "";
  76. public String getSatisfSurveyIvrId() {
  77. return satisfSurveyIvrId;
  78. }
  79. public void setSatisfSurveyIvrId(String satisfSurveyIvrId) {
  80. this.satisfSurveyIvrId = satisfSurveyIvrId;
  81. }
  82. private static ThreadPoolExecutor transferCallThreadPool;
  83. private static ThreadPoolExecutor fsMsgThreadPool;
  84. private volatile String uuid = "";
  85. private volatile String bleg = "";
  86. private static final String BLEGSTR = "bleg";
  87. public String getTraceId(){
  88. return uuid;
  89. }
  90. /**
  91. * 转接座席超时时间
  92. */
  93. private static int transferAgentTimeOut = Integer.parseInt(
  94. SystemConfig.getValue("inbound-transfer-agent-timeout", "30")
  95. );
  96. private volatile SessionEntity agentSessionEntity = null;
  97. private volatile myESLEventListener eslListener;
  98. private volatile long lastPlayNoFreeAgentTime = System.currentTimeMillis() - 21000;
  99. private volatile boolean keepMusicPlayed = false;
  100. /**
  101. * 通话转接中
  102. */
  103. private volatile boolean transferring = false;
  104. /**
  105. * 通话转接失败
  106. */
  107. private volatile boolean transferFailed = false;
  108. /**
  109. * 当前esl连接池对象;
  110. */
  111. protected volatile EslConnectionPool eslConnectionPool;
  112. protected final String WAIT_WAV_FILE = "ivr/keep.wav";
  113. private Semaphore playKeepMusicSignal = new Semaphore(1);
  114. private Semaphore playBackStartSignal = new Semaphore(0);
  115. private Semaphore playBackStoppedSignal = new Semaphore(0);
  116. public void playWaitMusic(){
  117. log.info("{} playWaitMusic for call session. ", inboundDetail.getUuid());
  118. EslConnectionUtil.sendExecuteCommand(
  119. "playback",
  120. "$${sounds_dir}/" + WAIT_WAV_FILE,
  121. inboundDetail.getUuid()
  122. );
  123. }
  124. public boolean waitForPlayBackStoppedSignal() {
  125. try {
  126. return playBackStoppedSignal.tryAcquire(1, 2000, TimeUnit.MILLISECONDS);
  127. } catch (Throwable e) {
  128. }
  129. return false;
  130. }
  131. public boolean waitForPlayBackStartSignal() {
  132. try {
  133. return playBackStartSignal.tryAcquire(1, 2000, TimeUnit.MILLISECONDS);
  134. } catch (Throwable e) {
  135. }
  136. return false;
  137. }
  138. private void releasePlayBackStoppedSignal() {
  139. playBackStoppedSignal.release();
  140. }
  141. public boolean getPlayKeepMusicSignal() {
  142. try {
  143. return playKeepMusicSignal.tryAcquire(2000, TimeUnit.MILLISECONDS);
  144. }catch (Throwable e){
  145. }
  146. return false;
  147. }
  148. public void releasePlayKeepMusicSignal() {
  149. playKeepMusicSignal.release();
  150. }
  151. static {
  152. int fsEslMsgThreadPoolSize = Integer.parseInt(AppContextProvider.getEnvConfig("app-config.fs-esl-msg-thread-pool-size", "50"));
  153. fsMsgThreadPool = ThreadPoolCreator.create(fsEslMsgThreadPoolSize, "fsMsgThreadPool", 12L, 5000);
  154. int transferCallThreadPoolSize = Integer.parseInt( AppContextProvider.getEnvConfig("app-config.inbound-call.transfer-call-thread-pool-size", "15"));
  155. transferCallThreadPool = ThreadPoolCreator.create(transferCallThreadPoolSize, "transferCall", 24, 2000);
  156. startMonitor();
  157. }
  158. private AtomicInteger bLegIndex = new AtomicInteger(0);
  159. /**
  160. * 生成分机转接的Leg的uuid; 如果使用固定的uuid可能会导致出现重复的uuid;
  161. * [switch_core_session.c:2394 Duplicate UUID! 解决历史上出现的这个错误]
  162. * @return
  163. */
  164. private String generateBLegStr(){
  165. int index = bLegIndex.incrementAndGet();
  166. return String.format("%s-%s-%d", this.uuid, BLEGSTR, index);
  167. }
  168. private static boolean inboundCallMonitorEnabled = Boolean.parseBoolean(
  169. SystemConfig.getValue("inbound_call_monitor_enabled", "false")
  170. );
  171. private CallMonitorInfo callMonitorInfo;
  172. public CallMonitorInfo getCallMonitorInfo(){
  173. return callMonitorInfo;
  174. }
  175. public CallHandler(InboundDetail inboundDetail) {
  176. queueNo = globalQueueCounter.incrementAndGet();
  177. inboundDetail.setTransferredSucceed(false);
  178. log.info("{} init callHandler object ...", inboundDetail.getUuid());
  179. this.inboundDetail = inboundDetail;
  180. this.uuid = inboundDetail.getUuid();
  181. this.bleg = generateBLegStr();
  182. this.eslConnectionPool = EslConnectionUtil.getDefaultEslConnectionPool();
  183. eslListener = new myESLEventListener();
  184. this.eslConnectionPool.getDefaultEslConn().addListener(this.uuid + UuidKeys.ACD, eslListener);
  185. this.eslConnectionPool.getDefaultEslConn().removeOtherListenersExcludeByUuidKeys(this.uuid,
  186. new String[]{UuidKeys.ACD, UuidKeys.BATCH_CALL}
  187. );
  188. if(detectCallActive()) {
  189. callTaskList.put(uuid, this);
  190. }
  191. log.info("{} init CallHandler finished.", inboundDetail.getUuid());
  192. if(inboundCallMonitorEnabled) {
  193. CallMonitorInfo callMonitorInfo = new CallMonitorInfo(
  194. this.bleg,
  195. this.uuid,
  196. "",
  197. inboundDetail.getCaller(),
  198. inboundDetail.getRemoteVideoPort() > 0 ? PhoneCallType.VIDEO_CALL : PhoneCallType.AUDIO_CALL,
  199. CallDirection.INBOUND,
  200. inboundDetail.getGroupId(),
  201. inboundDetail.getInboundTime()
  202. );
  203. this.callMonitorInfo = callMonitorInfo;
  204. InboundMonitorDataPull.add(callMonitorInfo);
  205. }
  206. }
  207. /**
  208. * 呼入电话被重新入队列之后,重新初始化某些参数
  209. */
  210. public void ReInit(){
  211. transferring = false;
  212. transferFailed = false;
  213. inboundDetail.setTransferTime(0L);
  214. this.bleg = generateBLegStr();
  215. }
  216. /**
  217. * 发送挂机指令; 释放计数器; 关闭Esl连接;
  218. */
  219. public void hangup() {
  220. EslConnectionUtil.sendExecuteCommand(
  221. "hangup",
  222. "mandatory-hangup",
  223. this.uuid,
  224. this.eslConnectionPool
  225. );
  226. }
  227. /**
  228. * 开启监视线程; 如果一个通话1分钟还收到机器人语音,则强制结束它;
  229. * (很有可能是未收到挂机信号,强制结束是为了避免ThreadNum泄漏)
  230. *
  231. */
  232. private static void startMonitor(){
  233. new Thread(new Runnable() {
  234. @Override
  235. public void run() {
  236. while(true){
  237. try {
  238. monitorCall();
  239. }catch(Exception ex){
  240. log.error("monitorCall error: {}", ex.toString(), CommonUtils.getStackTraceString(ex.getStackTrace()));
  241. }
  242. ThreadUtil.sleep(10);
  243. }
  244. }
  245. }, "monitorCallTaskThread").start();
  246. }
  247. private static void monitorCall(){
  248. Iterator<Map.Entry<String, CallHandler>> it = callTaskList.entrySet().iterator();
  249. int processCount = 0;
  250. while (it.hasNext()){
  251. Map.Entry<String, CallHandler> entry = it.next();
  252. CallHandler task = entry.getValue();
  253. long currentTime = System.currentTimeMillis();
  254. long timePassed = currentTime - task.inboundDetail.getTransferTime() + 200;
  255. boolean transferTimeout = (task.inboundDetail.getTransferTime() > 0L) && (timePassed > transferAgentTimeOut * 1000);
  256. boolean transferredSucceed = task.inboundDetail.getTransferredSucceed();
  257. boolean hangup = task.inboundDetail.getHangup();
  258. // 通话未挂机且未被应答
  259. boolean notAnsweredAndNotHangup = !transferredSucceed && !hangup;
  260. boolean callExtensionNoAnswer = task.transferring && transferTimeout && notAnsweredAndNotHangup;
  261. boolean transferExtensionFailed = task.transferFailed;
  262. if(transferExtensionFailed || callExtensionNoAnswer){
  263. log.warn("{} Put the transfer-failed call back to the queue:{}", task.uuid, JSON.toJSONString(task.inboundDetail));
  264. EslConnectionUtil.sendExecuteCommand(
  265. "hangup",
  266. "Call-Extension-TimeOut",
  267. task.bleg,
  268. task.eslConnectionPool
  269. );
  270. // ReInit 必须在hangup之后,否则老的通话无法挂机;
  271. task.ReInit();
  272. if(InboundGroupHandler.addCallToQueue(task, task.getInboundDetail().getGroupId())){
  273. log.info("{} Put the transfer-failed call back to the queue successfully.", task.getInboundDetail().getUuid());
  274. }
  275. processCount++;
  276. continue;
  277. }
  278. long waitMills = (System.currentTimeMillis() - task.lastPlayNoFreeAgentTime);
  279. long interval = acdPlayQueueNumInterval * 1000;
  280. if (notAnsweredAndNotHangup && waitMills >= interval && !task.transferring) {
  281. StringBuilder sbTips = new StringBuilder();
  282. String tips = getQueueNumTips(task);
  283. if(!StringUtils.isNullOrEmpty(tips)){
  284. sbTips.append("file_string://");
  285. sbTips.append(tips);
  286. }else{
  287. sbTips.append("$${sounds_dir}/ivr/noFreeAgent.wav");
  288. }
  289. EslConnectionUtil.sendExecuteCommand(
  290. "playback",
  291. sbTips.toString(),
  292. task.uuid,
  293. task.eslConnectionPool
  294. );
  295. task.lastPlayNoFreeAgentTime = System.currentTimeMillis();
  296. continue;
  297. }
  298. if (notAnsweredAndNotHangup && !task.keepMusicPlayed ) {
  299. task.playWaitMusic();
  300. EslConnectionUtil.sendExecuteCommand(
  301. "playback",
  302. "$${sounds_dir}/ivr/pleaseWait.wav",
  303. task.uuid,
  304. task.eslConnectionPool
  305. );
  306. task.keepMusicPlayed = true;
  307. }
  308. }
  309. if(processCount != 0) {
  310. log.info("monitorThread, call session counter:" + processCount);
  311. }
  312. }
  313. /**
  314. * 获取排队人数播报提示音
  315. * @return
  316. */
  317. private static String getQueueNumTips(CallHandler task){
  318. InboundGroupHandler groupHandler = InboundGroupHandlerList.getInstance()
  319. .getCallHandlerBySkillGroupId(task.inboundDetail.getGroupId() );
  320. int queueNum = groupHandler.getQueuePosition(task);
  321. if(queueNum == 0) {
  322. return "";
  323. }
  324. queueNum = queueNum - 1;
  325. StringBuilder stringBuilder = new StringBuilder();
  326. stringBuilder.append("$${sounds_dir}/ivr/queue-wait-num-tips-start.wav");
  327. stringBuilder.append(";");
  328. stringBuilder.append("$${sounds_dir}/ivr/digits/");
  329. stringBuilder.append(queueNum);
  330. stringBuilder.append(".wav");
  331. stringBuilder.append(";");
  332. stringBuilder.append("$${sounds_dir}/ivr/queue-wait-num-tips-end.wav");
  333. return CommonUtils.joinTtsFiles(
  334. task.uuid, stringBuilder.toString(), false, false
  335. );
  336. }
  337. private void removeFsListener() {
  338. try {
  339. log.info("{} remove FreeSWITCH eslListener, uuid={}", uuid, this.uuid);
  340. callTaskList.remove(this.uuid);
  341. EslConnectionUtil.getDefaultEslConnectionPool().getDefaultEslConn().removeListener(this.uuid);
  342. //需要移除可能存在的bleg,避免产生内存泄漏;
  343. EslConnectionUtil.getDefaultEslConnectionPool().getDefaultEslConn().removeListener(bleg);
  344. }catch (Throwable ex) {
  345. log.error("{} error occurs while removeFsListener, details: {} {}",
  346. uuid, ex.toString(), CommonUtils.getStackTraceString(ex.getStackTrace()));
  347. }
  348. }
  349. /**
  350. * 为异常情况生成挂机事件数据;
  351. * @return
  352. */
  353. protected Map<String, String> generateHangupEvent(String hangupClause){
  354. Map<String, String> eslHeaders = new HashMap<>(5);
  355. eslHeaders.put("Event-Name", EventNames.CHANNEL_HANGUP);
  356. eslHeaders.put("Callee", this.inboundDetail.getCallee());
  357. eslHeaders.put("Unique-ID", this.uuid);
  358. eslHeaders.put("Hangup-Cause", hangupClause);
  359. eslHeaders.put("Event-Date-Timestamp", String.valueOf(System.currentTimeMillis() * 1000L));
  360. return eslHeaders;
  361. }
  362. /**
  363. * 检测通话是否挂机;
  364. * @return 已挂机返回false,未挂机返回true
  365. */
  366. private boolean detectCallActive(){
  367. EslMessage apiResponseMsg = EslConnectionUtil.sendSyncApiCommand(
  368. "uuid_exists",
  369. uuid,
  370. this.eslConnectionPool
  371. );
  372. if (apiResponseMsg != null && apiResponseMsg.getBodyLines().size() != 0) {
  373. String apiResponseText = apiResponseMsg.getBodyLines().get(0);
  374. if ("false".equalsIgnoreCase(apiResponseText)) {
  375. log.info("{} call session is hangup, stop process.", getTraceId());
  376. eslListener.processFsMsg(this.generateHangupEvent("hangup-before-robot-process"));
  377. return false;
  378. }
  379. } else {
  380. log.info("{} uuid_exists check error, can not get apiResponseMsg...", getTraceId());
  381. }
  382. return true;
  383. }
  384. /**
  385. * 转接电话到座席;
  386. * @param agent
  387. */
  388. public void tryToBridgeCall(SessionEntity agent) {
  389. transferCallThreadPool.execute(new Runnable() {
  390. @Override
  391. public void run() {
  392. log.info("{} Try to transfer the call to agent: {}", uuid, JSON.toJSONString(agent));
  393. agentSessionEntity = agent;
  394. inboundDetail.setOpnum(agentSessionEntity.getOpNum());
  395. inboundDetail.setExtnum(agentSessionEntity.getExtNum());
  396. AcdSqlQueue.addToSqlQueue(inboundDetail);
  397. MessageHandlerEngine engine = MessageHandlerEngineList.getInstance().getMsgHandlerEngine(agent.getSessionId());
  398. if(null != engine){
  399. //发送弹屏消息
  400. engine.sendReplyToAgent(new MessageResponse(RespStatus.NEW_INBOUND_CALL, "new inbound call", inboundDetail));
  401. transferring = true;
  402. playOpNumOnTransferring();
  403. if(inboundDetail.getHangup()){
  404. log.warn("{} The customer has hung-up. The transfer request is abandoned.", uuid);
  405. MessageHandlerEngineList.sendReplyToAgent(
  406. agent.getOpNum(),
  407. new MessageResponse(RespStatus.CALLER_HANGUP, "customer has benn hangup.")
  408. );
  409. ThreadUtil.sleep(50);
  410. resetAgentStatus();
  411. return;
  412. }
  413. CallApi callApi = ((CallApi)engine.getMessageHandleByName("call"));
  414. if(null != callApi) {
  415. String displayNumber = hideInboundNumber ?
  416. CommonUtils.hiddenPhoneNumber(inboundDetail.getCaller()) : inboundDetail.getCaller();
  417. eslConnectionPool.getDefaultEslConn().addListener(bleg, eslListener);
  418. String callType = inboundDetail.getRemoteVideoPort() > 0 ? PhoneCallType.VIDEO_CALL : PhoneCallType.AUDIO_CALL;
  419. SwitchChannel agentChannel = new SwitchChannel(bleg, uuid, callType, CallDirection.INBOUND);
  420. agentChannel.setPhoneNumber(callApi.getExtNum());
  421. SwitchChannel customerChannel = new SwitchChannel(uuid, bleg, callType, CallDirection.INBOUND);
  422. customerChannel.setPhoneNumber(inboundDetail.getCaller());
  423. customerChannel.setChannelState(ChanneState.BRIDGED);
  424. customerChannel.setFlag(ChannelFlag.HOLD_CALL);
  425. customerChannel.setInboundDetail(inboundDetail);
  426. if(!StringUtils.isNullOrEmpty(satisfSurveyIvrId)){
  427. customerChannel.setFlag(ChannelFlag.SATISFACTION_SURVEY_REQUIRED);
  428. EslConnectionUtil.sendExecuteCommand(
  429. "set",
  430. "park_after_bridge=true",
  431. uuid
  432. );
  433. }
  434. String asyncJobId = callApi.connectAgentExtNum(agentChannel, customerChannel,
  435. displayNumber, transferAgentTimeOut, inboundDetail.getInboundTime());
  436. eslConnectionPool.getDefaultEslConn().addListener(asyncJobId, eslListener);
  437. eslListener.setBackgroundJobUuid(asyncJobId);
  438. inboundDetail.setTransferTime(System.currentTimeMillis());
  439. log.info("{} transfer call response BackgroundJobUuid {}", bleg, asyncJobId);
  440. }else{
  441. log.error("{} cant not transfer the call, can not get callApi instance.", uuid);
  442. }
  443. }else{
  444. log.error("{} cant not get MessageHandlerEngine instance, cant not send pop-window msg to agent = {}", uuid, agent.getOpNum());
  445. }
  446. }
  447. });
  448. }
  449. private void resetAgentStatus(){
  450. if(inboundDetail.getManualAnsweredTime() == 0L && agentSessionEntity != null){
  451. // extension not answered, we must reset agent status.
  452. AppContextProvider.getBean(SysService.class).resetAgentBusyLockTimeEx(
  453. agentSessionEntity.getOpNum(),
  454. System.currentTimeMillis() - 5000
  455. );
  456. AgentCc.setAgentStatus(AgentStatus.free, agentSessionEntity.getOpNum());
  457. }
  458. }
  459. private void playOpNumOnTransferring(){
  460. if (playOpNum) {
  461. // 播放为当前通话服务的客服人员工号
  462. String destOpNum = agentSessionEntity.getExtNum();
  463. ThreadUtil.sleep(50);
  464. for (int i = 0; i <= destOpNum.length() - 1; i++) {
  465. EslConnectionUtil.sendExecuteCommand(
  466. "playback",
  467. "$${sounds_dir}/ivr/digits/" + destOpNum.charAt(i) + ".wav",
  468. uuid,
  469. eslConnectionPool
  470. );
  471. ThreadUtil.sleep(400);
  472. }
  473. EslConnectionUtil.sendExecuteCommand(
  474. "playback",
  475. "$${sounds_dir}/ivr/servicesForYou.wav",
  476. uuid,
  477. eslConnectionPool
  478. );
  479. ThreadUtil.sleep(1200);
  480. }
  481. }
  482. /**
  483. * 记录坐席挂机时间;
  484. */
  485. private void saveAgentHangupTime(String extNum){
  486. try {
  487. // 记录坐席挂机时间;
  488. if (agentSessionEntity != null) {
  489. AppContextProvider.getBean(SysService.class).saveHangupTime(extNum);
  490. }
  491. }catch (Throwable e){
  492. log.error("{} saveAgentHangupTime error: {} {} ",
  493. getTraceId(), e.toString(), CommonUtils.getStackTraceString(e.getStackTrace())
  494. );
  495. }
  496. }
  497. /**
  498. * 通话事件监听器 (用户应答、挂机、按键等事件时触发)
  499. **/
  500. class myESLEventListener implements IEslEventListener {
  501. private final Logger log = LoggerFactory.getLogger(myESLEventListener.class);
  502. private String backgroundJobUuid = "";
  503. private Semaphore callerParkSemaphore = new Semaphore(0);
  504. private myESLEventListener(){
  505. }
  506. public void setBackgroundJobUuid(String backgroundJobUuid) {
  507. this.backgroundJobUuid = backgroundJobUuid;
  508. }
  509. public void processFsMsg(Map<String, String> headers) {
  510. String uniqueID = headers.get("Unique-ID");
  511. String eventName = headers.get("Event-Name");
  512. String hangupCause = headers.get("Hangup-Cause")
  513. + ":" + headers.get("variable_proto_specific_hangup_cause");
  514. // esl消息从产生到被处理的延迟时间; 毫秒数
  515. long eventTime = Long.parseLong(headers.get("Event-Date-Timestamp")) / 1000L;
  516. long now = System.currentTimeMillis();
  517. long timeDelay = now - eventTime;
  518. log.info("{} The [{}] event takes {} ms from generation to processing.", uuid, eventName, timeDelay);
  519. String playbackFilePath = headers.get("Playback-File-Path");
  520. if (EventNames.PLAYBACK_START.equalsIgnoreCase(eventName)) {
  521. if (playbackFilePath != null && playbackFilePath.endsWith(WAIT_WAV_FILE)) {
  522. playBackStartSignal.release();
  523. }
  524. }else if (EventNames.PLAYBACK_STOP.equalsIgnoreCase(eventName)) {
  525. if (playbackFilePath != null && playbackFilePath.endsWith(WAIT_WAV_FILE)) {
  526. releasePlayBackStoppedSignal();
  527. log.info("{} recv PLAYBACK_STOP event for wav file {}. ", inboundDetail.getUuid(), playbackFilePath);
  528. boolean getAllowSignal = getPlayKeepMusicSignal();
  529. if(getAllowSignal) {
  530. if (inboundDetail.getManualAnsweredTime() == 0L) {
  531. playWaitMusic();
  532. waitForPlayBackStartSignal();
  533. }
  534. releasePlayKeepMusicSignal();
  535. }else{
  536. log.error("{} getPlayKeepMusicSignal error!", inboundDetail.getUuid());
  537. }
  538. }
  539. }else if (EventNames.CHANNEL_PARK.equalsIgnoreCase(eventName)) {
  540. if (uuid.equalsIgnoreCase(uniqueID)) {
  541. log.info("{} recv caller park event={}", uuid, eventName);
  542. callerParkSemaphore.release();
  543. }
  544. }
  545. else if (EventNames.CHANNEL_HANGUP.equalsIgnoreCase(eventName)) {
  546. if (!uniqueID.contains(BLEGSTR)) {
  547. if(inboundDetail.getManualAnsweredTime() == 0L) {
  548. log.info("{} Customer-Hangup event received, now we hangup extension. ", uuid);
  549. EslConnectionUtil.sendExecuteCommand("hangup", "Customer-Hangup", bleg );
  550. }
  551. if(agentSessionEntity != null) {
  552. saveAgentHangupTime(agentSessionEntity.getExtNum());
  553. }
  554. resetAgentStatus();
  555. log.info("{} save cdr, hangupCause: {}", uuid, hangupCause);
  556. String transferToConferenceTime = headers.get("variable_transfer_to_conference_time");
  557. if(!StringUtils.isNullOrEmpty(transferToConferenceTime)){
  558. try {
  559. now = DateUtils.parseDateTime(URLDecoder.decode(transferToConferenceTime,"utf-8")).getTime();
  560. log.info("{} parse transferToConferenceTime successfully. {}", uuid, now);
  561. }catch(Throwable throwable) {
  562. log.error("{} parse transferToConferenceTime error! {} {}", uuid,
  563. throwable.toString(), CommonUtils.getStackTraceString(throwable.getStackTrace())
  564. );
  565. }
  566. }
  567. inboundDetail.setHangup(true);
  568. inboundDetail.setHangupTime(now);
  569. if(inboundDetail.getAnsweredTime() > 0L) {
  570. inboundDetail.setAnsweredTimeLen(now - inboundDetail.getAnsweredTime());
  571. }
  572. inboundDetail.setTimeLen(now - inboundDetail.getInboundTime());
  573. if(inboundDetail.getManualAnsweredTime() > 0L) {
  574. inboundDetail.setManualAnsweredTimeLen(now - inboundDetail.getManualAnsweredTime());
  575. }
  576. List<JSONObject> origDialogueList = inboundDetail.getChatContent();
  577. origDialogueList.addAll(AsrResultListener.getDialogueByUuid(inboundDetail.getUuid()));
  578. inboundDetail.setChatContent(origDialogueList);
  579. removeFsListener();
  580. AcdSqlQueue.addToSqlQueue(inboundDetail);
  581. // 推送话单;
  582. CdrDetail cdrDetail = new CdrDetail();
  583. cdrDetail.setUuid(uuid);
  584. if(inboundDetail.getOutboundPhoneInfo() == null) {
  585. cdrDetail.setCdrType("inbound");
  586. }else{
  587. cdrDetail.setCdrType("outbound");
  588. }
  589. cdrDetail.setCdrBody(JSON.toJSONString(inboundDetail));
  590. CdrPush.addCdrToQueue(cdrDetail);
  591. }else {
  592. String extnum = headers.get("variable_extnum");
  593. saveAgentHangupTime(extnum);
  594. log.info("{} extension is hangup, hangupCause: {}", uuid, hangupCause);
  595. boolean answered = inboundDetail.getManualAnsweredTime() > 0L;
  596. if (!answered) {
  597. log.warn("{} The extension not answered the call session. Extension {} is abnormal. Please pay attention to it!", uuid, extnum);
  598. }
  599. resetAgentStatus();
  600. if (inboundDetail.getManualAnsweredTime() > 0L) {
  601. if (!StringUtils.isNullOrEmpty(satisfSurveyIvrId)) {
  602. try {
  603. callerParkSemaphore.tryAcquire(2100L, TimeUnit.MILLISECONDS);
  604. } catch (Throwable e) {
  605. }
  606. log.info("{} Try to start ivr process for satisfaction survey. ivrId={}.", inboundDetail.getUuid(), satisfSurveyIvrId);
  607. AppContextProvider.getBean(IvrEngine.class).startIvrSession(inboundDetail, satisfSurveyIvrId);
  608. }
  609. }
  610. }
  611. } else if (EventNames.CHANNEL_PROGRESS_MEDIA.equalsIgnoreCase(eventName)) {
  612. log.info("{} recv ringing event {}", uuid, eventName);
  613. } else if (EventNames.CHANNEL_ANSWER.equalsIgnoreCase(eventName)) {
  614. if (uniqueID.contains(BLEGSTR)) {
  615. // 桥接通话
  616. log.info("{} the extension {} has been connected, try to bridge session. {}",
  617. uuid,
  618. headers.get("variable_extnum"),
  619. inboundDetail.getCaller()
  620. );
  621. EslMessage eslMessage = EslConnectionUtil.sendSyncApiCommand(
  622. "uuid_bridge",
  623. String.format("%s %s",uuid, uniqueID),
  624. eslConnectionPool
  625. );
  626. boolean bridgeSucceed = false;
  627. if(eslMessage.getBodyLines().size() > 0){
  628. if(eslMessage.getBodyLines().get(0).contains("+OK")){
  629. bridgeSucceed = true;
  630. }
  631. }
  632. if(!bridgeSucceed){
  633. log.error("{} call bridged failed: {}", uuid, JSON.toJSONString(eslMessage));
  634. }else{
  635. log.info("{} call bridged successfully: {}", uuid, JSON.toJSONString(eslMessage));
  636. }
  637. assert null != agentSessionEntity;
  638. // 记录当前接听者;
  639. inboundDetail.setOpnum(agentSessionEntity.getOpNum());
  640. inboundDetail.setExtnum(agentSessionEntity.getExtNum());
  641. inboundDetail.setManualAnsweredTime(System.currentTimeMillis());
  642. inboundDetail.setTransferredSucceed(true);
  643. breakWaitMusic();
  644. log.info("{} resetAgentBusyLockTime. uerId={}, extNum={}",
  645. uuid,
  646. agentSessionEntity.getOpNum(),
  647. agentSessionEntity.getExtNum()
  648. );
  649. AppContextProvider.getBean(SysService.class).resetAgentBusyLockTime(agentSessionEntity.getOpNum());
  650. AcdSqlQueue.addToSqlQueue(inboundDetail);
  651. }
  652. }
  653. }
  654. private void breakWaitMusic(){
  655. boolean getAllowSignal = getPlayKeepMusicSignal();
  656. if(getAllowSignal) {
  657. long startTime = System.currentTimeMillis();
  658. int maxTry = 3;
  659. int tryCounter = 0;
  660. while (tryCounter < maxTry) {
  661. tryCounter++;
  662. EslConnectionUtil.sendSyncApiCommand("uuid_break", String.format("%s all", inboundDetail.getUuid()));
  663. if(waitForPlayBackStoppedSignal()){
  664. break;
  665. }
  666. }
  667. log.info("{} waitForPlayBackStoppedSignal took {} ms. ", inboundDetail.getUuid(), System.currentTimeMillis() - startTime);
  668. releasePlayKeepMusicSignal();
  669. }else{
  670. log.error("{} getPlayKeepMusicSignal error!", inboundDetail.getUuid());
  671. }
  672. }
  673. @Override
  674. public void eventReceived(String addr, EslEvent event) {
  675. // 这里创建单独的消息处理线程池, 避免拖慢Freeswitch消息处理速度
  676. fsMsgThreadPool.execute(new Runnable() {
  677. @Override
  678. public void run() {
  679. try {
  680. processFsMsg(event.getEventHeaders());
  681. }catch (Exception e){
  682. log.error("{} processFsMsg error : {} {}", uuid, e.toString(),
  683. CommonUtils.getStackTraceString(e.getStackTrace()));
  684. }
  685. }
  686. });
  687. }
  688. @Override
  689. public void backgroundJobResultReceived(String addr, EslEvent event) {
  690. eslConnectionPool.getDefaultEslConn().removeListener(this.backgroundJobUuid);
  691. String eslStr = event.toString();
  692. log.info("{} backgroundJobResultReceived [originate result] : {}" , uuid, eslStr);
  693. if (CommonUtils.checkTransferFailCase(eslStr)) {
  694. transferFailed = true;
  695. log.error("{} exception result got while connect extension,details:{}", uuid, event.toString());
  696. }
  697. }
  698. @Override
  699. public String context() {
  700. return CallHandler.class.getName();
  701. }
  702. }
  703. @Override
  704. public boolean equals(Object o) {
  705. if (this == o) {
  706. return true;
  707. // 引用相等返回 true
  708. }
  709. // 如果等于 null,或者对象类型不同返回 false
  710. if (!(o instanceof CallHandler)) {
  711. return false;
  712. }
  713. // 强转为自定义 CallHandler 类型
  714. CallHandler callHandler = (CallHandler) o;
  715. // 如果uuid相等,就返回 true
  716. return uuid.equals(callHandler.uuid);
  717. }
  718. @Override
  719. public int hashCode() {
  720. return Objects.hash(uuid);
  721. }
  722. }