WebSocketService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. namespace App\Services;
  3. @error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
  4. use App\Module\Base;
  5. use App\Module\Chat;
  6. use App\Module\Users;
  7. use App\Tasks\ChromeExtendTask;
  8. use App\Tasks\NotificationTask;
  9. use App\Tasks\PushTask;
  10. use Cache;
  11. use DB;
  12. use Hhxsv5\LaravelS\Swoole\Task\Task;
  13. use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
  14. use Swoole\Http\Request;
  15. use Swoole\WebSocket\Frame;
  16. use Swoole\WebSocket\Server;
  17. /**
  18. * @see https://wiki.swoole.com/#/start/start_ws_server
  19. */
  20. class WebSocketService implements WebSocketHandlerInterface
  21. {
  22. /**
  23. * 声明没有参数的构造函数
  24. * WebSocketService constructor.
  25. */
  26. public function __construct()
  27. {
  28. }
  29. /**
  30. * 连接建立时触发
  31. * @param Server $server
  32. * @param Request $request
  33. */
  34. public function onOpen(Server $server, Request $request)
  35. {
  36. global $_A;
  37. $_A = [
  38. '__static_langdata' => [],
  39. ];
  40. //判断参数
  41. $fd = $request->fd;
  42. if (!isset($request->get['token'])) {
  43. $server->push($fd, Chat::formatMsgSend([
  44. 'messageType' => 'error',
  45. 'body' => [
  46. 'error' => '参数错误'
  47. ],
  48. ]));
  49. $server->close($fd);
  50. $this->deleteUser($fd);
  51. return;
  52. }
  53. //判断token
  54. $token = $request->get['token'];
  55. $channel = $request->get['channel'] ?: '';
  56. $cacheKey = "ws::token:" . md5($token);
  57. $username = Cache::remember($cacheKey, now()->addSeconds(1), function () use ($token) {
  58. list($id, $username, $encrypt, $timestamp) = explode("@", base64_decode($token) . "@@@@");
  59. if (intval($id) > 0 && intval($timestamp) + 2592000 > time()) {
  60. if (DB::table('users')->where(['id' => $id, 'username' => $username, 'encrypt' => $encrypt])->exists()) {
  61. return $username;
  62. }
  63. }
  64. return null;
  65. });
  66. if (empty($username)) {
  67. Cache::forget($cacheKey);
  68. $server->push($fd, Chat::formatMsgSend([
  69. 'messageType' => 'error',
  70. 'channel' => $channel,
  71. 'body' => [
  72. 'error' => '会员不存在',
  73. ],
  74. ]));
  75. $server->close($fd);
  76. $this->deleteUser($fd);
  77. return;
  78. }
  79. //踢下线
  80. if (in_array($channel, ['ios', 'android'])) {
  81. $userLists = $this->getUser('', $channel, $username);
  82. foreach ($userLists AS $user) {
  83. $server->push($user['fd'], Chat::formatMsgSend([
  84. 'messageType' => 'kick',
  85. 'channel' => $channel,
  86. 'body' => [
  87. 'ip' => Base::getIp(),
  88. 'time' => time(),
  89. 'newfd' => $fd,
  90. ],
  91. ]));
  92. $this->deleteUser($user['fd']);
  93. }
  94. }
  95. //保存用户、发送open事件
  96. Cache::forever("ws::immediatelyNotify-" . $username, "no");
  97. $this->saveUser($fd, $channel, $username);
  98. $server->push($fd, Chat::formatMsgSend([
  99. 'messageType' => 'open',
  100. 'channel' => $channel,
  101. 'body' => [
  102. 'fd' => $fd,
  103. ],
  104. ]));
  105. //发送最后一条未发送的信息
  106. $lastMsg = Base::DBC2A(DB::table('chat_msg')->where('receive', $username)->orderByDesc('indate')->first());
  107. if ($lastMsg && $lastMsg['roger'] === 0) {
  108. $dialog = Chat::openDialog($lastMsg['username'], $lastMsg['receive']);
  109. if (!Base::isError($dialog)) {
  110. $dialog = $dialog['data'];
  111. $unread = intval(DB::table('chat_dialog')->where('id', $dialog['id'])->value(($dialog['recField'] == 1 ? 'unread1' : 'unread2')));
  112. $body = Base::string2array($lastMsg['message']);
  113. $body['id'] = $lastMsg['id'];
  114. $body['resend'] = 1;
  115. $body['unread'] = $unread;
  116. $body['username'] = $lastMsg['username'];
  117. $body['userimg'] = Users::userimg($lastMsg['username']);
  118. $body['indate'] = $lastMsg['indate'];
  119. //
  120. $basic = Users::username2basic($lastMsg['username']);
  121. $body['userid'] = $basic ? $basic['userid'] : 0;
  122. $body['nickname'] = $basic ? $basic['nickname'] : ($body['nickname'] || '');
  123. $body['userimg'] = $basic ? $basic['userimg'] : ($body['userimg'] || '');
  124. //
  125. $server->push($fd, Chat::formatMsgSend([
  126. 'messageType' => 'user',
  127. 'contentId' => $lastMsg['id'],
  128. 'channel' => $channel,
  129. 'username' => $lastMsg['username'],
  130. 'target' => $lastMsg['receive'],
  131. 'body' => $body,
  132. 'time' => $lastMsg['indate'],
  133. ]));
  134. }
  135. }
  136. }
  137. /**
  138. * 收到消息时触发
  139. * @param Server $server
  140. * @param Frame $frame
  141. */
  142. public function onMessage(Server $server, Frame $frame)
  143. {
  144. global $_A;
  145. $_A = [
  146. '__static_langdata' => [],
  147. ];
  148. //
  149. $data = Chat::formatMsgReceive($frame->data);
  150. $back = [
  151. 'status' => 1,
  152. 'message' => '',
  153. ];
  154. //
  155. switch ($data['messageType']) {
  156. /**
  157. * APP激活进入前台
  158. */
  159. case 'appActivity':
  160. Cache::forever("ws::immediatelyNotify-" . $data['username'], "no");
  161. break;
  162. /**
  163. * 刷新
  164. */
  165. case 'refresh':
  166. DB::table('ws')->where([
  167. 'fd' => $frame->fd,
  168. 'channel' => $data['channel'],
  169. ])->update(['update' => time()]);
  170. break;
  171. /**
  172. * 总未读消息数
  173. */
  174. case 'unread':
  175. $username = $this->getUsername($frame->fd, $data['channel']);
  176. if ($username) {
  177. $num = intval(DB::table('chat_dialog')->where('user1', $username)->sum('unread1'));
  178. $num+= intval(DB::table('chat_dialog')->where('user2', $username)->sum('unread2'));
  179. $back['message'] = $num;
  180. } else {
  181. $back['message'] = 0;
  182. }
  183. break;
  184. /**
  185. * 已读会员消息
  186. */
  187. case 'read':
  188. $username = $this->getUsername($frame->fd, $data['channel']);
  189. $dialog = Chat::openDialog($username, $data['target']);
  190. if (!Base::isError($dialog)) {
  191. $dialog = $dialog['data'];
  192. $upArray = [];
  193. if ($dialog['user1'] == $dialog['user2']) {
  194. $upArray['unread1'] = 0;
  195. $upArray['unread2'] = 0;
  196. } else {
  197. $upArray[($dialog['recField'] == 1 ? 'unread2' : 'unread1')] = 0;
  198. }
  199. DB::table('chat_dialog')->where('id', $dialog['id'])->update($upArray);
  200. }
  201. $chromeExtendTask = new ChromeExtendTask($username);
  202. Task::deliver($chromeExtendTask);
  203. break;
  204. /**
  205. * 收到信息回执
  206. */
  207. case 'roger':
  208. $contentIds = Base::explodeInt(',', $data['contentId']);
  209. if ($contentIds) {
  210. $username = $this->getUsername($frame->fd, $data['channel']);
  211. if ($username) {
  212. DB::table('chat_msg')->where('receive', $username)->whereIn('id', $contentIds)->update([
  213. 'roger' => 1,
  214. ]);
  215. }
  216. }
  217. break;
  218. /**
  219. * 发给用户
  220. */
  221. case 'user':
  222. $username = $this->getUsername($frame->fd, $data['channel']);
  223. $res = Chat::saveMessage($username, $data['target'], $data['body']);
  224. if (Base::isError($res)) {
  225. $back = [
  226. 'status' => 0,
  227. 'message' => $res['msg'],
  228. ];
  229. } else {
  230. $resData = $res['data'];
  231. $back['message'] = $resData['id'];
  232. $data['contentId'] = $resData['id'];
  233. $data['body']['id'] = $resData['id'];
  234. $data['body']['unread'] = $resData['unread'];
  235. //
  236. $basic = Users::username2basic($username);
  237. $data['body']['userid'] = $basic ? $basic['userid'] : 0;
  238. $data['body']['nickname'] = $basic ? $basic['nickname'] : ($data['body']['nickname'] || '');
  239. $data['body']['userimg'] = $basic ? $basic['userimg'] : ($data['body']['userimg'] || '');
  240. //
  241. $pushLists = [];
  242. foreach ($this->getUserOfName($data['target']) AS $item) {
  243. $pushLists[] = [
  244. 'fd' => $item['fd'],
  245. 'msg' => $data
  246. ];
  247. }
  248. $pushTask = new PushTask($pushLists);
  249. Task::deliver($pushTask);
  250. //
  251. $notificationTask = new NotificationTask($resData['id']);
  252. $notificationTask->delay(Cache::get("ws::immediatelyNotify-" . $data['target']) == "yes" ? 2 : 10);
  253. Task::deliver($notificationTask);
  254. }
  255. break;
  256. /**
  257. * 发给用户(不保存记录)
  258. */
  259. case 'info':
  260. $pushLists = [];
  261. foreach ($this->getUserOfName($data['target']) AS $item) {
  262. $pushLists[] = [
  263. 'fd' => $item['fd'],
  264. 'msg' => $data
  265. ];
  266. }
  267. $pushTask = new PushTask($pushLists);
  268. Task::deliver($pushTask);
  269. break;
  270. /**
  271. * 发给整个团队
  272. */
  273. case 'team':
  274. if ($data['body']['type'] === 'taskA') {
  275. $taskId = intval(Base::val($data['body'], 'taskDetail.id'));
  276. if ($taskId > 0) {
  277. $userLists = Chat::getTaskUsers($taskId);
  278. } else {
  279. $userLists = $this->getTeamUsers();
  280. }
  281. //
  282. $pushLists = [];
  283. foreach ($userLists as $user) {
  284. $data['messageType'] = 'user';
  285. $data['target'] = $user['username'];
  286. $pushLists[] = [
  287. 'fd' => $user['fd'],
  288. 'msg' => $data
  289. ];
  290. }
  291. $pushTask = new PushTask($pushLists);
  292. Task::deliver($pushTask);
  293. }
  294. break;
  295. /**
  296. * 知识库协作
  297. */
  298. case 'docs':
  299. $back['message'] = [];
  300. $body = $data['body'];
  301. $type = $body['type'];
  302. $sid = intval($body['sid']);
  303. if ($sid <= 0) {
  304. return;
  305. }
  306. $array = Base::json2array(Cache::get("docs::" . $sid));
  307. if ($array) {
  308. foreach ($array as $uname => $vbody) {
  309. if (intval($vbody['indate']) + 20 < time()) {
  310. unset($array[$uname]);
  311. }
  312. }
  313. }
  314. if ($type == 'enter' || $type == 'refresh') {
  315. $array[$body['username']] = $body;
  316. } elseif ($type == 'quit') {
  317. unset($array[$body['username']]);
  318. }
  319. //
  320. Cache::put("docs::" . $sid, Base::array2json($array), 30);
  321. if ($array) {
  322. ksort($array);
  323. }
  324. $back['message'] = array_values($array);
  325. //
  326. if ($type == 'enter' || $type == 'quit') {
  327. $pushLists = [];
  328. foreach ($back['message'] AS $tuser) {
  329. foreach ($this->getUserOfName($tuser['username']) AS $item) {
  330. $pushLists[] = [
  331. 'fd' => $item['fd'],
  332. 'msg' => [
  333. 'messageType' => 'docs',
  334. 'body' => [
  335. 'type' => 'users',
  336. 'sid' => $sid,
  337. 'lists' => $back['message']
  338. ]
  339. ]
  340. ];
  341. }
  342. }
  343. $pushTask = new PushTask($pushLists);
  344. Task::deliver($pushTask);
  345. }
  346. break;
  347. }
  348. if ($data['messageId']) {
  349. $pushLists = [];
  350. $pushLists[] = [
  351. 'fd' => $frame->fd,
  352. 'msg' => [
  353. 'messageType' => 'back',
  354. 'messageId' => $data['messageId'],
  355. 'body' => $back,
  356. ]
  357. ];
  358. $pushTask = new PushTask($pushLists);
  359. Task::deliver($pushTask);
  360. }
  361. }
  362. /**
  363. * 关闭连接时触发
  364. * @param Server $server
  365. * @param $fd
  366. * @param $reactorId
  367. */
  368. public function onClose(Server $server, $fd, $reactorId)
  369. {
  370. $this->deleteUser($fd);
  371. }
  372. /** ****************************************************************************** */
  373. /** ****************************************************************************** */
  374. /** ****************************************************************************** */
  375. /**
  376. * 保存用户
  377. * @param $fd
  378. * @param $channel
  379. * @param $username
  380. */
  381. private function saveUser($fd, $channel, $username)
  382. {
  383. try {
  384. DB::transaction(function () use ($username, $channel, $fd) {
  385. $this->deleteUser($fd);
  386. DB::table('ws')->updateOrInsert([
  387. 'key' => md5($fd . '@' . $channel . '@' . $username)
  388. ], [
  389. 'fd' => $fd,
  390. 'username' => $username,
  391. 'channel' => $channel,
  392. 'update' => time()
  393. ]);
  394. });
  395. } catch (\Throwable $e) {
  396. }
  397. }
  398. /**
  399. * 清除用户
  400. * @param $fd
  401. */
  402. private function deleteUser($fd)
  403. {
  404. DB::table('ws')->where('fd', $fd)->delete();
  405. }
  406. /**
  407. * 获取用户
  408. * @param string $fd
  409. * @param string $channel
  410. * @param string $username
  411. * @return array
  412. */
  413. private function getUser($fd = '', $channel = '', $username = '')
  414. {
  415. $array = [];
  416. if ($fd) $array['fd'] = $fd;
  417. if ($channel) $array['channel'] = $channel;
  418. if ($username) $array['username'] = $username;
  419. if (empty($array)) {
  420. return [];
  421. }
  422. return Base::DBC2A(DB::table('ws')->select(['fd', 'username', 'channel'])->where($array)->get());
  423. }
  424. private function getUserOfFd($fd, $channel = '') {
  425. return $this->getUser($fd, $channel);
  426. }
  427. private function getUserOfName($username, $channel = '') {
  428. return $this->getUser('', $channel, $username);
  429. }
  430. private function getUsername($fd, $channel) {
  431. return DB::table('ws')->where(['fd' => $fd, 'channel' => $channel ])->value('username');
  432. }
  433. /**
  434. * 获取团队所有在线用户
  435. * @return array|string
  436. */
  437. private function getTeamUsers()
  438. {
  439. return Base::DBC2A(DB::table('ws')->select(['fd', 'username', 'channel'])->where([
  440. ['update', '>', time() - 600],
  441. ])->get());
  442. }
  443. }