WebSocketService.php 15 KB

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