ChatService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. <?php
  2. namespace App\JsonRpc;
  3. use App\Model\ChatFriends;
  4. use App\Model\ChatGroups;
  5. use App\Model\ChatGroupsMember;
  6. use App\Model\ChatRecords;
  7. use App\Model\ChatTopic;
  8. use App\Model\ChatTopicsReply;
  9. use App\Model\User;
  10. use App\Tools\PublicData;
  11. use App\Tools\Result;
  12. use Hyperf\DbConnection\Db;
  13. use Hyperf\RpcServer\Annotation\RpcService;
  14. #[RpcService(name: "ChatService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
  15. class ChatService implements ChatServiceInterface
  16. {
  17. /**
  18. * 获取用户信息
  19. * @param array $data
  20. * @return array
  21. */
  22. public function getFriendInfo(array $data): array
  23. {
  24. $result = ChatFriends::where('friend_id', $data['friend_id'])
  25. ->where('user_id', $data['user_id'])
  26. ->select(
  27. 'chat_friends.*',
  28. 'user.user_name',
  29. 'user.mobile',
  30. 'user.nickname',
  31. 'user.avatar'
  32. )
  33. ->leftJoin('user', 'user.id', '=', 'chat_friends.friend_id')
  34. ->first();
  35. return Result::success($result);
  36. }
  37. /**
  38. * 搜索好友
  39. * @param array $data
  40. * @return array
  41. */
  42. public function searchFriend(array $data): array
  43. {
  44. $keyword = $data['keyword'];
  45. $userId = $data['user_id'];
  46. $result = User::where('user_name', 'like', '%' . $data['keyword'] . '%')
  47. ->orWhere('nickname', 'like', '%' . $data['keyword'] . '%')
  48. ->orWhere('mobile', 'like', '%' . $data['keyword'] . '%')
  49. ->leftJoin('chat_friends', function ($join) use ($userId) {
  50. $join->on('user.id', '=', 'chat_friends.friend_id')
  51. ->where('chat_friends.user_id', $userId);
  52. })
  53. ->select('user.*', 'chat_friends.remark as remark', 'chat_friends.id as isfriend')
  54. ->get();
  55. if ($result) {
  56. return Result::success($result);
  57. } else {
  58. return Result::error('没有找到相关好友');
  59. }
  60. }
  61. /**
  62. * 添加申请
  63. * @param array $data
  64. * @return array
  65. */
  66. public function addFriend(array $data): array
  67. {
  68. Db::beginTransaction();
  69. try
  70. {
  71. // 检查是否存在相同的记录
  72. $existingRecord = ChatFriends::where([
  73. 'user_id' => $data['user_id'],
  74. 'friend_id' => $data['friend_id'],
  75. ])->first();
  76. if ($existingRecord) {
  77. Db::rollBack();
  78. if ($existingRecord->status == 1) {
  79. return Result::error("好友申请已存在", 0);
  80. } elseif ($existingRecord->status == 2) {
  81. return Result::error("已经是好友关系", 0);
  82. }
  83. }
  84. $result = ChatFriends::insertGetId($data);
  85. Db::commit();
  86. } catch (\Throwable $ex) {
  87. Db::rollBack();
  88. var_dump($ex->getMessage());
  89. return Result::error("添加好友申请失败", 0);
  90. }
  91. return Result::success("添加成功");
  92. }
  93. /**
  94. * 好友列表
  95. * @param array $data
  96. * @return array
  97. */
  98. public function getFriendsList(array $data): array
  99. {
  100. var_dump($data);
  101. $result = ChatFriends::leftJoin('user', 'user.id', '=', 'chat_friends.friend_id')
  102. ->select(
  103. 'chat_friends.*',
  104. 'user.user_name',
  105. 'user.mobile',
  106. 'user.nickname',
  107. 'user.avatar'
  108. )
  109. ->where([
  110. ['user_id', $data['user_id']],
  111. ['chat_friends.status', $data['status']], // 明确指定 chat_friends 表中的 status 列
  112. ])
  113. ->get();
  114. return Result::success($result);
  115. }
  116. /**
  117. * 好友列表
  118. * @param array $data
  119. * @return array
  120. */
  121. public function getFriendsApplyList(array $data): array
  122. {
  123. var_dump($data);
  124. $result = ChatFriends::leftJoin('user', 'user.id', '=', 'chat_friends.user_id')
  125. ->select(
  126. 'chat_friends.*',
  127. 'user.user_name',
  128. 'user.mobile',
  129. 'user.nickname',
  130. 'user.avatar'
  131. )
  132. ->where([
  133. ['friend_id', $data['friend_id']],
  134. ['chat_friends.status', $data['status']], // 明确指定 chat_friends 表中的 status 列
  135. ])
  136. ->get();
  137. return Result::success($result);
  138. }
  139. /**
  140. * 更新申请
  141. * @param array $data
  142. * @return array
  143. */
  144. public function applyFriend(array $data): array
  145. {
  146. $status = $data['status'];
  147. //判断同意还是不同意
  148. if ($status == 2) {
  149. Db::beginTransaction();
  150. try {
  151. $where = [
  152. 'id' => $data['id'],
  153. 'status' => 1,
  154. ];
  155. $fr = ChatFriends::where($where)->first();
  156. if (empty($fr)) {
  157. Db::rollBack();
  158. return Result::error("好友申请记录不存在,已经是好友了", 0);
  159. }
  160. $data['status'] = $status;
  161. $data['applied_at'] = date("Y-m-d H:i:s"); //好友审核时间操作人friend_id
  162. unset($data['user_id']);
  163. ChatFriends::where($where)->update($data);
  164. Db::table('chat_friends')
  165. ->updateOrInsert(
  166. [
  167. 'user_id' => $fr['friend_id'],
  168. 'friend_id' => $fr['user_id'],
  169. ],
  170. [
  171. 'status' => $status,
  172. ]
  173. );
  174. Db::commit();
  175. } catch (\Throwable $ex) {
  176. Db::rollBack();
  177. var_dump($ex->getMessage());
  178. return Result::error("同意添加为好友失败", 0);
  179. }
  180. return Result::success(['添加成功']);
  181. } else if ($status == 4) { //拒绝
  182. Db::beginTransaction();
  183. try {
  184. $where1 = [
  185. 'id' => $data['id'],
  186. ];
  187. $deletedRows = ChatFriends::where($where1)->delete();
  188. if ($deletedRows > 0) {
  189. Db::commit();
  190. } else {
  191. // 处理记录不存在的情况
  192. Db::rollBack();
  193. throw new \Exception('记录不存在');
  194. }
  195. } catch (\Throwable $ex) {
  196. Db::rollBack();
  197. var_dump($ex->getMessage());
  198. return Result::error("拒绝添加好友失败", 0);
  199. }
  200. return Result::success(['已经拒绝']);
  201. }
  202. }
  203. /**
  204. * 删除好友
  205. * @param array $data
  206. * @return array
  207. */
  208. public function delFriend(array $data): array
  209. {
  210. Db::beginTransaction();
  211. try {
  212. $where = [
  213. 'user_id' => $data['user_id'],
  214. 'friend_id' => $data['friend_id'],
  215. ];
  216. $orwhere = [
  217. 'friend_id' => $data['user_id'],
  218. 'user_id' => $data['friend_id'],
  219. ];
  220. $result = ChatFriends::where($where)
  221. ->orWhere($orwhere)->delete();
  222. var_dump($result, '-0------------------');
  223. $where = [
  224. 'user_id' => $data['user_id'],
  225. 'receiver_id' => $data['friend_id'],
  226. ];
  227. $orwhere = [
  228. 'receiver_id' => $data['user_id'],
  229. 'user_id' => $data['friend_id'],
  230. ];
  231. ChatRecords::where($where)->orWhere($orwhere)->delete();
  232. Db::commit();
  233. if ($result) {
  234. return Result::success("删除成功”");
  235. } else {
  236. return Result::error('删除失败');
  237. }
  238. } catch (\Exception $e) {
  239. Db::rollback();
  240. return Result::error($e->getMessage());
  241. }
  242. }
  243. /**
  244. * 是否好友
  245. * @param array $data
  246. * @return array
  247. */
  248. public function isFriend(array $data): array
  249. {
  250. $where = [
  251. 'user_id' => $data['user_id'],
  252. 'friend_id' => $data['friend_id'],
  253. ];
  254. $result = ChatFriends::where($where)->first();
  255. if ($result) {
  256. return Result::success(true);
  257. } else {
  258. return Result::error('不是好友');
  259. }
  260. }
  261. /**
  262. * 添加聊天内容
  263. * @param array $data
  264. * @return array
  265. */
  266. public function addChatRecords(array $data): array
  267. {
  268. Db::beginTransaction();
  269. try {;
  270. //添加会话内容
  271. $ChatRecordsData = [[
  272. 'msg_type' => $data['msg_type'] ?? 0,
  273. 'user_id' => $data['user_id'] ?? 0,
  274. 'is_read' => $data['is_read'] ?? 0,
  275. 'talk_type' => $data['talk_type'] ?? 0,
  276. 'action' => $data['action'] ?? 0,
  277. 'group_receiver_id' => $data['group_receiver_id'] ?? 0,
  278. 'content' => $data['content'] ?? '',
  279. 'receiver_id' => $data['receiver_id'] ?? '',
  280. ]];
  281. ChatRecords::insert($ChatRecordsData);
  282. Db::commit();} catch (\Throwable $ex) {
  283. Db::rollBack();
  284. var_dump($ex->getMessage());
  285. return Result::error("存储消息失败", 0);
  286. }
  287. return Result::success([]);
  288. }
  289. /**
  290. * 修改好友备注
  291. * @param array $data
  292. * @return array
  293. */
  294. public function updateFriend(array $data): array
  295. {
  296. $result = ChatFriends::where(['user_id' => $data['user_id'],
  297. 'friend_id' => $data['friend_id'],
  298. 'status' => 2,
  299. ])->update(['remark' => $data['remark']]);
  300. if ($result) {
  301. return Result::success('修改成功');
  302. } else {
  303. return Result::error('修改失败');
  304. }
  305. }
  306. /**
  307. * 会话列表
  308. * @param array $data
  309. * @return array
  310. */
  311. public function getConversation(array $data): array
  312. {
  313. $userId = $data['user_id'];
  314. $unreadMessages = ChatRecords::where('user_id', $userId)
  315. ->where('is_read', 0)
  316. // ->where('action', 'recieved')
  317. ->leftJoin('user', 'chat_records.receiver_id', '=', 'user.id')
  318. ->leftJoin('chat_groups', 'chat_records.receiver_id', '=', 'chat_groups.id')
  319. ->select(
  320. 'receiver_id',
  321. DB::raw('COUNT(receiver_id) AS num'),
  322. DB::raw('MAX(chat_records.id) AS max_id'),
  323. 'user.user_name as user_name',
  324. 'user.avatar as avatar',
  325. 'user.mobile as mobile',
  326. 'chat_groups.group_name as group_name'
  327. )
  328. ->groupBy('receiver_id')
  329. ->orderBy(DB::raw('MAX(chat_records.id)'), 'desc')
  330. ->get();
  331. // 查询已读消息,并将 num 字段设置为 0
  332. $readMessages = ChatRecords::where('user_id', $userId)
  333. ->where('is_read', 1)
  334. // ->where('action', 'recieved')
  335. ->leftJoin('user', 'chat_records.receiver_id', '=', 'user.id')
  336. ->leftJoin('chat_groups', 'chat_records.receiver_id', '=', 'chat_groups.id')
  337. ->select(
  338. 'receiver_id',
  339. DB::raw('0 AS num'),
  340. DB::raw('MAX(chat_records.id) AS max_id'),
  341. 'user.user_name as user_name',
  342. 'user.avatar as avatar',
  343. 'user.mobile as mobile',
  344. 'chat_groups.group_name as group_name'
  345. )
  346. ->groupBy('receiver_id')
  347. ->orderBy(DB::raw('MAX(chat_records.id)'), 'desc')
  348. ->get();
  349. // 合并未读消息和已读消息
  350. // $allMessages = array_merge($unreadMessages->toArray(), $readMessages->toArray());
  351. // 使用关联数组去重,并优先保留未读消息
  352. $allMessages = [];
  353. foreach ($unreadMessages as $message) {
  354. $allMessages[$message['receiver_id']] = $message->toArray();
  355. }
  356. foreach ($readMessages as $message) {
  357. if (strlen($message['receiver_id']) === 18) {
  358. } else {
  359. // $allMessages[$message['receiver_id']] = $message->toArray();
  360. }
  361. if (!isset($allMessages[$message['receiver_id']])) {
  362. $allMessages[$message['receiver_id']] = $message->toArray();
  363. }
  364. }
  365. // var_dump($allMessages);
  366. // 处理结果,判断是否是群聊
  367. $formattedMessages = [];
  368. foreach ($allMessages as $message) {
  369. $formattedMessage = [
  370. 'receiver_id' => $message['receiver_id'],
  371. 'num' => $message['num'],
  372. 'max_id' => $message['max_id'],
  373. 'user_name' => $message['user_name'],
  374. 'avatar' => $message['avatar'],
  375. 'mobile' => $message['mobile'],
  376. 'group_name' => $message['group_name'],
  377. ];
  378. if (strlen($message['receiver_id']) === 18) { // 判断是否是 UUID
  379. $formattedMessage['type'] = 'group';
  380. $formattedMessage['name'] = $message['group_name'];
  381. $formattedMessage['is_group'] = 1;
  382. } else {
  383. $formattedMessage['type'] = 'user';
  384. $formattedMessage['name'] = $message['user_name'];
  385. $formattedMessage['is_group'] = 0;
  386. }
  387. $formattedMessages[] = $formattedMessage;
  388. }
  389. if (!empty($formattedMessages)) {
  390. return Result::success($formattedMessages);
  391. } else {
  392. return Result::error('没有消息');
  393. }
  394. }
  395. /**
  396. * 获取聊天记录
  397. * @param array $data
  398. * @return array
  399. */
  400. public function getChatRecords(array $data): array
  401. {
  402. var_dump('222222');
  403. Db::beginTransaction();
  404. try {
  405. $userId = $data['user_id'];
  406. $friendId = $data['friend_id'];
  407. $result = ChatRecords::where(function ($query) use ($userId, $friendId) {
  408. $query->where('user_id', $userId)->where('receiver_id', $friendId);
  409. })
  410. // ->orWhere(function ($query) use ($userId, $friendId) {
  411. // $query->where('user_id', $friendId)->where('receiver_id', $userId);
  412. // })
  413. ->leftJoin('user as u1', 'chat_records.user_id', '=', 'u1.id')
  414. ->leftJoin('user as u2', 'chat_records.receiver_id', '=', 'u2.id')
  415. ->select('chat_records.*', 'u1.user_name as user_id_name', 'u1.avatar as user_avatar', 'u2.user_name as receiver_id_name', 'u2.avatar as receiver_avatar')
  416. ->orderBy('id', 'asc')->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  417. //更新聊天记录已读
  418. ChatRecords::where('user_id', $userId)
  419. ->where('receiver_id', $friendId)
  420. ->where('is_read', 0)
  421. ->where('talk_type', 1)
  422. ->update(['is_read' => 1]);
  423. Db::commit();
  424. } catch (\Throwable $ex) {
  425. Db::rollBack();
  426. var_dump($ex->getMessage());
  427. return Result::error("获取聊天记录失败", 0);
  428. }
  429. if ($result) {
  430. return Result::success($result);
  431. } else {
  432. return Result::error('没有聊天记录');
  433. }
  434. }
  435. /**
  436. * 获取群聊天记录
  437. * @param array $data
  438. * @return array
  439. */
  440. public function getGroupChatRecords(array $data): array
  441. {
  442. Db::beginTransaction();
  443. try {
  444. $userId = $data['user_id'];
  445. $group_id = $data['group_id'];
  446. $result = ChatRecords::where('receiver_id', $group_id)
  447. ->where('user_id', $userId)
  448. ->leftJoin('user as u1', 'chat_records.user_id', '=', 'u1.id')
  449. ->leftJoin('user as u2', 'chat_records.group_receiver_id', '=', 'u2.id')
  450. ->select('chat_records.*', 'u1.user_name as user_id_name', 'u1.avatar as user_avatar', 'u2.user_name as receiver_id_name', 'u2.avatar as receiver_avatar')
  451. ->orderBy('id', 'asc')->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  452. //更新群聊天记录
  453. ChatRecords::where('receiver_id', $group_id)
  454. ->where('user_id', $userId)
  455. ->update(['is_read' => 1]);
  456. Db::commit();
  457. } catch (\Throwable $ex) {
  458. Db::rollBack();
  459. var_dump($ex->getMessage());
  460. return Result::error("获取群聊天记录失败", 0);
  461. }
  462. if ($result) {
  463. return Result::success($result);
  464. } else {
  465. return Result::error('没有群消息');
  466. }
  467. }
  468. /**
  469. * 群组 - 创建群
  470. * @param array $data
  471. * @return array
  472. */
  473. public function addGroup(array $data): array
  474. {
  475. Db::beginTransaction();
  476. try {
  477. //创建群
  478. $groupData = [
  479. 'id' => PublicData::uuid(),
  480. 'creator_id' => $data['user_id'],
  481. 'group_name' => $data['group_name'],
  482. 'avatar' => $data['avatar'] ?? '',
  483. 'profile' => $data['profile'] ?? '',
  484. ];
  485. ChatGroups::insert($groupData);
  486. //创建群用户
  487. $groupMemberData = [];
  488. if ($data['group_member']) {
  489. foreach ($data['group_member'] as $key => $val) {
  490. $groupMemberData[$key] = [
  491. 'id' => PublicData::uuid(),
  492. 'group_id' => $groupData['id'],
  493. 'user_id' => $val,
  494. 'leader' => $data['user_id'] == $val ? 2 : 0,
  495. ];
  496. }
  497. }
  498. ChatGroupsMember::insert($groupMemberData);
  499. //插入一条消息
  500. $chatRecordsData = [
  501. 'user_id' => $data['user_id'],
  502. 'receiver_id' => $groupData['id'],
  503. 'content' => '我创建了一个群' . Date('Y-m-d H:i:s'),
  504. 'msg_type' => 1,
  505. 'is_read' => 0,
  506. 'talk_type' => 2,
  507. 'action' => 'said',
  508. 'group_receiver_id' => $data['user_id'],
  509. ];
  510. ChatRecords::insert($chatRecordsData);
  511. Db::commit();
  512. } catch (\Throwable $ex) {
  513. Db::rollBack();
  514. var_dump($ex->getMessage());
  515. return Result::error("创建群失败", 0);
  516. }
  517. return Result::success([]);
  518. }
  519. /**
  520. * 群组 - 加入群
  521. * @param array $data
  522. * @return array
  523. */
  524. public function addGroupMember(array $data): array
  525. {
  526. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->update(['leader' => 2]);
  527. if ($result) {
  528. return Result::success('修改成功');
  529. } else {
  530. return Result::error('修改失败');
  531. }
  532. }
  533. /**
  534. * 群组 - 群信息
  535. * @param array $data
  536. * @return array
  537. */
  538. public function getGroupInfo(array $data): array
  539. {
  540. $result = ChatGroups::where(['chat_groups.id' => $data['group_id']])
  541. ->join('user', 'chat_groups.creator_id', '=', 'user.id')
  542. ->select('chat_groups.*', 'user.user_name as user_name', 'user.avatar as avatar')
  543. ->first();
  544. return Result::success($result);
  545. }
  546. /**
  547. * 群组 - 删除群
  548. * @param array $data
  549. * @return array
  550. */
  551. public function delGroup(array $data): array
  552. {
  553. Db::beginTransaction();
  554. try {
  555. $groupMember = ChatGroupsMember::where(['group_id' => $data['group_id']])->delete();
  556. $result = ChatGroups::where(['id' => $data['group_id']])->delete();
  557. $result = ChatRecords::where(['receiver_id' => $data['group_id']])->delete();
  558. //群聊记录
  559. Db::commit();
  560. } catch (\Throwable $ex) {
  561. Db::rollBack();
  562. var_dump($ex->getMessage());
  563. return Result::error("删除群失败", 0);
  564. }
  565. if ($result) {
  566. return Result::success('删除成功');
  567. } else {
  568. return Result::error('删除失败');
  569. }
  570. }
  571. /**
  572. * 群组 - 退出群
  573. * @param array $data
  574. * @return array
  575. */
  576. public function quitGroup(array $data): array
  577. {
  578. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  579. ChatRecords::where(['receiver_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  580. if ($result) {
  581. return Result::success('退出成功');
  582. } else {
  583. return Result::error('退出失败');
  584. }
  585. }
  586. /**
  587. * 群组 - 我的群
  588. * @param array $data
  589. * @return array
  590. */
  591. public function getGroupList(array $data): array
  592. {
  593. $result = ChatGroupsMember::where(['user_id' => $data['user_id']])
  594. ->leftJoin('chat_groups', 'chat_groups_members.group_id', '=', 'chat_groups.id')
  595. ->select('chat_groups.*', 'chat_groups_members.group_id as group_id')
  596. ->orderBy('chat_groups.id', 'desc')
  597. ->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  598. return Result::success($result);
  599. }
  600. /**
  601. * 群组 - 删除群成员
  602. * @param array $data
  603. * @return array
  604. */
  605. public function delGroupMembers(array $data): array
  606. {
  607. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  608. if ($result) {
  609. return Result::success('删除成功');
  610. } else {
  611. return Result::error('删除失败');
  612. }
  613. }
  614. /**
  615. * 群组 - 更新群
  616. * @param array $data
  617. * @return array
  618. */
  619. public function updateGroup(array $data): array
  620. {
  621. // 提取需要的字段
  622. $groupId = $data['group_id'];
  623. $groupName = $data['group_name'] ?? null;
  624. $profile = $data['profile'] ?? null;
  625. $avatar = $data['avatar'] ?? null;
  626. // 查询群组
  627. $group = ChatGroups::find($groupId);
  628. if (!$group) {
  629. return Result::error('群组不存在');
  630. }
  631. // 更新群组信息
  632. if ($groupName !== null) {
  633. $group->group_name = $groupName;
  634. }
  635. if ($profile !== null) {
  636. $group->profile = $profile;
  637. }
  638. if ($avatar !== null) {
  639. $group->avatar = $avatar;
  640. }
  641. // 保存更改
  642. if ($group->save()) {
  643. return Result::success($group->toArray());
  644. } else {
  645. return Result::error('更新群组信息失败');
  646. }
  647. }
  648. /**
  649. * 群组 - 删除群
  650. * @param array $data
  651. * @return array
  652. */
  653. public function deleteGroup(array $data): array
  654. {
  655. $result = ChatGroups::where(['id' => $data['group_id']])->delete();
  656. if ($result) {
  657. return Result::success('删除成功');
  658. } else {
  659. return Result::error('删除失败');
  660. }
  661. }
  662. /**
  663. * 群组 - 群用户列表
  664. * @param array $data
  665. * @return array
  666. */
  667. public function getGroupMembers(array $data): array
  668. {
  669. $groupMember = ChatGroupsMember::where(['group_id' => $data['group_id']])
  670. ->leftJoin('user as u1', 'chat_groups_members.user_id', '=', 'u1.id')
  671. ->select('chat_groups_members.*', 'u1.user_name', 'u1.avatar')
  672. ->orderBy('id', 'desc')
  673. ->get();
  674. return Result::success($groupMember);
  675. }
  676. /**
  677. * 群组 - 添加群
  678. * @param array $data
  679. * @return array
  680. */
  681. public function joinGroup(array $data): array
  682. {
  683. $group = ChatGroups::where(['id' => $data['group_id']])->first();
  684. if (empty($group)) {
  685. return Result::error("群不存在", 0);
  686. }
  687. $groupMember = ChatGroupsMember::where(['user_id' => $data['user_id'], 'group_id' => $data['group_id']])->first();
  688. if ($groupMember) {
  689. return Result::error("已加入群", 0);
  690. }
  691. $info = [
  692. 'id' => PublicData::uuid(),
  693. 'user_id' => $data['user_id'],
  694. 'group_id' => $data['group_id'],
  695. ];
  696. $result = ChatGroupsMember::insertGetId($info);
  697. if ($result) {
  698. return Result::success($data);
  699. } else {
  700. return Result::error($data);
  701. };
  702. }
  703. /**
  704. * 话题 - 列表
  705. * @param array $data
  706. * @return array
  707. */
  708. public function getTopicsList(array $data): array
  709. {
  710. $where = [];
  711. if (!empty($data['title'])) {
  712. $where[] = ['chat_topics.title', 'like', '%' . $data['title'] . '%'];
  713. }
  714. if (!empty($data['user_id'])) {
  715. $where[] = ['chat_topics.user_id', '=', $data['user_id']];
  716. }
  717. if (!empty($data['status'])) {
  718. $where[] = ['chat_topics.status', '=', $data['status']];
  719. }
  720. if (!empty($data['type'])) {
  721. $where[] = ['chat_topics.type', '=', $data['type']];
  722. }
  723. if (!empty($data['nickname'])) {
  724. $where[] = ['user.nickname', '=', $data['nickname']];
  725. }
  726. var_dump($where);
  727. $result = ChatTopic::where($where)
  728. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  729. ->leftJoin('chat_topics_reply', 'chat_topics.id', '=', 'chat_topics_reply.topic_id')
  730. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name'
  731. ,
  732. DB::raw('count(chat_topics_reply.id) as num'))
  733. ->groupBy('chat_topics.id')
  734. ->orderBy('chat_topics.id', 'desc')
  735. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  736. return Result::success($result);
  737. }
  738. public function getTopic(array $data): array
  739. {
  740. $result = ChatTopic::where(['id' => $data['id']])->first();
  741. return Result::success($result);
  742. }
  743. public function addTopic(array $data): array
  744. {
  745. $chattopic = [];
  746. try {
  747. $data['created_at'] = date('Y-m-d H:i:s');
  748. $data['updated_at'] = date('Y-m-d H:i:s');
  749. $result = ChatTopic::insertGetId($data);
  750. if ($result && $data['is_group'] == 1) {
  751. //chat_group
  752. $group_id = PublicData::uuid();
  753. $groupData = [
  754. 'id' => $group_id,
  755. 'creator_id' => $data['user_id'],
  756. 'group_name' => $data['group_name'] ?? '',
  757. 'profile' => $data['profile'] ?? 0,
  758. ];
  759. $groupResult = ChatGroups::insertGetId($groupData);
  760. $groupMemberData = [
  761. 'id' => PublicData::uuid(),
  762. 'user_id' => $data['user_id'],
  763. 'group_id' => $group_id,
  764. 'leader' => 2,
  765. ];
  766. $groupMemberResult = ChatGroupsMember::insertGetId($groupMemberData);
  767. //更新result的 group_id
  768. $data['group_id'] = $group_id;
  769. ChatTopic::where(['id' => $result])->update($data);
  770. //插入一条消息
  771. $chatRecordsData = [
  772. 'user_id' => $data['user_id'],
  773. 'receiver_id' => $group_id,
  774. 'content' => '我创建了一个群' . Date('Y-m-d H:i:s'),
  775. 'msg_type' => 1,
  776. 'is_read' => 0,
  777. 'talk_type' => 2,
  778. 'action' => 'said',
  779. 'group_receiver_id' => $data['user_id'],
  780. ];
  781. ChatRecords::insert($chatRecordsData);
  782. // 查询 Chattopic 数据
  783. $chattopic = Chattopic::find($result);
  784. } else {
  785. $chattopic = Chattopic::find($result);
  786. }
  787. Db::beginTransaction();
  788. Db::commit();
  789. } catch (\Exception $e) {
  790. Db::rollBack();
  791. return Result::error($data, $e->getMessage());
  792. }
  793. return Result::success($chattopic);
  794. }
  795. public function updateTopic(array $data): array
  796. {
  797. $result = ChatTopic::where(['id' => $data['id']])->update($data);
  798. if ($result) {
  799. return Result::success($data);
  800. } else {
  801. return Result::error($data);
  802. };
  803. }
  804. public function delTopic(array $data): array
  805. {
  806. $result = ChatTopic::where(['id' => $data['id']])->delete();
  807. //删除群和成员和聊天
  808. //删除话题回复
  809. if ($result) {
  810. return Result::success($data);
  811. } else {
  812. return Result::error('删除失败');
  813. };
  814. }
  815. public function getTopicInfo(array $data): array
  816. {
  817. $result = ChatTopic::where(['chat_topics.id' => $data['id']])
  818. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  819. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  820. ->first();
  821. return Result::success($result);
  822. }
  823. public function addReply(array $data): array
  824. {
  825. $result = ChatTopic::where(['id' => $data['id']])->get();
  826. if ($result) {
  827. $replydata['created_at'] = date('Y-m-d H:i:s');
  828. $replydata['updated_at'] = date('Y-m-d H:i:s');
  829. $replydata['content'] = $data['content'];
  830. $replydata['user_id'] = $data['user_id'];
  831. $replydata['topic_id'] = $data['id'];
  832. $re = ChatTopicsReply::insertGetId($replydata);
  833. }
  834. if ($re) {
  835. return Result::success($data);
  836. } else {
  837. return Result::error($data);
  838. }
  839. }
  840. public function getTopicReply(array $data): array
  841. {
  842. var_dump($data);
  843. $result = ChatTopicsReply::where(['topic_id' => $data['id']])
  844. ->leftJoin('user', 'user.id', '=', 'chat_topics_reply.user_id')
  845. ->select('chat_topics_reply.*', 'user.nickname', 'user.avatar', 'user.user_name')
  846. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  847. return Result::success($result);
  848. }
  849. /**
  850. * 修改群成员
  851. * @param array $data
  852. * @return array
  853. */
  854. public function updateGroupMembers(array $data): array
  855. {
  856. $where = [
  857. 'group_id' => $data['group_id'],
  858. ];
  859. $group_id = $data['group_id'];
  860. //先删除群成员
  861. $result = ChatGroupsMember::where($where)
  862. ->where([["user_id", '!=', $data['user_id']]])->delete();
  863. $groupMemberData = [];
  864. foreach ($data['group_member'] as $value) {
  865. $groupMemberData[] = [
  866. 'id' => PublicData::uuid(),
  867. 'user_id' => $value,
  868. 'group_id' => $group_id,
  869. 'leader' => 0,
  870. ];
  871. }
  872. $result = ChatGroupsMember::where($where)->insert($groupMemberData);
  873. // 获取群信息
  874. $groupInfo = ChatGroups::where(['id' => $group_id])->first();
  875. if ($result) {
  876. return Result::success($groupInfo);
  877. } else {
  878. return Result::error($data);
  879. }
  880. }
  881. public function clearGroupRecords(array $data): array
  882. {
  883. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['id']])->delete();
  884. if ($result) {
  885. return Result::success("删除成功");
  886. } else {
  887. return Result::error("删除失败");
  888. }
  889. }
  890. public function recallRecord(array $data): array
  891. {
  892. //获取所有id,并删除掉
  893. $ids = array_column($data, 'id');
  894. $result = ChatRecords::whereIn('id', $ids)->delete();
  895. if ($result) {
  896. return Result::success("删除成功");
  897. } else {
  898. return Result::error("删除失败");
  899. }
  900. }
  901. public function clearRecords(array $data): array
  902. {
  903. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['friend_id']])->delete();
  904. if ($result) {
  905. return Result::success("删除成功");
  906. } else {
  907. return Result::error("删除失败");
  908. }
  909. }
  910. public function getRecordByContent(array $data): array
  911. {
  912. $result = ChatRecords::where(['chat_records.user_id' => $data['user_id'], 'chat_records.receiver_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  913. ->orWhere(['chat_records.receiver_id' => $data['user_id'], 'chat_records.user_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  914. ->all();
  915. if ($result) {
  916. return Result::success($result['id']);
  917. } else {
  918. return Result::error("没有数据");
  919. }
  920. }
  921. public function getRecord(array $data): array
  922. {
  923. $result = ChatRecords::where(['chat_records.id' => $data['id']])
  924. ->leftJoin('user', 'user.id', '=', 'chat_records.user_id')
  925. ->leftJoin('user as user2', 'user2.id', '=', 'chat_records.receiver_id')
  926. ->select('chat_records.*', 'user.nickname', 'user.avatar', 'user.user_name', 'user2.nickname as receiver_nickname', 'user2.avatar as receiver_avatar')
  927. ->get();
  928. return Result::success($result);
  929. }
  930. public function delReply(array $data): array
  931. {
  932. $result = ChatTopicsReply::where(['id' => $data['id']])->delete();
  933. if ($result) {
  934. return Result::success("删除成功");
  935. } else {
  936. return Result::error("删除失败");
  937. }
  938. }
  939. public function delAllReply(array $data): array
  940. {
  941. $result = ChatTopicsReply::where(['topic_id' => $data['topicid']])->delete();
  942. if ($result) {
  943. return Result::success("删除成功");
  944. } else {
  945. return Result::error("删除失败");
  946. }
  947. }
  948. public function getTopicsListAdmin(array $data): array
  949. {
  950. $where = [];
  951. if (!empty($data['type'])) {
  952. $where['type'] = $data['type'];
  953. }
  954. if (!empty($data['title'])) {
  955. $where['title'] = $data['title'];
  956. }
  957. $result = ChatTopic::where($where)
  958. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  959. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  960. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  961. return Result::success($result);
  962. }
  963. }