WebSocketService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <?php
  2. namespace App\Services;
  3. @error_reporting(E_ALL & ~E_NOTICE);
  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. $server->push($fd, Chat::formatMsgSend([
  120. 'messageType' => 'user',
  121. 'contentId' => $lastMsg['id'],
  122. 'channel' => $channel,
  123. 'username' => $lastMsg['username'],
  124. 'target' => $lastMsg['receive'],
  125. 'body' => $body,
  126. 'time' => $lastMsg['indate'],
  127. ]));
  128. }
  129. }
  130. }
  131. /**
  132. * 收到消息时触发
  133. * @param Server $server
  134. * @param Frame $frame
  135. */
  136. public function onMessage(Server $server, Frame $frame)
  137. {
  138. global $_A;
  139. $_A = [
  140. '__static_langdata' => [],
  141. ];
  142. //
  143. $data = Chat::formatMsgReceive($frame->data);
  144. $back = [
  145. 'status' => 1,
  146. 'message' => '',
  147. ];
  148. //
  149. switch ($data['messageType']) {
  150. /**
  151. * APP激活进入前台
  152. */
  153. case 'appActivity':
  154. Cache::forever("ws::immediatelyNotify-" . $data['username'], "no");
  155. break;
  156. /**
  157. * 刷新
  158. */
  159. case 'refresh':
  160. DB::table('ws')->where([
  161. 'fd' => $frame->fd,
  162. 'channel' => $data['channel'],
  163. ])->update(['update' => time()]);
  164. break;
  165. /**
  166. * 总未读消息数
  167. */
  168. case 'unread':
  169. $username = DB::table('ws')->where([
  170. 'fd' => $frame->fd,
  171. 'channel' => $data['channel'],
  172. ])->value('username');
  173. if ($username) {
  174. $num = intval(DB::table('chat_dialog')->where('user1', $username)->sum('unread1'));
  175. $num+= intval(DB::table('chat_dialog')->where('user2', $username)->sum('unread2'));
  176. $back['message'] = $num;
  177. } else {
  178. $back['message'] = 0;
  179. }
  180. break;
  181. /**
  182. * 已读会员消息
  183. */
  184. case 'read':
  185. $username = DB::table('ws')->where([
  186. 'fd' => $frame->fd,
  187. 'channel' => $data['channel'],
  188. ])->value('username');
  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 = DB::table('ws')->where([
  211. 'fd' => $frame->fd,
  212. 'channel' => $data['channel'],
  213. ])->value('username');
  214. if ($username) {
  215. DB::table('chat_msg')->where('receive', $username)->whereIn('id', $contentIds)->update([
  216. 'roger' => 1,
  217. ]);
  218. }
  219. }
  220. break;
  221. /**
  222. * 发给用户
  223. */
  224. case 'user':
  225. $username = DB::table('ws')->where([
  226. 'fd' => $frame->fd,
  227. 'channel' => $data['channel'],
  228. ])->value('username');
  229. $res = Chat::saveMessage($username, $data['target'], $data['body']);
  230. if (Base::isError($res)) {
  231. $back = [
  232. 'status' => 0,
  233. 'message' => $res['msg'],
  234. ];
  235. } else {
  236. $resData = $res['data'];
  237. $back['message'] = $resData['id'];
  238. $data['contentId'] = $resData['id'];
  239. $data['body']['id'] = $resData['id'];
  240. $data['body']['unread'] = $resData['unread'];
  241. //
  242. $basic = Users::username2basic($username);
  243. $data['body']['nickname'] = $basic ? $basic['nickname'] : ($data['body']['nickname'] || '');
  244. $data['body']['userimg'] = $basic ? $basic['userimg'] : ($data['body']['userimg'] || '');
  245. //
  246. $pushLists = [];
  247. foreach ($this->getUserOfName($data['target']) AS $item) {
  248. $pushLists[] = [
  249. 'fd' => $item['fd'],
  250. 'msg' => $data
  251. ];
  252. }
  253. $pushTask = new PushTask($pushLists);
  254. Task::deliver($pushTask);
  255. //
  256. $notificationTask = new NotificationTask($resData['id']);
  257. $notificationTask->delay(Cache::get("ws::immediatelyNotify-" . $data['target']) == "yes" ? 2 : 10);
  258. Task::deliver($notificationTask);
  259. }
  260. break;
  261. /**
  262. * 发给用户(不保存记录)
  263. */
  264. case 'info':
  265. $pushLists = [];
  266. foreach ($this->getUserOfName($data['target']) AS $item) {
  267. $pushLists[] = [
  268. 'fd' => $item['fd'],
  269. 'msg' => $data
  270. ];
  271. }
  272. $pushTask = new PushTask($pushLists);
  273. Task::deliver($pushTask);
  274. break;
  275. /**
  276. * 发给整个团队
  277. */
  278. case 'team':
  279. if ($data['body']['type'] === 'taskA') {
  280. $taskId = intval(Base::val($data['body'], 'taskDetail.id'));
  281. if ($taskId > 0) {
  282. $userLists = Chat::getTaskUsers($taskId);
  283. } else {
  284. $userLists = $this->getTeamUsers();
  285. }
  286. //
  287. $pushLists = [];
  288. foreach ($userLists as $user) {
  289. $data['messageType'] = 'user';
  290. $data['target'] = $user['username'];
  291. $pushLists[] = [
  292. 'fd' => $user['fd'],
  293. 'msg' => $data
  294. ];
  295. }
  296. $pushTask = new PushTask($pushLists);
  297. Task::deliver($pushTask);
  298. }
  299. break;
  300. /**
  301. * 知识库协作
  302. */
  303. case 'docs':
  304. $back['message'] = [];
  305. $body = $data['body'];
  306. $type = $body['type'];
  307. $sid = intval($body['sid']);
  308. if ($sid <= 0) {
  309. return;
  310. }
  311. $array = Base::json2array(Cache::get("docs::" . $sid));
  312. if ($array) {
  313. foreach ($array as $uname => $vbody) {
  314. if (intval($vbody['indate']) + 20 < time()) {
  315. unset($array[$uname]);
  316. }
  317. }
  318. }
  319. if ($type == 'enter' || $type == 'refresh') {
  320. $array[$body['username']] = $body;
  321. } elseif ($type == 'quit') {
  322. unset($array[$body['username']]);
  323. }
  324. //
  325. Cache::put("docs::" . $sid, Base::array2json($array), 30);
  326. if ($array) {
  327. ksort($array);
  328. }
  329. $back['message'] = array_values($array);
  330. //
  331. if ($type == 'enter' || $type == 'quit') {
  332. $pushLists = [];
  333. foreach ($back['message'] AS $tuser) {
  334. foreach ($this->getUserOfName($tuser['username']) AS $item) {
  335. $pushLists[] = [
  336. 'fd' => $item['fd'],
  337. 'msg' => [
  338. 'messageType' => 'docs',
  339. 'body' => [
  340. 'type' => 'users',
  341. 'sid' => $sid,
  342. 'lists' => $back['message']
  343. ]
  344. ]
  345. ];
  346. }
  347. }
  348. $pushTask = new PushTask($pushLists);
  349. Task::deliver($pushTask);
  350. }
  351. break;
  352. }
  353. if ($data['messageId']) {
  354. $pushLists = [];
  355. $pushLists[] = [
  356. 'fd' => $frame->fd,
  357. 'msg' => [
  358. 'messageType' => 'back',
  359. 'messageId' => $data['messageId'],
  360. 'body' => $back,
  361. ]
  362. ];
  363. $pushTask = new PushTask($pushLists);
  364. Task::deliver($pushTask);
  365. }
  366. }
  367. /**
  368. * 关闭连接时触发
  369. * @param Server $server
  370. * @param $fd
  371. * @param $reactorId
  372. */
  373. public function onClose(Server $server, $fd, $reactorId)
  374. {
  375. $this->deleteUser($fd);
  376. }
  377. /** ****************************************************************************** */
  378. /** ****************************************************************************** */
  379. /** ****************************************************************************** */
  380. /**
  381. * 保存用户
  382. * @param $fd
  383. * @param $channel
  384. * @param $username
  385. */
  386. private function saveUser($fd, $channel, $username)
  387. {
  388. try {
  389. DB::transaction(function () use ($username, $channel, $fd) {
  390. $this->deleteUser($fd);
  391. DB::table('ws')->updateOrInsert([
  392. 'key' => md5($fd . '@' . $channel . '@' . $username)
  393. ], [
  394. 'fd' => $fd,
  395. 'username' => $username,
  396. 'channel' => $channel,
  397. 'update' => time()
  398. ]);
  399. });
  400. } catch (\Throwable $e) {
  401. }
  402. }
  403. /**
  404. * 清除用户
  405. * @param $fd
  406. */
  407. private function deleteUser($fd)
  408. {
  409. DB::table('ws')->where('fd', $fd)->delete();
  410. }
  411. /**
  412. * 获取用户
  413. * @param string $fd
  414. * @param string $channel
  415. * @param string $username
  416. * @return array
  417. */
  418. private function getUser($fd = '', $channel = '', $username = '')
  419. {
  420. $array = [];
  421. if ($fd) $array['fd'] = $fd;
  422. if ($channel) $array['channel'] = $channel;
  423. if ($username) $array['username'] = $username;
  424. if (empty($array)) {
  425. return [];
  426. }
  427. return Base::DBC2A(DB::table('ws')->select(['fd', 'username', 'channel'])->where($array)->get());
  428. }
  429. private function getUserOfFd($fd, $channel = '') {
  430. return $this->getUser($fd, $channel);
  431. }
  432. private function getUserOfName($username, $channel = '') {
  433. return $this->getUser('', $channel, $username);
  434. }
  435. /**
  436. * 获取团队所有在线用户
  437. * @return array|string
  438. */
  439. private function getTeamUsers()
  440. {
  441. return Base::DBC2A(DB::table('ws')->select(['fd', 'username', 'channel'])->where([
  442. ['update', '>', time() - 600],
  443. ])->get());
  444. }
  445. }