WebSocketService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. $pushLists = [];
  236. foreach ($this->getUserOfName($data['target']) AS $item) {
  237. $pushLists[] = [
  238. 'fd' => $item['fd'],
  239. 'msg' => $data
  240. ];
  241. }
  242. $pushTask = new PushTask($pushLists);
  243. Task::deliver($pushTask);
  244. }
  245. break;
  246. /**
  247. * 发给用户(不保存记录)
  248. */
  249. case 'info':
  250. $pushLists = [];
  251. foreach ($this->getUserOfName($data['target']) AS $item) {
  252. $pushLists[] = [
  253. 'fd' => $item['fd'],
  254. 'msg' => $data
  255. ];
  256. }
  257. $pushTask = new PushTask($pushLists);
  258. Task::deliver($pushTask);
  259. break;
  260. /**
  261. * 发给整个团队
  262. */
  263. case 'team':
  264. if ($data['body']['type'] === 'taskA') {
  265. $taskId = intval(Base::val($data['body'], 'taskDetail.id'));
  266. if ($taskId > 0) {
  267. $userLists = Chat::getTaskUsers($taskId);
  268. } else {
  269. $userLists = $this->getTeamUsers();
  270. }
  271. //
  272. $pushLists = [];
  273. foreach ($userLists as $user) {
  274. $data['messageType'] = 'user';
  275. $data['target'] = $user['username'];
  276. $pushLists[] = [
  277. 'fd' => $user['fd'],
  278. 'msg' => $data
  279. ];
  280. }
  281. $pushTask = new PushTask($pushLists);
  282. Task::deliver($pushTask);
  283. }
  284. break;
  285. /**
  286. * 知识库协作
  287. */
  288. case 'docs':
  289. $back['message'] = [];
  290. $body = $data['body'];
  291. $type = $body['type'];
  292. $sid = intval($body['sid']);
  293. if ($sid <= 0) {
  294. return;
  295. }
  296. $array = Base::json2array(Cache::get("docs::" . $sid));
  297. if ($array) {
  298. foreach ($array as $uname => $vbody) {
  299. if (intval($vbody['indate']) + 20 < time()) {
  300. unset($array[$uname]);
  301. }
  302. }
  303. }
  304. if ($type == 'enter' || $type == 'refresh') {
  305. $array[$body['username']] = $body;
  306. } elseif ($type == 'quit') {
  307. unset($array[$body['username']]);
  308. }
  309. //
  310. Cache::put("docs::" . $sid, Base::array2json($array), 30);
  311. ksort($array);
  312. $back['message'] = array_values($array);
  313. //
  314. if ($type == 'enter' || $type == 'quit') {
  315. $pushLists = [];
  316. foreach ($back['message'] AS $tuser) {
  317. foreach ($this->getUserOfName($tuser['username']) AS $item) {
  318. $pushLists[] = [
  319. 'fd' => $item['fd'],
  320. 'msg' => [
  321. 'messageType' => 'docs',
  322. 'body' => [
  323. 'type' => 'users',
  324. 'sid' => $sid,
  325. 'lists' => $back['message']
  326. ]
  327. ]
  328. ];
  329. }
  330. }
  331. $pushTask = new PushTask($pushLists);
  332. Task::deliver($pushTask);
  333. }
  334. break;
  335. }
  336. if ($data['messageId']) {
  337. $pushLists = [];
  338. $pushLists[] = [
  339. 'fd' => $frame->fd,
  340. 'msg' => [
  341. 'messageType' => 'back',
  342. 'messageId' => $data['messageId'],
  343. 'body' => $back,
  344. ]
  345. ];
  346. $pushTask = new PushTask($pushLists);
  347. Task::deliver($pushTask);
  348. }
  349. }
  350. /**
  351. * 关闭连接时触发
  352. * @param Server $server
  353. * @param $fd
  354. * @param $reactorId
  355. */
  356. public function onClose(Server $server, $fd, $reactorId)
  357. {
  358. $this->deleteUser($fd);
  359. }
  360. /** ****************************************************************************** */
  361. /** ****************************************************************************** */
  362. /** ****************************************************************************** */
  363. /**
  364. * 保存用户
  365. * @param $fd
  366. * @param $channel
  367. * @param $username
  368. */
  369. private function saveUser($fd, $channel, $username)
  370. {
  371. try {
  372. DB::transaction(function () use ($username, $channel, $fd) {
  373. $this->deleteUser($fd);
  374. DB::table('ws')->updateOrInsert([
  375. 'key' => md5($fd . '@' . $channel . '@' . $username)
  376. ], [
  377. 'fd' => $fd,
  378. 'username' => $username,
  379. 'channel' => $channel,
  380. 'update' => time()
  381. ]);
  382. });
  383. } catch (\Throwable $e) {
  384. }
  385. }
  386. /**
  387. * 清除用户
  388. * @param $fd
  389. */
  390. private function deleteUser($fd)
  391. {
  392. DB::table('ws')->where('fd', $fd)->delete();
  393. }
  394. /**
  395. * 获取用户
  396. * @param string $fd
  397. * @param string $channel
  398. * @param string $username
  399. * @return array
  400. */
  401. private function getUser($fd = '', $channel = '', $username = '')
  402. {
  403. $array = [];
  404. if ($fd) $array['fd'] = $fd;
  405. if ($channel) $array['channel'] = $channel;
  406. if ($username) $array['username'] = $username;
  407. if (empty($array)) {
  408. return [];
  409. }
  410. return Base::DBC2A(DB::table('ws')->select(['fd', 'username', 'channel'])->where($array)->get());
  411. }
  412. private function getUserOfFd($fd, $channel = '') {
  413. return $this->getUser($fd, $channel);
  414. }
  415. private function getUserOfName($username, $channel = '') {
  416. return $this->getUser('', $channel, $username);
  417. }
  418. /**
  419. * 获取团队所有在线用户
  420. * @return array|string
  421. */
  422. private function getTeamUsers()
  423. {
  424. return Base::DBC2A(DB::table('ws')->select(['fd', 'username', 'channel'])->where([
  425. ['update', '>', time() - 600],
  426. ])->get());
  427. }
  428. }