Events.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. use Workerman\Lib\Timer;
  22. /**
  23. * 主逻辑
  24. * 主要是处理 onConnect onMessage onClose 三个方法
  25. * onConnect 和 onClose 如果不需要可以不用实现并删除
  26. */
  27. class Events
  28. {
  29. /**
  30. * 新建一个类的静态成员,用来保存数据库实例
  31. */
  32. public static $db = null;
  33. public static $global = null;
  34. /**
  35. * 进程启动后初始化数据库连接
  36. */
  37. public static function onWorkerStart($worker)
  38. {
  39. if (empty(self::$db)) {
  40. self::$db = new \Workerman\MySQL\Connection('192.168.2.186', '3306', 'root', '', 'customer_service');
  41. }
  42. if (empty(self::$global)) {
  43. self::$global = new \GlobalData\Client('127.0.0.1:2207');
  44. // 客服列表
  45. if (is_null(self::$global->kfList)) {
  46. self::$global->kfList = [];
  47. }
  48. // 会员列表[动态的,这里面只是目前未被分配的会员信息]
  49. if (is_null(self::$global->userList)) {
  50. self::$global->userList = [];
  51. }
  52. // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
  53. if (is_null(self::$global->uidSimpleList)) {
  54. self::$global->uidSimpleList = [];
  55. }
  56. // 当天的累积接入值
  57. $key = date('Ymd') . 'total_in';
  58. if (is_null(self::$global->$key)) {
  59. self::$global->$key = 0;
  60. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  61. unset(self::$global->$oldKey);
  62. unset($oldKey, $key);
  63. }
  64. // 成功接入值
  65. $key = date('Ymd') . 'success_in';
  66. if (is_null(self::$global->$key)) {
  67. self::$global->$key = 0;
  68. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  69. unset(self::$global->$oldKey);
  70. unset($oldKey, $key);
  71. }
  72. }
  73. // 定时统计数据
  74. if (0 === $worker->id) {
  75. // 1分钟统计一次实时数据
  76. Timer::add(60 * 1, function () {
  77. self::writeLog(1);
  78. });
  79. // 40分钟写一次当前日期点数的log数据
  80. Timer::add(60 * 40, function () {
  81. self::writeLog(2);
  82. });
  83. }
  84. }
  85. /**
  86. * 当客户端连接时触发
  87. * 如果业务不需此回调可以删除onConnect
  88. *
  89. * @param int $client_id 连接id
  90. */
  91. public static function onConnect($client_id)
  92. {
  93. // 检测是否开启自动应答
  94. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  95. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  96. $hello = [
  97. 'message_type' => 'helloMessage',
  98. 'data' => [
  99. 'name' => '智能助手',
  100. 'time' => date('H:i'),
  101. 'content' => htmlspecialchars($sayHello['0']['word'])
  102. ]
  103. ];
  104. Gateway::sendToClient($client_id, json_encode($hello, 256));
  105. unset($hello);
  106. }
  107. unset($sayHello);
  108. }
  109. /**
  110. * 当客户端发来消息时触发
  111. * @param int $client_id 连接id
  112. * @param mixed $message 具体消息
  113. */
  114. public static function onMessage($client_id, $message)
  115. {
  116. if ($message == '{"type":"ping"}') {
  117. Gateway::sendToCurrentClient('{"type":"pong"}');
  118. return;
  119. } else {
  120. //echo "onMessage: " . $message . "\r\n";
  121. //print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
  122. }
  123. $message = json_decode($message, true);
  124. switch ($message['type']) {
  125. // 客服初始化
  126. case 'init':
  127. $kfList = self::$global->kfList;
  128. // 如果该客服未在内存中记录则记录
  129. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  130. do {
  131. $newKfList = $kfList;
  132. $newKfList[$message['group']][$message['uid']] = [
  133. 'id' => $message['uid'],
  134. 'name' => $message['name'],
  135. 'avatar' => $message['avatar'],
  136. 'client_id' => $client_id,
  137. 'task' => 0,
  138. 'user_info' => []
  139. ];
  140. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  141. unset($newKfList, $kfList);
  142. } else if (isset($kfList[$message['group']][$message['uid']])) {
  143. do {
  144. $newKfList = $kfList;
  145. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  146. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  147. unset($newKfList, $kfList);
  148. }
  149. // 绑定 client_id 和 uid
  150. Gateway::bindUid($client_id, $message['uid']);
  151. $_SESSION['group'] = $message['group'];
  152. $_SESSION['iskefu'] = 1;
  153. $_SESSION['uid'] = $message['uid'];
  154. // TODO 尝试拉取用户来服务 [二期规划]
  155. break;
  156. // 顾客初始化
  157. case 'userInit';
  158. $userList = self::$global->userList;
  159. // 如果该顾客未在内存中记录则记录
  160. if (array_key_exists($message['uid'], $userList)) {
  161. $uidSimpleList = self::$global->uidSimpleList;
  162. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  163. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  164. sleep(1);
  165. Gateway::closeClient($oldclientid);
  166. }
  167. if (!array_key_exists($message['uid'], $userList)) {
  168. do {
  169. $NewUserList = $userList;
  170. $NewUserList[$message['uid']] = [
  171. 'id' => $message['uid'],
  172. 'name' => $message['name'],
  173. 'avatar' => $message['avatar'],
  174. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  175. 'browse' => Gateway::browse_info(),
  176. 'system' => Gateway::get_os(),
  177. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  178. 'group' => $message['group'],
  179. 'client_id' => $client_id
  180. ];
  181. } while (!self::$global->cas('userList', $userList, $NewUserList));
  182. unset($NewUserList, $userList);
  183. // 维护 UID对应的client_id 数组
  184. do {
  185. $old = $newList = self::$global->uidSimpleList;
  186. $newList[$message['uid']] = [
  187. $client_id,
  188. $message['group']
  189. ];
  190. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  191. unset($old, $newList);
  192. // 写入接入值
  193. $key = date('Ymd') . 'total_in';
  194. self::$global->$key = 0;
  195. do {
  196. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  197. unset(self::$global->$oldKey);
  198. } while (!self::$global->increment($key));
  199. unset($key);
  200. }
  201. // 绑定 client_id 和 uid
  202. Gateway::bindUid($client_id, $message['uid']);
  203. $_SESSION['iskefu'] = 0;
  204. $_SESSION['uid'] = $message['uid'];
  205. // 尝试分配新会员进入服务
  206. self::userOnlineTask($client_id, $message['group']);
  207. break;
  208. // 聊天
  209. case 'chatMessage':
  210. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  211. if (!empty($client)) {
  212. $chat_message = [
  213. 'message_type' => 'chatMessage',
  214. 'data' => [
  215. 'name' => $message['data']['from_name'],
  216. 'avatar' => $message['data']['from_avatar'],
  217. 'id' => $message['data']['from_id'],
  218. 'time' => date('H:i'),
  219. 'content' => htmlspecialchars($message['data']['content']),
  220. ]
  221. ];
  222. Gateway::sendToClient($client['0'], json_encode($chat_message));
  223. unset($chat_message);
  224. // 聊天信息入库
  225. $serviceLog = [
  226. 'from_id' => $message['data']['from_id'],
  227. 'from_name' => $message['data']['from_name'],
  228. 'from_avatar' => $message['data']['from_avatar'],
  229. 'to_id' => $message['data']['to_id'],
  230. 'to_name' => $message['data']['to_name'],
  231. 'content' => $message['data']['content'],
  232. 'servicelog_id' => $message['data']['conversationId'],
  233. 'time_line' => time()
  234. ];
  235. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  236. unset($serviceLog);
  237. }
  238. break;
  239. // 转接
  240. case 'changeGroup':
  241. // 通知客户端转接中
  242. $simpleList = self::$global->uidSimpleList;
  243. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  244. return;
  245. }
  246. $userClient = $simpleList[$message['uid']]['0'];
  247. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  248. $reLink = [
  249. 'message_type' => 'relinkMessage'
  250. ];
  251. Gateway::sendToClient($userClient, json_encode($reLink));
  252. unset($reLink);
  253. // 记录该客服与该会员的服务结束
  254. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  255. // 从当前客服的服务表中删除这个会员
  256. $old = $kfList = self::$global->kfList;
  257. if (!isset($kfList[$userGroup])) {
  258. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  259. // 逐一通知
  260. foreach (self::$global->userList as $vo) {
  261. $waitMessage = [
  262. 'message_type' => 'wait',
  263. 'data' => [
  264. 'content' => $waitMsg,
  265. ]
  266. ];
  267. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  268. unset($waitMessage);
  269. }
  270. return;
  271. }
  272. $myList = $kfList[$userGroup]; // 该客服分组数组
  273. foreach ($myList as $key => $vo) {
  274. if (in_array($userClient, $vo['user_info'])) {
  275. // 维护现在的该客服的服务信息
  276. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  277. foreach ($vo['user_info'] as $k => $v) {
  278. if ($userClient == $v) {
  279. unset($kfList[$userGroup][$key]['user_info'][$k]);
  280. break;
  281. }
  282. }
  283. break;
  284. }
  285. }
  286. while (!self::$global->cas('kfList', $old, $kfList)) {
  287. }; // 刷新内存中客服的服务列表
  288. unset($old, $kfList, $myList);
  289. // 将会员加入队列中
  290. $userList = self::$global->userList;
  291. do {
  292. $NewUserList = $userList;
  293. $NewUserList[$message['uid']] = [
  294. 'id' => $message['uid'],
  295. 'name' => $message['name'],
  296. 'avatar' => $message['avatar'],
  297. 'ip' => $message['ip'],
  298. 'group' => $message['group'], // 指定要链接的分组
  299. 'client_id' => $userClient
  300. ];
  301. } while (!self::$global->cas('userList', $userList, $NewUserList));
  302. unset($NewUserList, $userList);
  303. // 执行会员分配通知双方
  304. self::userOnlineTask($userClient, $message['group']);
  305. unset($userClient, $userGroup);
  306. break;
  307. case 'closeUser':
  308. $userInfo = self::$global->uidSimpleList;
  309. if (isset($userInfo[$message['uid']])) {
  310. $waitMessage = [
  311. 'message_type' => 'wait',
  312. 'data' => [
  313. 'content' => '暂时没有客服上班,请稍后再咨询。',
  314. ]
  315. ];
  316. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  317. unset($waitMessage);
  318. }
  319. unset($userInfo);
  320. break;
  321. // 机器人问答.
  322. case 'toRobot':
  323. self::toRobot($client_id, $message);
  324. break;
  325. // 评价.
  326. case 'evaluate':
  327. self::evaluate($client_id, $message);
  328. break;
  329. // 客服关闭会话.
  330. case 'kfCloseUser':
  331. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  332. if (!empty($client)) {
  333. self::serverClose($client['0']);
  334. }
  335. break;
  336. }
  337. }
  338. /**
  339. * 当用户断开连接时触发
  340. * @param int $client_id 连接id
  341. *
  342. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  343. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  344. */
  345. public static function onClose($client_id)
  346. {
  347. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  348. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  349. if (empty($uid)) {
  350. return;
  351. }
  352. if ($isKefuoff) {
  353. self::serviceOffline($client_id, $uid);
  354. } else {
  355. self::guestOffline($client_id, $uid);
  356. }
  357. return;
  358. }
  359. //客服下线了
  360. public static function serviceOffline($client_id, $uid)
  361. {
  362. $group = $_SESSION['group'];
  363. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  364. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  365. if (!empty($user_info)) {
  366. foreach ($user_info as $val) {
  367. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  368. Gateway::closeClient($val);
  369. }
  370. }
  371. unset($kefuinfo_old_new[$group][$uid]);
  372. do {
  373. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  374. return;
  375. }
  376. //用户下线了
  377. public static function guestOffline($client_id, $uid)
  378. {
  379. $kfuid = -1;
  380. $krclient_id = 0;
  381. $kfgroup = -1;
  382. $userToKf = $userToKfNew = self::$global->userToKf;
  383. if (isset($userToKfNew[$uid])) {
  384. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  385. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  386. unset($userToKfNew[$uid]);
  387. do {
  388. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  389. }
  390. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  391. if (isset($uidSimpleListNew[$uid])) {
  392. $kfgroup = $uidSimpleListNew[$uid]['1'];
  393. unset($uidSimpleListNew[$uid]);
  394. do {
  395. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  396. }
  397. $userList = $userListNew = self::$global->userList;
  398. if (!empty($userList)) {
  399. $ischange = 0;
  400. foreach ($userList as $key => $val) {
  401. if ($val['id'] == $uid) {
  402. unset($userListNew[$key]);
  403. $ischange = 1;
  404. break;
  405. }
  406. }
  407. if ($ischange) {
  408. do {
  409. } while (!self::$global->cas('userList', $userList, $userListNew));
  410. }
  411. }
  412. if ($kfuid != -1 && $kfgroup != -1) {
  413. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  414. $ischange_kf_list = 0;
  415. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  416. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  417. if ($infos) {
  418. if (is_array($infos)) {
  419. foreach ($infos as $key => $val) {
  420. if ($val == $client_id) {
  421. $ischange_kf_list = 1;
  422. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  423. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  424. }
  425. }
  426. }
  427. if ($ischange_kf_list) {
  428. do {
  429. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  430. $chat_message = [
  431. 'message_type' => 'userClose',
  432. 'data' => [
  433. 'content' => '用户连接已断开',
  434. 'time' => date('H:i'),
  435. ]
  436. ];
  437. self::$db->query("update `ws_service_log` set `status` = '3' where `user_id`= '$uid' and kf_id='$kfuid' and group_id=$kfgroup and status!=3 ");
  438. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  439. }
  440. }
  441. }
  442. }
  443. }
  444. /**
  445. * 客服结束会话
  446. * @param int $client_id 连接id
  447. *
  448. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  449. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  450. */
  451. public static function serverClose($client_id)
  452. {
  453. // 返回.
  454. $chat_message = [
  455. 'message_type' => 'closeBysever',
  456. 'data' => [
  457. 'content' => '客服停止了该会话',
  458. 'time' => date('H:i'),
  459. ]
  460. ];
  461. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  462. $isServiceUserOut = false;
  463. // 将会员服务信息,从客服的服务列表中移除
  464. $old = $kfList = self::$global->kfList;
  465. foreach ($kfList as $k => $v) {
  466. foreach ($v as $key => $vo) {
  467. if (in_array($client_id, $vo['user_info'])) {
  468. $isServiceUserOut = true;
  469. // 根据client id 去更新会话工单一些信息
  470. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  471. // 从会员的内存表中检索出该会员的信息,并更新内存
  472. $oldSimple = $simpleList = self::$global->uidSimpleList;
  473. $outUser = [];
  474. foreach ($simpleList as $u => $c) {
  475. if ($c['0'] == $client_id) {
  476. $outUser[] = [
  477. 'user_id' => $u,
  478. 'group_id' => $c['1']
  479. ];
  480. unset($simpleList[$u]);
  481. break;
  482. }
  483. }
  484. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  485. };
  486. unset($oldSimple, $simpleList);
  487. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  488. // 通知 客服删除退出的用户
  489. if (!empty($outUser)) {
  490. $del_message = [
  491. 'message_type' => 'delUser',
  492. 'data' => [
  493. 'id' => $outUser['0']['user_id']
  494. ]
  495. ];
  496. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  497. unset($del_message);
  498. // 尝试分配新会员进入服务
  499. self::userOfflineTask($outUser['0']['group_id']);
  500. }
  501. unset($outUser);
  502. // 维护现在的该客服的服务信息
  503. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  504. foreach ($vo['user_info'] as $m => $l) {
  505. if ($client_id == $l) {
  506. unset($kfList[$k][$key]['user_info'][$m]);
  507. break;
  508. }
  509. }
  510. // 刷新内存中客服的服务列表
  511. while (!self::$global->cas('kfList', $old, $kfList)) {
  512. };
  513. unset($old, $kfList);
  514. break;
  515. }
  516. }
  517. if ($isServiceUserOut) break;
  518. }
  519. // 尝试从排队的用户中删除退出的客户端
  520. if (false == $isServiceUserOut) {
  521. $old = $userList = self::$global->userList;
  522. foreach (self::$global->userList as $key => $vo) {
  523. if ($client_id == $vo['client_id']) {
  524. $isServiceUserOut = true;
  525. unset($userList[$key]);
  526. break;
  527. }
  528. }
  529. while (!self::$global->cas('userList', $old, $userList)) {
  530. };
  531. // 从会员的内存表中检索出该会员的信息,并更新内存
  532. $oldSimple = $simpleList = self::$global->uidSimpleList;
  533. foreach ($simpleList as $u => $c) {
  534. if ($c['0'] == $client_id) {
  535. unset($simpleList[$u]);
  536. break;
  537. }
  538. }
  539. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  540. };
  541. unset($oldSimple, $simpleList);
  542. }
  543. // 尝试是否是客服退出
  544. if (false == $isServiceUserOut) {
  545. $old = $kfList = self::$global->kfList;
  546. foreach (self::$global->kfList as $k => $v) {
  547. foreach ($v as $key => $vo) {
  548. // 客服服务列表中无数据,才去删除客服内存信息
  549. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  550. unset($kfList[$k][$key]);
  551. break;
  552. }
  553. }
  554. }
  555. while (!self::$global->cas('kfList', $old, $kfList)) {
  556. };
  557. }
  558. }
  559. /**
  560. * 有人退出
  561. * @param $group
  562. */
  563. private static function userOfflineTask($group)
  564. {
  565. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  566. $maxNumber = self::getMaxServiceNum();
  567. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  568. unset($maxNumber);
  569. if (1 == $res['code']) {
  570. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  571. }; // 更新客服数据
  572. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  573. }; // 更新会员数据
  574. // 通知会员发送信息绑定客服的id
  575. $noticeUser = [
  576. 'message_type' => 'connect',
  577. 'data' => [
  578. 'kf_id' => $res['data']['0'],
  579. 'kf_name' => $res['data']['1']
  580. ]
  581. ];
  582. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  583. unset($noticeUser);
  584. // 通知客服端绑定会员的信息
  585. $noticeKf = [
  586. 'message_type' => 'connect',
  587. 'data' => [
  588. 'user_info' => $res['data']['3']
  589. ]
  590. ];
  591. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  592. unset($noticeKf);
  593. // 逐一通知
  594. $number = 1;
  595. foreach (self::$global->userList as $vo) {
  596. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  597. $waitMessage = [
  598. 'message_type' => 'wait',
  599. 'data' => [
  600. 'content' => $waitMsg,
  601. ]
  602. ];
  603. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  604. $number++;
  605. }
  606. unset($waitMessage, $number);
  607. // 写入接入值
  608. $key = date('Ymd') . 'success_in';
  609. self::$global->$key = 0;
  610. do {
  611. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  612. unset(self::$global->$oldKey);
  613. } while (!self::$global->increment($key));
  614. unset($key);
  615. } else {
  616. switch ($res['code']) {
  617. case -1:
  618. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  619. // 逐一通知
  620. foreach (self::$global->userList as $vo) {
  621. $waitMessage = [
  622. 'message_type' => 'wait',
  623. 'data' => [
  624. 'content' => $waitMsg,
  625. ]
  626. ];
  627. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  628. }
  629. break;
  630. case -2:
  631. break;
  632. case -3:
  633. break;
  634. case -4:
  635. // 逐一通知
  636. $number = 1;
  637. foreach (self::$global->userList as $vo) {
  638. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  639. $waitMessage = [
  640. 'message_type' => 'wait',
  641. 'data' => [
  642. 'content' => $waitMsg,
  643. ]
  644. ];
  645. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  646. $number++;
  647. }
  648. break;
  649. }
  650. unset($waitMessage, $number);
  651. }
  652. }
  653. /**
  654. * 有人进入执行分配
  655. * @param $client_id
  656. * @param $group
  657. */
  658. private static function userOnlineTask($client_id, $group)
  659. {
  660. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  661. $maxNumber = self::getMaxServiceNum();
  662. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  663. unset($maxNumber);
  664. if (1 == $res['code']) {
  665. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  666. }; // 更新客服数据
  667. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  668. }; // 更新会员数据
  669. $userToKf = self::$global->userToKf;
  670. $userToKf[$res['data']['3']['id']] = [
  671. $res['data']['3']['id'],
  672. $res['data']['0']
  673. ];
  674. self::$global->userToKf = $userToKf;
  675. // 服务信息入库
  676. $serviceLog = [
  677. 'user_id' => $res['data']['3']['id'],
  678. 'client_id' => $res['data']['3']['client_id'],
  679. 'user_name' => $res['data']['3']['name'],
  680. 'user_ip' => $res['data']['3']['ip'],
  681. 'user_avatar' => $res['data']['3']['avatar'],
  682. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  683. 'start_time' => time(),
  684. 'group_id' => $group,
  685. 'website' => $res['data']['3']['website'],
  686. 'system' => $res['data']['3']['system'],
  687. 'browse' => $res['data']['3']['browse'],
  688. 'status' => 1,
  689. 'end_time' => 0
  690. ];
  691. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  692. unset($serviceLog);
  693. // 通知会员发送信息绑定客服的id
  694. $noticeUser = [
  695. 'message_type' => 'connect',
  696. 'data' => [
  697. 'kf_id' => $res['data']['0'],
  698. 'conversationId' => $conversationId,
  699. 'kf_name' => $res['data']['1']
  700. ]
  701. ];
  702. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  703. unset($noticeUser);
  704. // 通知客服端绑定会员的信息
  705. $noticeKf = [
  706. 'message_type' => 'connect',
  707. 'data' => [
  708. 'user_info' => $res['data']['3'],
  709. 'conversationId' => $conversationId,
  710. ]
  711. ];
  712. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  713. unset($noticeKf);
  714. // 写入接入值
  715. $key = date('Ymd') . 'success_in';
  716. self::$global->$key = 0;
  717. do {
  718. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  719. unset(self::$global->$oldKey);
  720. } while (!self::$global->increment($key));
  721. unset($key);
  722. } else {
  723. $waitMsg = '';
  724. switch ($res['code']) {
  725. case -1:
  726. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  727. break;
  728. case -2:
  729. break;
  730. case -3:
  731. break;
  732. case -4:
  733. $number = count(self::$global->userList);
  734. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  735. break;
  736. }
  737. $waitMessage = [
  738. 'message_type' => 'wait',
  739. 'data' => [
  740. 'content' => $waitMsg,
  741. ]
  742. ];
  743. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  744. unset($waitMessage);
  745. }
  746. }
  747. /**
  748. * 给客服分配会员【均分策略】
  749. * @param $kfList
  750. * @param $userList
  751. * @param $group
  752. * @param $total
  753. */
  754. private static function assignmentTask($kfList, $userList, $group, $total)
  755. {
  756. // 没有客服上线
  757. if (empty($kfList) || empty($kfList[$group])) {
  758. return ['code' => -1];
  759. }
  760. // 没有待分配的会员
  761. if (empty($userList)) {
  762. return ['code' => -2];
  763. }
  764. // 未设置每个客服可以服务多少人
  765. if (0 == $total) {
  766. return ['code' => -3];
  767. }
  768. // 查看该组的客服是否在线
  769. if (!isset($kfList[$group])) {
  770. return ['code' => -1];
  771. }
  772. $kf = $kfList[$group];
  773. $user = array_shift($userList);
  774. $kf = array_shift($kf);
  775. $min = $kf['task'];
  776. $flag = $kf['id'];
  777. foreach ($kfList[$group] as $key => $vo) {
  778. if ($vo['task'] < $min) {
  779. $min = $vo['task'];
  780. $flag = $key;
  781. }
  782. }
  783. unset($kf);
  784. // 需要排队了
  785. if ($kfList[$group][$flag]['task'] == $total) {
  786. return ['code' => -4];
  787. }
  788. $kfList[$group][$flag]['task'] += 1;
  789. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  790. return [
  791. 'code' => 1,
  792. 'data' => [
  793. $kfList[$group][$flag]['id'],
  794. $kfList[$group][$flag]['name'],
  795. $kfList[$group][$flag]['client_id'],
  796. $user,
  797. $kfList,
  798. $userList
  799. ]
  800. ];
  801. }
  802. /**
  803. * 获取最大的服务人数
  804. * @return int
  805. */
  806. private static function getMaxServiceNum()
  807. {
  808. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  809. if (!empty($maxNumber)) {
  810. $maxNumber = 5;
  811. } else {
  812. $maxNumber = $maxNumber['0']['max_service'];
  813. }
  814. return $maxNumber;
  815. }
  816. /**
  817. * 将内存中的数据写入统计表
  818. * @param int $flag
  819. */
  820. private static function writeLog($flag = 1)
  821. {
  822. // 上午 8点 到 22 点开始统计
  823. if (date('H') < 8 || date('H') > 22) {
  824. return;
  825. }
  826. // 当前正在接入的人 和 在线客服数
  827. $kfList = self::$global->kfList;
  828. $nowTalking = 0;
  829. $onlineKf = 0;
  830. if (!empty($kfList)) {
  831. foreach ($kfList as $key => $vo) {
  832. $onlineKf += count($vo);
  833. foreach ($vo as $k => $v) {
  834. $nowTalking += count($v['user_info']);
  835. }
  836. }
  837. }
  838. // 在队列中的用户
  839. $inQueue = count(self::$global->userList);
  840. $key = date('Ymd') . 'total_in';
  841. $key2 = date('Ymd') . 'success_in';
  842. $param = [
  843. 'is_talking' => $nowTalking,
  844. 'in_queue' => $inQueue,
  845. 'online_kf' => $onlineKf,
  846. 'success_in' => self::$global->$key2,
  847. 'total_in' => self::$global->$key,
  848. 'now_date' => date('Y-m-d')
  849. ];
  850. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  851. if (2 == $flag) {
  852. $param = [
  853. 'is_talking' => $nowTalking,
  854. 'in_queue' => $inQueue,
  855. 'online_kf' => $onlineKf,
  856. 'success_in' => self::$global->$key2,
  857. 'total_in' => self::$global->$key,
  858. 'add_date' => date('Y-m-d'),
  859. 'add_hour' => date('H'),
  860. 'add_minute' => date('i'),
  861. ];
  862. self::$db->insert('ws_service_data')->cols($param)->query();
  863. }
  864. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  865. }
  866. /**
  867. * 机器人问答
  868. * @param $client_id 服务ID
  869. * @param $message 数据
  870. */
  871. private static function toRobot($client_id, $message)
  872. {
  873. $groups_id = $message['data']['groups_id'];
  874. $robot_name = $message['data']['robot_name'];
  875. $robotgroups_id = $message['data']['robotgroups_id'];
  876. // 查询问题.
  877. $getRobot = self::$db->query("select `robot_content` from `ws_robot` where `robot_status`= 1 and `groups_id`= '" . $groups_id . "' and `robot_name`= '" . $robot_name . "' and `robotgroups_id`= '" . $robotgroups_id . "'");
  878. $chat_message = [
  879. 'message_type' => 'chatMessage',
  880. 'data' => [
  881. 'name' => '智能助手',
  882. 'time' => date('H:i'),
  883. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  884. ]
  885. ];
  886. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  887. }
  888. /**
  889. * 评价
  890. * @param $client_id 服务ID
  891. * @param $message 数据
  892. */
  893. private static function evaluate($client_id, $message)
  894. {
  895. // 修改数据库.
  896. $evaluate_id = $message['data']['evaluate_id'];
  897. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  898. if ($result) {
  899. $chat_message = [
  900. 'message_type' => 'evaluate',
  901. 'data' => [
  902. 'status' => 1,
  903. 'time' => date('H:i'),
  904. ]
  905. ];
  906. } else {
  907. $chat_message = [
  908. 'message_type' => 'evaluate',
  909. 'data' => [
  910. 'status' => 2,
  911. 'time' => date('H:i'),
  912. ]
  913. ];
  914. }
  915. Gateway::sendToClient($client_id, json_encode($chat_message));
  916. }
  917. //踢掉同一用户的旧用户
  918. private static function tickOlduser($uid)
  919. {
  920. }
  921. }