Events.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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. self::userInitEnt($client_id, $message);
  159. break;
  160. // 聊天
  161. case 'chatMessage':
  162. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  163. if (!empty($client)) {
  164. $chat_message = [
  165. 'message_type' => 'chatMessage',
  166. 'data' => [
  167. 'name' => $message['data']['from_name'],
  168. 'avatar' => $message['data']['from_avatar'],
  169. 'id' => $message['data']['from_id'],
  170. 'time' => date('H:i'),
  171. 'content' => htmlspecialchars($message['data']['content']),
  172. ]
  173. ];
  174. Gateway::sendToClient($client['0'], json_encode($chat_message));
  175. unset($chat_message);
  176. // 聊天信息入库
  177. $serviceLog = [
  178. 'from_id' => $message['data']['from_id'],
  179. 'from_name' => $message['data']['from_name'],
  180. 'from_avatar' => $message['data']['from_avatar'],
  181. 'to_id' => $message['data']['to_id'],
  182. 'to_name' => $message['data']['to_name'],
  183. 'content' => $message['data']['content'],
  184. 'servicelog_id' => $message['data']['conversationId'],
  185. 'time_line' => time()
  186. ];
  187. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  188. unset($serviceLog);
  189. }
  190. break;
  191. // 转接
  192. case 'changeGroup':
  193. // 通知客户端转接中
  194. $simpleList = self::$global->uidSimpleList;
  195. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  196. return;
  197. }
  198. $userClient = $simpleList[$message['uid']]['0'];
  199. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  200. $reLink = [
  201. 'message_type' => 'relinkMessage'
  202. ];
  203. Gateway::sendToClient($userClient, json_encode($reLink));
  204. unset($reLink);
  205. // 记录该客服与该会员的服务结束
  206. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  207. // 从当前客服的服务表中删除这个会员
  208. $old = $kfList = self::$global->kfList;
  209. if (!isset($kfList[$userGroup])) {
  210. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  211. // 逐一通知
  212. foreach (self::$global->userList as $vo) {
  213. $waitMessage = [
  214. 'message_type' => 'wait',
  215. 'data' => [
  216. 'content' => $waitMsg,
  217. ]
  218. ];
  219. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  220. unset($waitMessage);
  221. }
  222. return;
  223. }
  224. $myList = $kfList[$userGroup]; // 该客服分组数组
  225. foreach ($myList as $key => $vo) {
  226. if (in_array($userClient, $vo['user_info'])) {
  227. // 维护现在的该客服的服务信息
  228. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  229. foreach ($vo['user_info'] as $k => $v) {
  230. if ($userClient == $v) {
  231. unset($kfList[$userGroup][$key]['user_info'][$k]);
  232. break;
  233. }
  234. }
  235. break;
  236. }
  237. }
  238. while (!self::$global->cas('kfList', $old, $kfList)) {
  239. }; // 刷新内存中客服的服务列表
  240. unset($old, $kfList, $myList);
  241. // 将会员加入队列中
  242. $userList = self::$global->userList;
  243. do {
  244. $NewUserList = $userList;
  245. $NewUserList[$message['uid']] = [
  246. 'id' => $message['uid'],
  247. 'name' => $message['name'],
  248. 'avatar' => $message['avatar'],
  249. 'ip' => $message['ip'],
  250. 'group' => $message['group'], // 指定要链接的分组
  251. 'client_id' => $userClient
  252. ];
  253. } while (!self::$global->cas('userList', $userList, $NewUserList));
  254. unset($NewUserList, $userList);
  255. // 执行会员分配通知双方
  256. self::userOnlineTask($userClient, $message['group']);
  257. unset($userClient, $userGroup);
  258. break;
  259. case 'closeUser':
  260. $userInfo = self::$global->uidSimpleList;
  261. if (isset($userInfo[$message['uid']])) {
  262. $waitMessage = [
  263. 'message_type' => 'wait',
  264. 'data' => [
  265. 'content' => '暂时没有客服上班,请稍后再咨询。',
  266. ]
  267. ];
  268. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  269. unset($waitMessage);
  270. }
  271. unset($userInfo);
  272. break;
  273. // 机器人问答.
  274. case 'toRobot':
  275. self::toRobot($client_id, $message);
  276. break;
  277. // 评价.
  278. case 'evaluate':
  279. self::evaluate($client_id, $message);
  280. break;
  281. // 客服关闭会话.
  282. case 'kfCloseUser':
  283. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  284. if (!empty($client)) {
  285. self::serverClose($client['0']);
  286. }
  287. break;
  288. // default:
  289. // Gateway::closeClient($client_id);
  290. }
  291. }
  292. //用户发送邦定用户事件
  293. public static function userInitEnt($client_id, $message)
  294. {
  295. $userList = self::$global->userList;
  296. // 如果该顾客未在内存中记录则记录
  297. $uidSimpleList = self::$global->uidSimpleList;
  298. if (isset($uidSimpleList[$message['uid']])) {
  299. $uidSimpleList = self::$global->uidSimpleList;
  300. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  301. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  302. Gateway::closeClient($oldclientid);
  303. sleep(2);
  304. }
  305. if (!array_key_exists($message['uid'], $userList)) {
  306. do {
  307. $NewUserList = $userList;
  308. $NewUserList[$message['uid']] = [
  309. 'id' => $message['uid'],
  310. 'name' => $message['name'],
  311. 'avatar' => $message['avatar'],
  312. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  313. 'browse' => Gateway::browse_info(),
  314. 'system' => Gateway::get_os(),
  315. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  316. 'group' => $message['group'],
  317. 'client_id' => $client_id
  318. ];
  319. } while (!self::$global->cas('userList', $userList, $NewUserList));
  320. unset($NewUserList, $userList);
  321. // 维护 UID对应的client_id 数组
  322. do {
  323. $old = $newList = self::$global->uidSimpleList;
  324. $newList[$message['uid']] = [
  325. $client_id,
  326. $message['group']
  327. ];
  328. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  329. unset($old, $newList);
  330. // 写入接入值
  331. $key = date('Ymd') . 'total_in';
  332. self::$global->$key = 0;
  333. do {
  334. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  335. unset(self::$global->$oldKey);
  336. } while (!self::$global->increment($key));
  337. unset($key);
  338. }
  339. // 绑定 client_id 和 uid
  340. Gateway::bindUid($client_id, $message['uid']);
  341. $_SESSION['iskefu'] = 0;
  342. $_SESSION['uid'] = $message['uid'];
  343. // 尝试分配新会员进入服务
  344. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  345. }
  346. /**
  347. * 当用户断开连接时触发
  348. * @param int $client_id 连接id
  349. *
  350. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  351. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  352. */
  353. public static function onClose($client_id)
  354. {
  355. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  356. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  357. if (empty($uid)) {
  358. return;
  359. }
  360. if ($isKefuoff) {
  361. self::serviceOffline($client_id, $uid);
  362. } else {
  363. self::guestOffline($client_id, $uid);
  364. }
  365. return;
  366. }
  367. //客服下线了
  368. public static function serviceOffline($client_id, $uid)
  369. {
  370. $group = $_SESSION['group'];
  371. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  372. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  373. $simpliUsers = self::$global->uidSimpleList;
  374. $simpliUsersID_UID_Arr = [];
  375. if (!empty($simpliUsers)) {
  376. foreach ($simpliUsers as $key => $val) {
  377. $simpliUsersID_UID_Arr[$val['0']] = $key;
  378. }
  379. }
  380. $now = time();
  381. if (!empty($user_info)) {
  382. foreach ($user_info as $val) {
  383. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  384. if (isset($simpliUsersID_UID_Arr[$val])) {
  385. self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2 ");
  386. }
  387. Gateway::closeClient($val);
  388. }
  389. }
  390. unset($kefuinfo_old_new[$group][$uid]);
  391. do {
  392. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  393. return;
  394. }
  395. //用户下线了
  396. public static function guestOffline($client_id, $uid)
  397. {
  398. $kfuid = -1;
  399. $krclient_id = 0;
  400. $kfgroup = -1;
  401. $userToKf = $userToKfNew = self::$global->userToKf;
  402. if (isset($userToKfNew[$uid])) {
  403. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  404. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  405. unset($userToKfNew[$uid]);
  406. do {
  407. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  408. }
  409. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  410. if (isset($uidSimpleListNew[$uid])) {
  411. $kfgroup = $uidSimpleListNew[$uid]['1'];
  412. unset($uidSimpleListNew[$uid]);
  413. do {
  414. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  415. }
  416. $userList = $userListNew = self::$global->userList;
  417. if (!empty($userList)) {
  418. $ischange = 0;
  419. foreach ($userList as $key => $val) {
  420. if ($val['id'] == $uid) {
  421. unset($userListNew[$key]);
  422. $ischange = 1;
  423. break;
  424. }
  425. }
  426. if ($ischange) {
  427. do {
  428. } while (!self::$global->cas('userList', $userList, $userListNew));
  429. }
  430. }
  431. if ($kfuid != -1 && $kfgroup != -1) {
  432. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  433. $ischange_kf_list = 0;
  434. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  435. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  436. if ($infos) {
  437. if (is_array($infos)) {
  438. foreach ($infos as $key => $val) {
  439. if ($val == $client_id) {
  440. $ischange_kf_list = 1;
  441. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  442. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  443. }
  444. }
  445. }
  446. if ($ischange_kf_list) {
  447. do {
  448. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  449. $chat_message = [
  450. 'message_type' => 'userClose',
  451. 'data' => [
  452. 'content' => '用户连接已断开',
  453. 'time' => date('H:i'),
  454. ]
  455. ];
  456. $now = time();
  457. $kf__uid = substr($kfuid, 2);
  458. $sql = "update `ws_service_log` set `status` = '3',end_time=$now where `user_id`= '$uid' and kf_id='$kf__uid' and group_id=$kfgroup and status=1 ";
  459. //echo "客户退出:". $sql ."\n";
  460. self::$db->query($sql);
  461. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  462. }
  463. }
  464. }
  465. }
  466. }
  467. /**
  468. * 客服结束会话
  469. * @param int $client_id 连接id
  470. *
  471. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  472. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  473. */
  474. public static function serverClose($client_id)
  475. {
  476. // 返回.
  477. $chat_message = [
  478. 'message_type' => 'closeBysever',
  479. 'data' => [
  480. 'content' => '客服停止了该会话',
  481. 'time' => date('H:i'),
  482. ]
  483. ];
  484. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  485. $isServiceUserOut = false;
  486. // 将会员服务信息,从客服的服务列表中移除
  487. $old = $kfList = self::$global->kfList;
  488. foreach ($kfList as $k => $v) {
  489. foreach ($v as $key => $vo) {
  490. if (in_array($client_id, $vo['user_info'])) {
  491. $isServiceUserOut = true;
  492. // 根据client id 去更新会话工单一些信息
  493. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  494. // 从会员的内存表中检索出该会员的信息,并更新内存
  495. $oldSimple = $simpleList = self::$global->uidSimpleList;
  496. $outUser = [];
  497. foreach ($simpleList as $u => $c) {
  498. if ($c['0'] == $client_id) {
  499. $outUser[] = [
  500. 'user_id' => $u,
  501. 'group_id' => $c['1']
  502. ];
  503. unset($simpleList[$u]);
  504. break;
  505. }
  506. }
  507. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  508. };
  509. unset($oldSimple, $simpleList);
  510. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  511. // 通知 客服删除退出的用户
  512. if (!empty($outUser)) {
  513. $del_message = [
  514. 'message_type' => 'delUser',
  515. 'data' => [
  516. 'id' => $outUser['0']['user_id']
  517. ]
  518. ];
  519. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  520. unset($del_message);
  521. // 尝试分配新会员进入服务
  522. self::userOfflineTask($outUser['0']['group_id']);
  523. }
  524. unset($outUser);
  525. // 维护现在的该客服的服务信息
  526. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  527. foreach ($vo['user_info'] as $m => $l) {
  528. if ($client_id == $l) {
  529. unset($kfList[$k][$key]['user_info'][$m]);
  530. break;
  531. }
  532. }
  533. // 刷新内存中客服的服务列表
  534. while (!self::$global->cas('kfList', $old, $kfList)) {
  535. };
  536. unset($old, $kfList);
  537. break;
  538. }
  539. }
  540. if ($isServiceUserOut) break;
  541. }
  542. // 尝试从排队的用户中删除退出的客户端
  543. if (false == $isServiceUserOut) {
  544. $old = $userList = self::$global->userList;
  545. foreach (self::$global->userList as $key => $vo) {
  546. if ($client_id == $vo['client_id']) {
  547. $isServiceUserOut = true;
  548. unset($userList[$key]);
  549. break;
  550. }
  551. }
  552. while (!self::$global->cas('userList', $old, $userList)) {
  553. };
  554. // 从会员的内存表中检索出该会员的信息,并更新内存
  555. $oldSimple = $simpleList = self::$global->uidSimpleList;
  556. foreach ($simpleList as $u => $c) {
  557. if ($c['0'] == $client_id) {
  558. unset($simpleList[$u]);
  559. break;
  560. }
  561. }
  562. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  563. };
  564. unset($oldSimple, $simpleList);
  565. }
  566. // 尝试是否是客服退出
  567. if (false == $isServiceUserOut) {
  568. $old = $kfList = self::$global->kfList;
  569. foreach (self::$global->kfList as $k => $v) {
  570. foreach ($v as $key => $vo) {
  571. // 客服服务列表中无数据,才去删除客服内存信息
  572. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  573. unset($kfList[$k][$key]);
  574. break;
  575. }
  576. }
  577. }
  578. while (!self::$global->cas('kfList', $old, $kfList)) {
  579. };
  580. }
  581. }
  582. /**
  583. * 有人退出
  584. * @param $group
  585. */
  586. private static function userOfflineTask($group)
  587. {
  588. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  589. $maxNumber = self::getMaxServiceNum();
  590. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  591. unset($maxNumber);
  592. if (1 == $res['code']) {
  593. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  594. }; // 更新客服数据
  595. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  596. }; // 更新会员数据
  597. // 通知会员发送信息绑定客服的id
  598. $noticeUser = [
  599. 'message_type' => 'connect',
  600. 'data' => [
  601. 'kf_id' => $res['data']['0'],
  602. 'kf_name' => $res['data']['1']
  603. ]
  604. ];
  605. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  606. unset($noticeUser);
  607. // 通知客服端绑定会员的信息
  608. $noticeKf = [
  609. 'message_type' => 'connect',
  610. 'data' => [
  611. 'user_info' => $res['data']['3']
  612. ]
  613. ];
  614. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  615. unset($noticeKf);
  616. // 逐一通知
  617. $number = 1;
  618. foreach (self::$global->userList as $vo) {
  619. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  620. $waitMessage = [
  621. 'message_type' => 'wait',
  622. 'data' => [
  623. 'content' => $waitMsg,
  624. ]
  625. ];
  626. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  627. $number++;
  628. }
  629. unset($waitMessage, $number);
  630. // 写入接入值
  631. $key = date('Ymd') . 'success_in';
  632. self::$global->$key = 0;
  633. do {
  634. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  635. unset(self::$global->$oldKey);
  636. } while (!self::$global->increment($key));
  637. unset($key);
  638. } else {
  639. switch ($res['code']) {
  640. case -1:
  641. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  642. // 逐一通知
  643. foreach (self::$global->userList as $vo) {
  644. $waitMessage = [
  645. 'message_type' => 'wait',
  646. 'data' => [
  647. 'content' => $waitMsg,
  648. ]
  649. ];
  650. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  651. }
  652. break;
  653. case -2:
  654. break;
  655. case -3:
  656. break;
  657. case -4:
  658. // 逐一通知
  659. $number = 1;
  660. foreach (self::$global->userList as $vo) {
  661. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  662. $waitMessage = [
  663. 'message_type' => 'wait',
  664. 'data' => [
  665. 'content' => $waitMsg,
  666. ]
  667. ];
  668. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  669. $number++;
  670. }
  671. break;
  672. }
  673. unset($waitMessage, $number);
  674. }
  675. }
  676. /**
  677. * 有人进入执行分配
  678. * @param $client_id
  679. * @param $group
  680. * @param $uid
  681. */
  682. private static function userOnlineTask($client_id, $group, $uid = 0)
  683. {
  684. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  685. $maxNumber = self::getMaxServiceNum();
  686. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  687. unset($maxNumber);
  688. if (1 == $res['code']) {
  689. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  690. }; // 更新客服数据
  691. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  692. }; // 更新会员数据
  693. $userToKf = self::$global->userToKf;
  694. $userToKf[$res['data']['3']['id']] = [
  695. $res['data']['3']['id'],
  696. $res['data']['0']
  697. ];
  698. self::$global->userToKf = $userToKf;
  699. // 服务信息入库
  700. $serviceLog = [
  701. 'user_id' => $res['data']['3']['id'],
  702. 'client_id' => $res['data']['3']['client_id'],
  703. 'user_name' => $res['data']['3']['name'],
  704. 'user_ip' => $res['data']['3']['ip'],
  705. 'user_avatar' => $res['data']['3']['avatar'],
  706. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  707. 'start_time' => time(),
  708. 'group_id' => $group,
  709. 'website' => $res['data']['3']['website'],
  710. 'system' => $res['data']['3']['system'],
  711. 'browse' => $res['data']['3']['browse'],
  712. 'status' => 1,
  713. 'end_time' => 0
  714. ];
  715. $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
  716. if (!$hisSession) {
  717. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  718. } else {
  719. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  720. $conversationId = $hisSession['servicelog_id'];
  721. }
  722. unset($serviceLog);
  723. // 通知会员发送信息绑定客服的id
  724. $noticeUser = [
  725. 'message_type' => 'connect',
  726. 'data' => [
  727. 'kf_id' => $res['data']['0'],
  728. 'conversationId' => $conversationId,
  729. 'kf_name' => $res['data']['1']
  730. ]
  731. ];
  732. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  733. unset($noticeUser);
  734. // 通知客服端绑定会员的信息
  735. $noticeKf = [
  736. 'message_type' => 'connect',
  737. 'data' => [
  738. 'user_info' => $res['data']['3'],
  739. 'conversationId' => $conversationId,
  740. ]
  741. ];
  742. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  743. unset($noticeKf);
  744. // 写入接入值
  745. $key = date('Ymd') . 'success_in';
  746. self::$global->$key = 0;
  747. do {
  748. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  749. unset(self::$global->$oldKey);
  750. } while (!self::$global->increment($key));
  751. unset($key);
  752. } else {
  753. $waitMsg = '';
  754. switch ($res['code']) {
  755. case -1:
  756. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  757. break;
  758. case -2:
  759. break;
  760. case -3:
  761. break;
  762. case -4:
  763. $number = count(self::$global->userList);
  764. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  765. break;
  766. }
  767. $waitMessage = [
  768. 'message_type' => 'wait',
  769. 'data' => [
  770. 'content' => $waitMsg,
  771. ]
  772. ];
  773. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  774. unset($waitMessage);
  775. }
  776. }
  777. /**
  778. * 给客服分配会员【均分策略】
  779. * @param $kfList
  780. * @param $userList
  781. * @param $group
  782. * @param $total
  783. */
  784. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  785. {
  786. // 没有客服上线
  787. if (empty($kfList) || empty($kfList[$group])) {
  788. return ['code' => -1];
  789. }
  790. // 没有待分配的会员
  791. if (empty($userList)) {
  792. return ['code' => -2];
  793. }
  794. // 未设置每个客服可以服务多少人
  795. if (0 == $total) {
  796. return ['code' => -3];
  797. }
  798. // 查看该组的客服是否在线
  799. if (!isset($kfList[$group])) {
  800. return ['code' => -1];
  801. }
  802. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  803. $odltalksession = false;
  804. $user = $user_first = array_shift($userList);
  805. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  806. $timevalielimit = time() - 60 * 5;
  807. $odltalksession = self::$db->select('*')->from('ws_service_log')->where('user_id=:uid and `group`=:group and `status`=3 and end_time>=:timevalielimit"')->bindValues(array('uid' => $uid, 'group' => $group, 'timevalielimit' => $timevalielimit))->row();
  808. if ($odltalksession) {
  809. foreach ($userList as $ttkey => $ttval) {
  810. if ($ttval['id'] == $uid) {
  811. array_unshift($userList, $user);
  812. $user = $userList[$ttkey];
  813. unset($userList[$ttkey]);
  814. break;
  815. }
  816. }
  817. }
  818. }
  819. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  820. if ($odltalksession) {
  821. $oldkrid = 'KF' . $odltalksession['kf_id'];
  822. if (isset($kfList[$group][$oldkrid])) {
  823. $kf = $kfList[$group][$oldkrid];
  824. $min = $kf['task'];
  825. $flag = $kf['id'];
  826. unset($kfList[$group][$oldkrid]);
  827. } else {
  828. goto NOSIGNKF;
  829. }
  830. } else {
  831. NOSIGNKF:
  832. $kf = $kfList[$group];
  833. $kf = array_shift($kf);
  834. $min = $kf['task'];
  835. $flag = $kf['id'];
  836. foreach ($kfList[$group] as $key => $vo) {
  837. if ($vo['task'] < $min) {
  838. $min = $vo['task'];
  839. $flag = $key;
  840. }
  841. }
  842. unset($kf);
  843. }
  844. // 需要排队了
  845. if ($kfList[$group][$flag]['task'] == $total) {
  846. return ['code' => -4];
  847. }
  848. $kfList[$group][$flag]['task'] += 1;
  849. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  850. return [
  851. 'code' => 1,
  852. 'data' => [
  853. $kfList[$group][$flag]['id'],
  854. $kfList[$group][$flag]['name'],
  855. $kfList[$group][$flag]['client_id'],
  856. $user,
  857. $kfList,
  858. $userList
  859. ]
  860. ];
  861. }
  862. /**
  863. * 获取最大的服务人数
  864. * @return int
  865. */
  866. private static function getMaxServiceNum()
  867. {
  868. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  869. if (!empty($maxNumber)) {
  870. $maxNumber = 5;
  871. } else {
  872. $maxNumber = $maxNumber['0']['max_service'];
  873. }
  874. return $maxNumber;
  875. }
  876. /**
  877. * 将内存中的数据写入统计表
  878. * @param int $flag
  879. */
  880. private static function writeLog($flag = 1)
  881. {
  882. // 上午 8点 到 22 点开始统计
  883. if (date('H') < 8 || date('H') > 22) {
  884. return;
  885. }
  886. // 当前正在接入的人 和 在线客服数
  887. $kfList = self::$global->kfList;
  888. $nowTalking = 0;
  889. $onlineKf = 0;
  890. if (!empty($kfList)) {
  891. foreach ($kfList as $key => $vo) {
  892. $onlineKf += count($vo);
  893. foreach ($vo as $k => $v) {
  894. $nowTalking += count($v['user_info']);
  895. }
  896. }
  897. }
  898. // 在队列中的用户
  899. $inQueue = count(self::$global->userList);
  900. $key = date('Ymd') . 'total_in';
  901. $key2 = date('Ymd') . 'success_in';
  902. $param = [
  903. 'is_talking' => $nowTalking,
  904. 'in_queue' => $inQueue,
  905. 'online_kf' => $onlineKf,
  906. 'success_in' => self::$global->$key2,
  907. 'total_in' => self::$global->$key,
  908. 'now_date' => date('Y-m-d')
  909. ];
  910. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  911. if (2 == $flag) {
  912. $param = [
  913. 'is_talking' => $nowTalking,
  914. 'in_queue' => $inQueue,
  915. 'online_kf' => $onlineKf,
  916. 'success_in' => self::$global->$key2,
  917. 'total_in' => self::$global->$key,
  918. 'add_date' => date('Y-m-d'),
  919. 'add_hour' => date('H'),
  920. 'add_minute' => date('i'),
  921. ];
  922. self::$db->insert('ws_service_data')->cols($param)->query();
  923. }
  924. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  925. }
  926. /**
  927. * 机器人问答
  928. * @param $client_id 服务ID
  929. * @param $message 数据
  930. */
  931. private static function toRobot($client_id, $message)
  932. {
  933. $groups_id = $message['data']['groups_id'];
  934. $robot_name = $message['data']['robot_name'];
  935. $robotgroups_id = $message['data']['robotgroups_id'];
  936. // 查询问题.
  937. $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 . "'");
  938. $chat_message = [
  939. 'message_type' => 'chatMessage',
  940. 'data' => [
  941. 'name' => '智能助手',
  942. 'time' => date('H:i'),
  943. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  944. ]
  945. ];
  946. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  947. }
  948. /**
  949. * 评价
  950. * @param $client_id 服务ID
  951. * @param $message 数据
  952. */
  953. private static function evaluate($client_id, $message)
  954. {
  955. // 修改数据库.
  956. $evaluate_id = $message['data']['evaluate_id'];
  957. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  958. if ($result) {
  959. $chat_message = [
  960. 'message_type' => 'evaluate',
  961. 'data' => [
  962. 'status' => 1,
  963. 'time' => date('H:i'),
  964. ]
  965. ];
  966. } else {
  967. $chat_message = [
  968. 'message_type' => 'evaluate',
  969. 'data' => [
  970. 'status' => 2,
  971. 'time' => date('H:i'),
  972. ]
  973. ];
  974. }
  975. Gateway::sendToClient($client_id, json_encode($chat_message));
  976. }
  977. //踢掉同一用户的旧用户
  978. private static function tickOlduser($uid)
  979. {
  980. }
  981. }