Events.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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. // default:
  337. // Gateway::closeClient($client_id);
  338. }
  339. }
  340. /**
  341. * 当用户断开连接时触发
  342. * @param int $client_id 连接id
  343. *
  344. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  345. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  346. */
  347. public static function onClose($client_id)
  348. {
  349. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  350. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  351. if (empty($uid)) {
  352. return;
  353. }
  354. if ($isKefuoff) {
  355. self::serviceOffline($client_id, $uid);
  356. } else {
  357. self::guestOffline($client_id, $uid);
  358. }
  359. return;
  360. }
  361. //客服下线了
  362. public static function serviceOffline($client_id, $uid)
  363. {
  364. $group = $_SESSION['group'];
  365. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  366. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  367. $simpliUsers = self::$global->uidSimpleList;
  368. $simpliUsersID_UID_Arr = [];
  369. if (!empty($simpliUsers)) {
  370. foreach ($simpliUsers as $key => $val) {
  371. $simpliUsersID_UID_Arr[$val['0']] = $key;
  372. }
  373. }
  374. $now = time();
  375. if (!empty($user_info)) {
  376. foreach ($user_info as $val) {
  377. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  378. if (isset($simpliUsersID_UID_Arr[$val])) {
  379. 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 ");
  380. }
  381. Gateway::closeClient($val);
  382. }
  383. }
  384. unset($kefuinfo_old_new[$group][$uid]);
  385. do {
  386. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  387. return;
  388. }
  389. //用户下线了
  390. public static function guestOffline($client_id, $uid)
  391. {
  392. $kfuid = -1;
  393. $krclient_id = 0;
  394. $kfgroup = -1;
  395. $userToKf = $userToKfNew = self::$global->userToKf;
  396. if (isset($userToKfNew[$uid])) {
  397. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  398. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  399. unset($userToKfNew[$uid]);
  400. do {
  401. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  402. }
  403. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  404. if (isset($uidSimpleListNew[$uid])) {
  405. $kfgroup = $uidSimpleListNew[$uid]['1'];
  406. unset($uidSimpleListNew[$uid]);
  407. do {
  408. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  409. }
  410. $userList = $userListNew = self::$global->userList;
  411. if (!empty($userList)) {
  412. $ischange = 0;
  413. foreach ($userList as $key => $val) {
  414. if ($val['id'] == $uid) {
  415. unset($userListNew[$key]);
  416. $ischange = 1;
  417. break;
  418. }
  419. }
  420. if ($ischange) {
  421. do {
  422. } while (!self::$global->cas('userList', $userList, $userListNew));
  423. }
  424. }
  425. if ($kfuid != -1 && $kfgroup != -1) {
  426. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  427. $ischange_kf_list = 0;
  428. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  429. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  430. if ($infos) {
  431. if (is_array($infos)) {
  432. foreach ($infos as $key => $val) {
  433. if ($val == $client_id) {
  434. $ischange_kf_list = 1;
  435. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  436. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  437. }
  438. }
  439. }
  440. if ($ischange_kf_list) {
  441. do {
  442. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  443. $chat_message = [
  444. 'message_type' => 'userClose',
  445. 'data' => [
  446. 'content' => '用户连接已断开',
  447. 'time' => date('H:i'),
  448. ]
  449. ];
  450. self::$db->query("update `ws_service_log` set `status` = '3' where `user_id`= '$uid' and kf_id='$kfuid' and group_id=$kfgroup and status=1 ");
  451. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  452. }
  453. }
  454. }
  455. }
  456. }
  457. /**
  458. * 客服结束会话
  459. * @param int $client_id 连接id
  460. *
  461. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  462. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  463. */
  464. public static function serverClose($client_id)
  465. {
  466. // 返回.
  467. $chat_message = [
  468. 'message_type' => 'closeBysever',
  469. 'data' => [
  470. 'content' => '客服停止了该会话',
  471. 'time' => date('H:i'),
  472. ]
  473. ];
  474. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  475. $isServiceUserOut = false;
  476. // 将会员服务信息,从客服的服务列表中移除
  477. $old = $kfList = self::$global->kfList;
  478. foreach ($kfList as $k => $v) {
  479. foreach ($v as $key => $vo) {
  480. if (in_array($client_id, $vo['user_info'])) {
  481. $isServiceUserOut = true;
  482. // 根据client id 去更新会话工单一些信息
  483. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  484. // 从会员的内存表中检索出该会员的信息,并更新内存
  485. $oldSimple = $simpleList = self::$global->uidSimpleList;
  486. $outUser = [];
  487. foreach ($simpleList as $u => $c) {
  488. if ($c['0'] == $client_id) {
  489. $outUser[] = [
  490. 'user_id' => $u,
  491. 'group_id' => $c['1']
  492. ];
  493. unset($simpleList[$u]);
  494. break;
  495. }
  496. }
  497. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  498. };
  499. unset($oldSimple, $simpleList);
  500. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  501. // 通知 客服删除退出的用户
  502. if (!empty($outUser)) {
  503. $del_message = [
  504. 'message_type' => 'delUser',
  505. 'data' => [
  506. 'id' => $outUser['0']['user_id']
  507. ]
  508. ];
  509. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  510. unset($del_message);
  511. // 尝试分配新会员进入服务
  512. self::userOfflineTask($outUser['0']['group_id']);
  513. }
  514. unset($outUser);
  515. // 维护现在的该客服的服务信息
  516. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  517. foreach ($vo['user_info'] as $m => $l) {
  518. if ($client_id == $l) {
  519. unset($kfList[$k][$key]['user_info'][$m]);
  520. break;
  521. }
  522. }
  523. // 刷新内存中客服的服务列表
  524. while (!self::$global->cas('kfList', $old, $kfList)) {
  525. };
  526. unset($old, $kfList);
  527. break;
  528. }
  529. }
  530. if ($isServiceUserOut) break;
  531. }
  532. // 尝试从排队的用户中删除退出的客户端
  533. if (false == $isServiceUserOut) {
  534. $old = $userList = self::$global->userList;
  535. foreach (self::$global->userList as $key => $vo) {
  536. if ($client_id == $vo['client_id']) {
  537. $isServiceUserOut = true;
  538. unset($userList[$key]);
  539. break;
  540. }
  541. }
  542. while (!self::$global->cas('userList', $old, $userList)) {
  543. };
  544. // 从会员的内存表中检索出该会员的信息,并更新内存
  545. $oldSimple = $simpleList = self::$global->uidSimpleList;
  546. foreach ($simpleList as $u => $c) {
  547. if ($c['0'] == $client_id) {
  548. unset($simpleList[$u]);
  549. break;
  550. }
  551. }
  552. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  553. };
  554. unset($oldSimple, $simpleList);
  555. }
  556. // 尝试是否是客服退出
  557. if (false == $isServiceUserOut) {
  558. $old = $kfList = self::$global->kfList;
  559. foreach (self::$global->kfList as $k => $v) {
  560. foreach ($v as $key => $vo) {
  561. // 客服服务列表中无数据,才去删除客服内存信息
  562. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  563. unset($kfList[$k][$key]);
  564. break;
  565. }
  566. }
  567. }
  568. while (!self::$global->cas('kfList', $old, $kfList)) {
  569. };
  570. }
  571. }
  572. /**
  573. * 有人退出
  574. * @param $group
  575. */
  576. private static function userOfflineTask($group)
  577. {
  578. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  579. $maxNumber = self::getMaxServiceNum();
  580. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  581. unset($maxNumber);
  582. if (1 == $res['code']) {
  583. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  584. }; // 更新客服数据
  585. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  586. }; // 更新会员数据
  587. // 通知会员发送信息绑定客服的id
  588. $noticeUser = [
  589. 'message_type' => 'connect',
  590. 'data' => [
  591. 'kf_id' => $res['data']['0'],
  592. 'kf_name' => $res['data']['1']
  593. ]
  594. ];
  595. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  596. unset($noticeUser);
  597. // 通知客服端绑定会员的信息
  598. $noticeKf = [
  599. 'message_type' => 'connect',
  600. 'data' => [
  601. 'user_info' => $res['data']['3']
  602. ]
  603. ];
  604. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  605. unset($noticeKf);
  606. // 逐一通知
  607. $number = 1;
  608. foreach (self::$global->userList as $vo) {
  609. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  610. $waitMessage = [
  611. 'message_type' => 'wait',
  612. 'data' => [
  613. 'content' => $waitMsg,
  614. ]
  615. ];
  616. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  617. $number++;
  618. }
  619. unset($waitMessage, $number);
  620. // 写入接入值
  621. $key = date('Ymd') . 'success_in';
  622. self::$global->$key = 0;
  623. do {
  624. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  625. unset(self::$global->$oldKey);
  626. } while (!self::$global->increment($key));
  627. unset($key);
  628. } else {
  629. switch ($res['code']) {
  630. case -1:
  631. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  632. // 逐一通知
  633. foreach (self::$global->userList as $vo) {
  634. $waitMessage = [
  635. 'message_type' => 'wait',
  636. 'data' => [
  637. 'content' => $waitMsg,
  638. ]
  639. ];
  640. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  641. }
  642. break;
  643. case -2:
  644. break;
  645. case -3:
  646. break;
  647. case -4:
  648. // 逐一通知
  649. $number = 1;
  650. foreach (self::$global->userList as $vo) {
  651. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  652. $waitMessage = [
  653. 'message_type' => 'wait',
  654. 'data' => [
  655. 'content' => $waitMsg,
  656. ]
  657. ];
  658. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  659. $number++;
  660. }
  661. break;
  662. }
  663. unset($waitMessage, $number);
  664. }
  665. }
  666. /**
  667. * 有人进入执行分配
  668. * @param $client_id
  669. * @param $group
  670. */
  671. private static function userOnlineTask($client_id, $group)
  672. {
  673. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  674. $maxNumber = self::getMaxServiceNum();
  675. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  676. unset($maxNumber);
  677. if (1 == $res['code']) {
  678. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  679. }; // 更新客服数据
  680. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  681. }; // 更新会员数据
  682. $userToKf = self::$global->userToKf;
  683. $userToKf[$res['data']['3']['id']] = [
  684. $res['data']['3']['id'],
  685. $res['data']['0']
  686. ];
  687. self::$global->userToKf = $userToKf;
  688. // 服务信息入库
  689. $serviceLog = [
  690. 'user_id' => $res['data']['3']['id'],
  691. 'client_id' => $res['data']['3']['client_id'],
  692. 'user_name' => $res['data']['3']['name'],
  693. 'user_ip' => $res['data']['3']['ip'],
  694. 'user_avatar' => $res['data']['3']['avatar'],
  695. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  696. 'start_time' => time(),
  697. 'group_id' => $group,
  698. 'website' => $res['data']['3']['website'],
  699. 'system' => $res['data']['3']['system'],
  700. 'browse' => $res['data']['3']['browse'],
  701. 'status' => 1,
  702. 'end_time' => 0
  703. ];
  704. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  705. unset($serviceLog);
  706. // 通知会员发送信息绑定客服的id
  707. $noticeUser = [
  708. 'message_type' => 'connect',
  709. 'data' => [
  710. 'kf_id' => $res['data']['0'],
  711. 'conversationId' => $conversationId,
  712. 'kf_name' => $res['data']['1']
  713. ]
  714. ];
  715. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  716. unset($noticeUser);
  717. // 通知客服端绑定会员的信息
  718. $noticeKf = [
  719. 'message_type' => 'connect',
  720. 'data' => [
  721. 'user_info' => $res['data']['3'],
  722. 'conversationId' => $conversationId,
  723. ]
  724. ];
  725. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  726. unset($noticeKf);
  727. // 写入接入值
  728. $key = date('Ymd') . 'success_in';
  729. self::$global->$key = 0;
  730. do {
  731. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  732. unset(self::$global->$oldKey);
  733. } while (!self::$global->increment($key));
  734. unset($key);
  735. } else {
  736. $waitMsg = '';
  737. switch ($res['code']) {
  738. case -1:
  739. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  740. break;
  741. case -2:
  742. break;
  743. case -3:
  744. break;
  745. case -4:
  746. $number = count(self::$global->userList);
  747. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  748. break;
  749. }
  750. $waitMessage = [
  751. 'message_type' => 'wait',
  752. 'data' => [
  753. 'content' => $waitMsg,
  754. ]
  755. ];
  756. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  757. unset($waitMessage);
  758. }
  759. }
  760. /**
  761. * 给客服分配会员【均分策略】
  762. * @param $kfList
  763. * @param $userList
  764. * @param $group
  765. * @param $total
  766. */
  767. private static function assignmentTask($kfList, $userList, $group, $total)
  768. {
  769. // 没有客服上线
  770. if (empty($kfList) || empty($kfList[$group])) {
  771. return ['code' => -1];
  772. }
  773. // 没有待分配的会员
  774. if (empty($userList)) {
  775. return ['code' => -2];
  776. }
  777. // 未设置每个客服可以服务多少人
  778. if (0 == $total) {
  779. return ['code' => -3];
  780. }
  781. // 查看该组的客服是否在线
  782. if (!isset($kfList[$group])) {
  783. return ['code' => -1];
  784. }
  785. $kf = $kfList[$group];
  786. $user = array_shift($userList);
  787. $kf = array_shift($kf);
  788. $min = $kf['task'];
  789. $flag = $kf['id'];
  790. foreach ($kfList[$group] as $key => $vo) {
  791. if ($vo['task'] < $min) {
  792. $min = $vo['task'];
  793. $flag = $key;
  794. }
  795. }
  796. unset($kf);
  797. // 需要排队了
  798. if ($kfList[$group][$flag]['task'] == $total) {
  799. return ['code' => -4];
  800. }
  801. $kfList[$group][$flag]['task'] += 1;
  802. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  803. return [
  804. 'code' => 1,
  805. 'data' => [
  806. $kfList[$group][$flag]['id'],
  807. $kfList[$group][$flag]['name'],
  808. $kfList[$group][$flag]['client_id'],
  809. $user,
  810. $kfList,
  811. $userList
  812. ]
  813. ];
  814. }
  815. /**
  816. * 获取最大的服务人数
  817. * @return int
  818. */
  819. private static function getMaxServiceNum()
  820. {
  821. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  822. if (!empty($maxNumber)) {
  823. $maxNumber = 5;
  824. } else {
  825. $maxNumber = $maxNumber['0']['max_service'];
  826. }
  827. return $maxNumber;
  828. }
  829. /**
  830. * 将内存中的数据写入统计表
  831. * @param int $flag
  832. */
  833. private static function writeLog($flag = 1)
  834. {
  835. // 上午 8点 到 22 点开始统计
  836. if (date('H') < 8 || date('H') > 22) {
  837. return;
  838. }
  839. // 当前正在接入的人 和 在线客服数
  840. $kfList = self::$global->kfList;
  841. $nowTalking = 0;
  842. $onlineKf = 0;
  843. if (!empty($kfList)) {
  844. foreach ($kfList as $key => $vo) {
  845. $onlineKf += count($vo);
  846. foreach ($vo as $k => $v) {
  847. $nowTalking += count($v['user_info']);
  848. }
  849. }
  850. }
  851. // 在队列中的用户
  852. $inQueue = count(self::$global->userList);
  853. $key = date('Ymd') . 'total_in';
  854. $key2 = date('Ymd') . 'success_in';
  855. $param = [
  856. 'is_talking' => $nowTalking,
  857. 'in_queue' => $inQueue,
  858. 'online_kf' => $onlineKf,
  859. 'success_in' => self::$global->$key2,
  860. 'total_in' => self::$global->$key,
  861. 'now_date' => date('Y-m-d')
  862. ];
  863. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  864. if (2 == $flag) {
  865. $param = [
  866. 'is_talking' => $nowTalking,
  867. 'in_queue' => $inQueue,
  868. 'online_kf' => $onlineKf,
  869. 'success_in' => self::$global->$key2,
  870. 'total_in' => self::$global->$key,
  871. 'add_date' => date('Y-m-d'),
  872. 'add_hour' => date('H'),
  873. 'add_minute' => date('i'),
  874. ];
  875. self::$db->insert('ws_service_data')->cols($param)->query();
  876. }
  877. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  878. }
  879. /**
  880. * 机器人问答
  881. * @param $client_id 服务ID
  882. * @param $message 数据
  883. */
  884. private static function toRobot($client_id, $message)
  885. {
  886. $groups_id = $message['data']['groups_id'];
  887. $robot_name = $message['data']['robot_name'];
  888. $robotgroups_id = $message['data']['robotgroups_id'];
  889. // 查询问题.
  890. $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 . "'");
  891. $chat_message = [
  892. 'message_type' => 'chatMessage',
  893. 'data' => [
  894. 'name' => '智能助手',
  895. 'time' => date('H:i'),
  896. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  897. ]
  898. ];
  899. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  900. }
  901. /**
  902. * 评价
  903. * @param $client_id 服务ID
  904. * @param $message 数据
  905. */
  906. private static function evaluate($client_id, $message)
  907. {
  908. // 修改数据库.
  909. $evaluate_id = $message['data']['evaluate_id'];
  910. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  911. if ($result) {
  912. $chat_message = [
  913. 'message_type' => 'evaluate',
  914. 'data' => [
  915. 'status' => 1,
  916. 'time' => date('H:i'),
  917. ]
  918. ];
  919. } else {
  920. $chat_message = [
  921. 'message_type' => 'evaluate',
  922. 'data' => [
  923. 'status' => 2,
  924. 'time' => date('H:i'),
  925. ]
  926. ];
  927. }
  928. Gateway::sendToClient($client_id, json_encode($chat_message));
  929. }
  930. //踢掉同一用户的旧用户
  931. private static function tickOlduser($uid)
  932. {
  933. }
  934. }