Im.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. <?php
  2. namespace app\enterprise\controller;
  3. use app\BaseController;
  4. use think\facade\Session;
  5. use think\facade\Db;
  6. use app\enterprise\model\{User, Message, GroupUser, Friend,Group,ChatDelog};
  7. use GatewayClient\Gateway;
  8. use Exception;
  9. use think\facade\Cache;
  10. use app\manage\model\{Config};
  11. use app\admin\model\GuessAskLanguages;
  12. use app\admin\model\QuestionLanguages;
  13. use app\admin\model\Complaint;
  14. use app\admin\model\ComplaintItem;
  15. use app\admin\model\Score;
  16. class Im extends BaseController
  17. {
  18. protected $fileType = ['file', 'image','video','voice','emoji'];
  19. /**
  20. * 给客服打分
  21. */
  22. public function Score()
  23. {
  24. $score = $this->request->param('score');
  25. $msg_id = $this->request->param('msg_id');
  26. if (empty($msg_id)) {
  27. return $this->error('参数有误',[], 10009);
  28. }
  29. if (empty($score)) {
  30. return $this->error('请打分',[], 10009);
  31. }
  32. $user_id = $this->userInfo['user_id'];
  33. $user = User::where('user_id', $user_id)->find();
  34. if (!$user) {
  35. return $this->error('用户不存在',[], 10009);
  36. }
  37. $exist = Message::where('msg_id', $msg_id)->where('to_user', $user_id)->find();
  38. if ($exist) {
  39. if ( $exist['is_click'] == 1) {
  40. return $this->error('已评价',[], 10009);
  41. }
  42. $extends = $exist['extends'] && !is_array($exist['extends']) ? json_decode($exist['extends'], true) : $exist['extends'];
  43. if (!empty($extends['cs_uid'])) {
  44. Score::create([
  45. 'user_id' => $user_id,
  46. 'cs_uid' => $extends['cs_uid'],
  47. 'score' => (int)$score,
  48. ]);
  49. //保留一位小数
  50. $avg_score = Score::where('cs_uid', $extends['cs_uid'])->avg('score');
  51. $avg_score = number_format($avg_score, 1);
  52. User::where('user_id', $extends['cs_uid'])->update(['score' => $avg_score]);
  53. }
  54. $exist->is_click = 1;
  55. $exist->save();
  56. }
  57. return $this->success([],'提交成功');
  58. }
  59. /**
  60. */
  61. public function complaintList()
  62. {
  63. try {
  64. $params = $this->request->param();
  65. $page = $params['page'] ?? 1;
  66. $limit = $params['limit'] ?? 15;
  67. $language_code = $params['language_code'] ?? $this->lang;
  68. $query = ComplaintItem::where('language_code', $language_code);
  69. $count = $query->count();
  70. $list = $query->order('weight','desc')
  71. ->limit($limit)
  72. ->page($page)
  73. ->select();
  74. } catch (Exception $e) {
  75. return $this->error($e->getMessage());
  76. }
  77. return $this->success(['count' => $count, 'list' => $list]);
  78. }
  79. /**
  80. * 投诉客服
  81. */
  82. public function complaint()
  83. {
  84. $params = $this->request->param();
  85. if (empty($params['complaint_item_id'])) {
  86. return $this->error('请选择投诉项',[], 10009);
  87. }
  88. $user_id = $this->userInfo['user_id'];
  89. $user = User::where('user_id', $user_id)->find();
  90. if (!$user) {
  91. return $this->error('用户不存在',[], 10009);
  92. }
  93. $exist = Complaint::where('user_id', $user_id)->where('cs_uid', $user->cs_uid)->find();
  94. if ($exist) {
  95. return $this->error('您已投诉过该客服,无需重复投诉',[], 10009);
  96. }
  97. Complaint::create([
  98. 'user_id' => $user_id,
  99. 'cs_uid' => $user->cs_uid,
  100. 'complaint_item_id' => $params['complaint_item_id'],
  101. 'remark' => $params['remark'] ?? '',
  102. 'language_code' => $this->lang,
  103. ]);
  104. return $this->success([],'提交成功');
  105. }
  106. /**
  107. * 猜你想问列表
  108. */
  109. public function guessask()
  110. {
  111. try {
  112. $params = $this->request->param();
  113. $page = $params['page'] ?? 1;
  114. $limit = $params['limit'] ?? 15;
  115. $language_code = $this->lang;
  116. $query = GuessAskLanguages::where('language_code', $language_code)->where('status', 1);
  117. if (!empty($params['keyword'])) {
  118. $query = $query->where('name', 'like', '%'.$params['keyword'].'%');
  119. }
  120. if (isset($params['type']) && $params['type'] != '') {
  121. $query = $query->where('type', $params['type']);
  122. }
  123. $count = $query->count();
  124. $list = $query->order('is_top','desc')
  125. ->order('is_rec','desc')
  126. ->order('click_num','desc')
  127. ->limit($limit)
  128. ->page($page)
  129. ->select();
  130. } catch (Exception $e) {
  131. return $this->error($e->getMessage());
  132. }
  133. return $this->success(['count' => $count, 'list' => $list]);
  134. }
  135. /**
  136. * 猜你想问点击使用
  137. */
  138. function guessaskClick()
  139. {
  140. try {
  141. $id = $this->request->param('id');
  142. $info = GuessAskLanguages::where('id', $id)->where('status', 1)->find();
  143. if ($info) {
  144. $info->click_num = $info->click_num + 1;
  145. $info->save();
  146. }
  147. } catch (Exception $e) {
  148. return $this->error($e->getMessage());
  149. }
  150. return $this->success([]);
  151. }
  152. /**
  153. * 问题列表
  154. */
  155. function question()
  156. {
  157. try {
  158. $params = $this->request->param();
  159. $page = $params['page'] ?? 1;
  160. $limit = $params['limit'] ?? 15;
  161. $language_code = $this->lang;
  162. $query = QuestionLanguages::where('language_code', $language_code)->where('status', 1);
  163. if (isset($params['question_type']) && $params['question_type'] != '') {
  164. $query = $query->where('question_type', $params['question_type']);
  165. }
  166. $count = $query->count();
  167. $list = $query->order('weight','desc')
  168. ->limit($limit)
  169. ->page($page)
  170. ->select();
  171. } catch (Exception $e) {
  172. return error($e->getMessage());
  173. }
  174. return $this->success(['count' => $count, 'list' => $list]);
  175. }
  176. /**
  177. * 问题点赞、点否
  178. */
  179. function questionClick()
  180. {
  181. try {
  182. $is_like = $this->request->param('is_like');
  183. $msg_id = $this->request->param('msg_id');
  184. if (empty($msg_id) || !in_array($is_like, [1, 0])) {
  185. return $this->error('参数有误',[], 10009);
  186. }
  187. $user_id = $this->userInfo['user_id'];
  188. $exist = Message::where('msg_id', $msg_id)->where('to_user', $user_id)->find();
  189. if ($exist && $exist['is_click'] == 0) {
  190. $extends = $exist['extends'];
  191. $id = $extends['question_id'] ?? 0;
  192. if ($id) {
  193. if ($is_like == 1) {
  194. QuestionLanguages::where('id', $id)->update(['like_count'=>Db::raw('like_count+1')]);
  195. } else {
  196. QuestionLanguages::where('id', $id)->update(['dislike_count'=>Db::raw('dislike_count+1')]);
  197. }
  198. }
  199. $exist->is_click = $is_like == 1 ? 1 : 2;
  200. $exist->save();
  201. }
  202. } catch (Exception $e) {
  203. return $this->error($e->getMessage());
  204. }
  205. return $this->success([]);
  206. }
  207. /**
  208. * 转人工客服
  209. */
  210. function transferHuman()
  211. {
  212. try {
  213. $user_id = $this->userInfo['user_id'];
  214. $user = User::where('user_id', $user_id)->find();
  215. if (!$user) {
  216. return $this->error('用户不存在',[], 10009);
  217. }
  218. if ($user->role > 0) {
  219. return $this->error('系统管理员无法转人工',[], 10009);
  220. }
  221. if($user->service_status == -1) {
  222. //机器人客服
  223. $autoTask = Config::autoTask();
  224. $auto_cs_uid = !empty($autoTask['user_id']) ? $autoTask['user_id'] : 1;
  225. $user->service_status = 0;
  226. $user->service_start = time();
  227. $user->timeout_type = 0;
  228. $user->cs_uid = $auto_cs_uid;
  229. $user->save();
  230. $param = [
  231. 'id' => \utils\Str::getUuid(),
  232. 'type' => 'text',
  233. 'status' => 'going',
  234. 'sendTime' => time() * 1000,
  235. 'toContactId' => $user_id,
  236. 'content' => Config::getFieldValue('transfer_to_human'),
  237. 'file_id' => 0,
  238. 'is_group' => 0,
  239. 'user_id' => $auto_cs_uid,
  240. ];
  241. Message::sendMsg($param, 0);
  242. // //通知客服已接线
  243. // wsSendMsg(0,'handleChat',['user_id'=>$user_id]);
  244. }
  245. } catch (Exception $e) {
  246. return $this->error($e->getMessage());
  247. }
  248. return $this->success([]);
  249. }
  250. // 获取联系人列表
  251. public function getContacts()
  252. {
  253. $this->userInfo['cs_uid'] = User::where('user_id', $this->userInfo['user_id'])->value('cs_uid');
  254. $map = [['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]];
  255. // if ($this->userInfo['role'] != 0) {
  256. // $map[] = ['service_status', '<>', -1];
  257. // }
  258. $data = User::getUserList($this->userInfo, $map, $this->userInfo['user_id'] , '', $this->userInfo['role']);
  259. $count=Friend::where(['status'=>2,'friend_user_id'=>$this->uid])->count();
  260. $time=Friend::where(['friend_user_id'=>$this->uid,'is_invite'=>1])->order('create_time desc')->value('create_time');
  261. return success('', $data,$count,$time*1000);
  262. }
  263. // 获取聊天列表
  264. public function getChatList()
  265. {
  266. $data = User::getChatList($this->userInfo['user_id']);
  267. $count=Friend::where(['status'=>2,'friend_user_id'=>$this->uid])->count();
  268. $time=Friend::where(['friend_user_id'=>$this->uid,'is_invite'=>1])->order('create_time desc')->value('create_time');
  269. return success('', $data,$count,$time*1000);
  270. }
  271. // 获取好友列表
  272. public function getFriendList()
  273. {
  274. $data = User::getFriendList([['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]],$this->userInfo['user_id']);
  275. return success('', $data);
  276. }
  277. // 获取群聊列表
  278. public function getGroupList()
  279. {
  280. $data = User::getGroupList($this->userInfo['user_id']);
  281. return success('', $data);
  282. }
  283. // 获取单个人员的信息
  284. public function getContactInfo(){
  285. $id = $this->request->param('id');
  286. $is_group = is_string($id) ? 1 : 0;
  287. $user=new User;
  288. $data=$user->setContact($id,$is_group);
  289. if(!$data){
  290. return warning($user->getError());
  291. }
  292. return success('',$data);
  293. }
  294. //发送消息
  295. public function sendMessage()
  296. {
  297. $param = $this->request->param();
  298. $param['user_id'] = $this->userInfo['user_id'];
  299. $message=new Message();
  300. $data = $message->sendMessage($param,$this->globalConfig);
  301. if ($data) {
  302. return success('', $data);
  303. } else {
  304. return warning($message->getError());
  305. }
  306. }
  307. //转发消息
  308. public function forwardMessage()
  309. {
  310. $param = $this->request->param();
  311. $userIds=$param['user_ids'] ?? [];
  312. if(!$userIds || count($userIds)>5){
  313. return warning(lang('im.forwardLimit',['count'=>5]));
  314. }
  315. $msg_id=$param['msg_id'] ?? 0;
  316. $message=Message::find($msg_id);
  317. if(!$message){
  318. return warning(lang('im.exist'));
  319. }
  320. $msg=$message->toArray();
  321. $userInfo=$this->userInfo;
  322. queuePush([
  323. 'action'=>'forwardMessage',
  324. 'message'=>$msg,
  325. 'user_ids'=>$userIds,
  326. 'config'=>$this->globalConfig,
  327. 'userInfo'=>$userInfo
  328. ]);
  329. return success(lang('im.forwardOk'));
  330. }
  331. // 获取用户信息
  332. public function getUserInfo()
  333. {
  334. $user_id = $this->request->param('user_id');
  335. $group_id = $this->request->param('group_id');
  336. $groupInfo=[];
  337. if($group_id){
  338. $group_id = explode('-', $group_id)[1];
  339. $groupInfo=Group::where(['group_id'=>$group_id])->find();
  340. if($groupInfo){
  341. // 查询操作对象的角色
  342. $groupInfo['userInfo']=GroupUser::where(['user_id'=>$user_id,'group_id'=>$group_id])->find() ?: [];
  343. // 查询我的角色
  344. $groupInfo['manageRole']=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$group_id])->value('role') ?: 3;
  345. }
  346. }
  347. $user=User::find($user_id);
  348. if(!$user){
  349. return error(lang('user.exist'));
  350. }
  351. $user->avatar=avatarUrl($user->avatar,$user->realname,$user->user_id,120);
  352. // 账号前面截取3位,后面截取两位,中间星号展示
  353. $user->account=substr($user->account, 0, 3).'******'.substr($user->account, -2, 2);
  354. // 查询好友关系
  355. $friend=Friend::where(['friend_user_id'=>$user_id,'create_user'=>$this->userInfo['user_id'],'status'=>1])->find();
  356. $user->friend=$friend ? : '';
  357. $location='';
  358. if($user->last_login_ip){
  359. $location=implode(" ", \Ip::find($user->last_login_ip));
  360. }
  361. $user->location=$location;
  362. $user->groupInfo=$groupInfo ? : [];
  363. $user->password='';
  364. $userModel=new User;
  365. $user->contactInfo=$userModel->setContact($user_id,0) ?? [];
  366. return success('', $user);
  367. }
  368. // 扫码登录,向客户端推送数据
  369. public function tokenLogin(){
  370. $param = $this->request->param();
  371. $token=$param['token'] ?? '';
  372. $client_id='';
  373. if($token){
  374. $client_id=authcode(urldecode($token),"DECODE", config('app.app_id'));
  375. if(!$client_id){
  376. return warning(lang('user.loginError'));
  377. }
  378. }else{
  379. return warning(lang('user.loginError'));
  380. }
  381. $userInfo=$this->userInfo;
  382. if(!$userInfo){
  383. return warning(lang('user.loginError'));
  384. }
  385. // 如果用户已经有设置
  386. $setting=$userInfo['setting'] ?: '';
  387. if($setting){
  388. $setting['hideMessageName']= $setting['hideMessageName']=='true' ? true : false;
  389. $setting['hideMessageTime']= $setting['hideMessageTime']=='true' ? true : false;
  390. $setting['avatarCricle']= $setting['avatarCricle']=='true' ? true : false;
  391. $setting['isVoice']= $setting['isVoice']=='true' ? true : false;
  392. $setting['sendKey']=(int)$setting['sendKey'];
  393. }
  394. $userInfo['setting']=$setting;
  395. Gateway::$registerAddress = config('gateway.registerAddress');
  396. //如果登录信息中含有client——id则自动进行绑定
  397. if($client_id){
  398. $user_id=$userInfo['user_id'];
  399. // 如果当前ID在线,将其他地方登陆挤兑下线
  400. if(Gateway::isUidOnline($user_id)){
  401. wsSendMsg($user_id,'offline',['id'=>$user_id,'client_id'=>$client_id,'isMobile'=>false]);
  402. }
  403. Gateway::bindUid($client_id, $user_id);
  404. // 查询团队,如果有团队则加入团队
  405. $group=Group::getMyGroup(['gu.user_id'=>$user_id,'gu.status'=>1]);
  406. if($group){
  407. $group=$group->toArray();
  408. $group_ids=arrayToString($group,'group_id',false);
  409. foreach($group_ids as $v){
  410. Gateway::joinGroup($client_id, $v);
  411. }
  412. }
  413. }
  414. $update=[
  415. 'last_login_time'=>time(),
  416. 'last_login_ip'=>$this->request->ip(),
  417. 'login_count'=>Db::raw('login_count+1')
  418. ];
  419. User::where('user_id',$userInfo['user_id'])->update($update);
  420. $authToken=User::refreshToken($userInfo,'web');
  421. $data=[
  422. 'sessionId'=>Session::getId(),
  423. 'authToken'=>$authToken,
  424. 'userInfo'=>$userInfo
  425. ];
  426. Gateway::sendToClient($client_id, json_encode(array(
  427. 'type' => 'tokenLogin',
  428. 'data' => $data,
  429. )));
  430. return success(lang('user.loginOk'),$data);
  431. }
  432. // 搜索用户
  433. public function searchUser(){
  434. $keywords=$this->request->param('keywords','');
  435. if(!$keywords){
  436. return success('',[]);
  437. }
  438. $map=['status'=>1,'account'=>$keywords];
  439. $list=User::where($map)->field(User::$defaultField)->where([['account','<>',$this->userInfo['account']]])->select()->toArray();
  440. if($list){
  441. $ids=array_column($list,'user_id');
  442. $friendList=Friend::getFriend([['create_user','=',$this->uid],['friend_user_id','in',$ids]]);
  443. foreach($list as $k=>$v){
  444. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  445. $list[$k]['friend']=$friendList[$v['user_id']] ?? '';
  446. }
  447. }
  448. return success('', $list);
  449. }
  450. // 获取系统所有人员加搜索
  451. public function userList(){
  452. $keywords=$this->request->param('keywords','');
  453. $listRows=$this->request->param('limit',20);
  454. $page=$this->request->param('page',1);
  455. $map=['status'=>1];
  456. $field="user_id,realname,avatar";
  457. if(!$keywords){
  458. $list=User::where($map)->field($field)->order('user_id asc')->limit(20)->paginate(['list_rows'=>$listRows,'page'=>$page]);;
  459. if($list){
  460. $list=$list->toArray()['data'];
  461. }
  462. }else{
  463. $list=User::where($map)->field($field)->where([['account','<>',$this->userInfo['account']]])->whereLike('account|realname|name_py','%'.$keywords.'%')->select()->toArray();
  464. }
  465. if($list){
  466. foreach($list as $k=>$v){
  467. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  468. $list[$k]['id']=$v['user_id'];
  469. }
  470. }
  471. return success('', $list);
  472. }
  473. // 获取聊天记录
  474. public function getMessageList()
  475. {
  476. $param = $this->request->param();
  477. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  478. // 如果toContactId是数字,绝对是单聊
  479. $is_group = is_numeric($param['toContactId']) ? 0 : $is_group;
  480. // 设置当前聊天消息为已读
  481. $chat_identify = $this->setIsRead($is_group, $param['toContactId']);
  482. $type = isset($param['type']) ? $param['type'] : '';
  483. $is_at = isset($param['is_at']) ? $param['is_at'] : '';
  484. $map = ['chat_identify' => $chat_identify, 'status' => 1];
  485. $where = [];
  486. if ($type && $type != "all") {
  487. $map['type'] = $type;
  488. } else {
  489. if (isset($param['type'])) {
  490. $where[] = ['type', '<>', 'event'];
  491. }
  492. }
  493. $groupManage=[];
  494. // 群聊查询入群时间以后的消息
  495. if($is_group==1){
  496. $group_id = explode('-', $param['toContactId'])[1];
  497. $group=Group::where(['group_id'=> $group_id])->find();
  498. $groupManage=GroupUser::getGroupManage($group_id);
  499. if($group && $group['setting']){
  500. $groupSetting=json_decode($group['setting'],true);
  501. $history=$groupSetting['history'] ?? false;
  502. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  503. if(!$history){
  504. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  505. $where[] = ['create_time', '>=', $createTime ? : 0];
  506. }
  507. }
  508. }
  509. $keywords = isset($param['keywords']) ? $param['keywords'] : '';
  510. if ($keywords && in_array($type, ['text', 'all'])) {
  511. $where[] = ['content', 'like', '%' . $keywords . '%'];
  512. }
  513. // 如果是查询@数据
  514. if($is_at){
  515. $atList=Db::name('message')->where($map)->where($where)->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  516. if($atList){
  517. $data = $this->recombileMsg($atList,false);
  518. Message::setAtread($data,$this->userInfo['user_id']);
  519. return success('', $data, count($data));
  520. }else{
  521. return success('', [], 0);
  522. }
  523. }
  524. $listRows = $param['limit'] ?: 20;
  525. $pageSize = $param['page'] ?: 1;
  526. $last_id = $param['last_id'] ?? 0;
  527. if($last_id){
  528. $where[]=['msg_id','<',$last_id];
  529. $pageSize=1;
  530. }
  531. //判断是客服还是用户
  532. if ($this->userInfo['role'] == 0) {
  533. //用户可见历史记录的时长
  534. $hours = Config::where('field', 'user_show_message')->value('val');
  535. if ($hours > 0) {
  536. $start_time = time() - $hours * 60 * 60;
  537. $where[] = ['create_time', '>=', $start_time];
  538. }
  539. } elseif ($this->userInfo['role'] > 0) {
  540. //客服可见历史记录的时长
  541. $hours = Config::where('field', 'kefu_show_message')->value('val');
  542. if ($hours > 0) {
  543. $start_time = time() - $hours * 60 * 60;
  544. $where[] = ['create_time', '>=', $start_time];
  545. }
  546. $toUser = User::where('user_id', $param['toContactId'])->find();
  547. if ($toUser && $toUser->service_status == 1 && $toUser->cs_uid == $this->userInfo['user_id']) {
  548. //将用户待处理的状态更新成服务中
  549. $toUser->service_status = 2;
  550. $toUser->service_time = time();
  551. $toUser->save();
  552. //通知客服-会话服务中
  553. wsSendMsg(0,'handleChat',['user_id'=>$param['toContactId']]);
  554. } else {
  555. $map['chat_identify'] = $toUser->cs_uid.'-'.$param['toContactId'];
  556. }
  557. }
  558. $list = Message::getList($map, $where, 'msg_id desc', $listRows, $pageSize);
  559. $data = $this->recombileMsg($list,true,$groupManage);
  560. // 如果是群聊并且是第一页消息,需要推送@数据给用户
  561. if($param['is_group']==1 && $param['page']==1){
  562. $isPush=Cache::get('atMsgPush'.$chat_identify) ?? '';
  563. $atList=Db::name('message')->where(['chat_identify'=>$chat_identify,'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  564. $msgIda=array_column($atList,'msg_id');
  565. // 如果两次推送at数据的列表不一样,则推送
  566. if($isPush!=json_encode($msgIda)){
  567. $atData=$this->recombileMsg($atList,false);
  568. wsSendMsg($this->userInfo['user_id'],'atMsgList',[
  569. 'list'=>$atData,
  570. 'count'=>count($atData),
  571. 'toContactId'=>$param['toContactId']
  572. ]);
  573. Cache::set('atMsgPush'.$chat_identify,json_encode($msgIda),60);
  574. }
  575. }
  576. // 如果是消息管理器则不用倒序
  577. if (!isset($param['type'])) {
  578. $data = array_reverse($data);
  579. }
  580. return success('', $data, $list->total());
  581. }
  582. // 获取单条消息详情
  583. public function getMessageInfo()
  584. {
  585. $param = $this->request->param();
  586. $id = $param['msg_id'] ?? 0;
  587. $message = Message::where(['msg_id' => $id])->find();
  588. if ($message) {
  589. $data = $this->recombileMsg([$message], false);
  590. return success('', $data);
  591. } else {
  592. return warning(lang('im.exist'));
  593. }
  594. }
  595. // 获取单条消息上下文
  596. public function getMessageContext()
  597. {
  598. $param = $this->request->param();
  599. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  600. $id = $param['msg_id'] ?? 0;
  601. $direction = $param['direction'] ?? 0;
  602. $message = Message::where(['msg_id' => $id])->find();
  603. if (!$message) {
  604. return warning(lang('im.exist'));
  605. }
  606. $groupManage=[];
  607. $where = [];
  608. $map = ['chat_identify' => $message['chat_identify'], 'status' => 1];
  609. if($is_group==1 && $direction<2){
  610. $group_id = $message['to_user'];
  611. $group=Group::where(['group_id'=> $group_id])->find();
  612. $groupManage=GroupUser::getGroupManage($group_id);
  613. if($group && $group['setting']){
  614. $groupSetting=json_decode($group['setting'],true);
  615. $history=$groupSetting['history'] ?? false;
  616. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  617. if(!$history){
  618. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  619. $where[] = ['create_time', '>=', $createTime ? : 0];
  620. }
  621. }
  622. }
  623. if($direction==0){
  624. $where[] = ['msg_id', '<', $id];
  625. $beforeList = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  626. $beforeList = array_reverse($beforeList);
  627. $where2 = [];
  628. $where2[] = ['msg_id', '>=', $id];
  629. $afterList = Message::where($map)->where($where2)->order('msg_id asc')->limit(5)->select()->toArray();
  630. $data = array_merge($beforeList, $afterList);
  631. }elseif($direction==1){
  632. $where[] = ['msg_id', '<', $id];
  633. $data = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  634. $data = array_reverse($data);
  635. }else{
  636. $where[] = ['msg_id', '>', $id];
  637. $data = Message::where($map)->where($where)->order('msg_id asc')->limit(5)->select()->toArray();
  638. }
  639. if($data){
  640. $data = $this->recombileMsg($data, false,$groupManage);
  641. }
  642. return success('', $data);
  643. }
  644. protected function recombileMsg($list,$isPagination=true,$manage=[])
  645. {
  646. $data = [];
  647. $userInfo = $this->userInfo;
  648. if ($list) {
  649. $listData = $isPagination ? $list->toArray()['data'] : $list;
  650. $userList = User::matchUser($listData, true, 'from_user', 120);
  651. foreach ($listData as $k => $v) {
  652. // 屏蔽已删除的消息
  653. if ($v['del_user']) {
  654. $delUser = explode(',', $v['del_user']);
  655. if (in_array($userInfo['user_id'], $delUser)) {
  656. unset($list[$k]);
  657. continue;
  658. // $v['type']="event";
  659. // $v['content']="删除了一条消息";
  660. }
  661. }
  662. $content = str_encipher($v['content'],false);
  663. $preview = '';
  664. $ext='';
  665. if (in_array($v['type'], $this->fileType)) {
  666. $content = getFileUrl($content);
  667. $preview = previewUrl($content);
  668. $ext=getExtUrl($content);
  669. }
  670. $fromUser = $userList[$v['from_user']];
  671. // 处理撤回的消息
  672. if ($v['type'] == "event" && $v['is_undo']==1) {
  673. if ($v['from_user'] == $userInfo['user_id']) {
  674. $content = lang('im.you'). $content;
  675. } elseif ($v['is_group'] == 1) {
  676. $content = $fromUser['realname'] . $content;
  677. } else {
  678. $content = lang('im.other') . $content;
  679. }
  680. }
  681. $toContactId=$v['is_group'] ==1 ? 'group-'.$v['to_user'] : $v['to_user'];
  682. $atList=($v['at'] ?? null) ? explode(',',$v['at']): [];
  683. $role=$manage[$v['from_user']] ?? 3;
  684. $data[] = [
  685. 'msg_id' => $v['msg_id'],
  686. 'id' => $v['id'],
  687. 'status' => "succeed",
  688. 'type' => $v['type'],
  689. 'sendTime' => (is_string($v['create_time']) ? strtotime($v['create_time']) : $v['create_time'])* 1000,
  690. 'content' => $content,
  691. 'preview' => $preview,
  692. 'download' => $v['file_id'] ? getMainHost().'/filedown/'.encryptIds($v['file_id']) : '',
  693. 'is_read' => $v['is_read'],
  694. 'is_group' => $v['is_group'],
  695. 'at' => $atList,
  696. 'toContactId' => $toContactId,
  697. 'from_user' => $v['from_user'],
  698. 'file_id' => $v['file_id'],
  699. 'file_cate' => $v['file_cate'],
  700. 'fileName' => $v['file_name'],
  701. 'fileSize' => $v['file_size'],
  702. 'is_click' => $v['is_click'],
  703. 'fromUser' => $fromUser,
  704. 'extUrl'=>$ext,
  705. 'role'=>$role,
  706. 'extends'=>is_string($v['extends'])?json_decode($v['extends'],true) : $v['extends']
  707. ];
  708. }
  709. }
  710. return $data;
  711. }
  712. // 设置当前窗口的消息默认为已读
  713. public function setMsgIsRead()
  714. {
  715. $param = $this->request->param();
  716. // 判断是否是一个二维数组
  717. if (is_array($param['messages'][0] ?? '')) {
  718. $messages=$param['messages'];
  719. } else {
  720. $messages=[$param['messages']];
  721. }
  722. $this->setIsRead($param['is_group'], $param['toContactId'],$messages);
  723. if (!$param['is_group']) {
  724. wsSendMsg($param['fromUser'], 'isRead', $messages, 0);
  725. }
  726. return success('');
  727. }
  728. // 设置全部为已读
  729. public function readAllMsg()
  730. {
  731. // 阅读所有单聊
  732. $map = ['to_user' => $this->userInfo['user_id'], 'is_read' => 0, 'is_group' => 0];
  733. Message::where($map)->update(['is_read' => 1]);
  734. // 阅读所有群聊
  735. GroupUser::where(['user_id' => $this->userInfo['user_id'], 'status' => 1])->update(['unread'=>0]);
  736. return success('');
  737. }
  738. // 设置消息已读
  739. protected function setIsRead($is_group, $to_user,$messages=[])
  740. {
  741. if ($is_group==1) {
  742. $chat_identify = $to_user;
  743. } else if($is_group==0) {
  744. $chat_identify = chat_identify($this->userInfo['user_id'], $to_user);
  745. } else if($is_group==2){
  746. $chat_identify = $to_user;
  747. }
  748. $data=[
  749. 'action'=>'setIsRead',
  750. 'is_group'=>$is_group,
  751. 'to_user'=>$to_user,
  752. 'messages'=>$messages,
  753. 'user_id'=>$this->userInfo['user_id']
  754. ];
  755. queuePush($data,3);
  756. return $chat_identify;
  757. }
  758. // 聊天设置
  759. public function setting()
  760. {
  761. $param = $this->request->param();
  762. if ($param) {
  763. User::where(['user_id' => $this->userInfo['user_id']])->update(['setting' => $param]);
  764. return success('');
  765. }
  766. return warning('');
  767. }
  768. // 撤回消息
  769. public function undoMessage()
  770. {
  771. // echo Lang::getLangSet();
  772. // echo \think\facade\Lang::get('ok');
  773. // echo \think\facade\Lang::get('im.other');
  774. // die;
  775. // Lang::clear();
  776. // $setRes = Lang::setLangSet('en');
  777. // dump('设置语言是否成功:', $setRes); // 应返回 true
  778. // dump('当前语言标识:', Lang::getLangSet()); // 应返回 en
  779. // dump('已加载的语言文件:', Lang::getLoadFiles()); // 应包含 en.php 路径
  780. // dump('im.other 值:', Lang::get('im.other')); // 看实际返回值
  781. // die;
  782. $param = $this->request->param();
  783. $id = $param['id'];
  784. $message = Message::where(['id' => $id])->find();
  785. if ($message) {
  786. // 如果时间超过了2分钟也不能撤回
  787. $createTime=is_string($message['create_time']) ? strtotime($message['create_time']) : $message['create_time'];
  788. $redoTime=$this->globalConfig['chatInfo']['redoTime'] ?? 120;
  789. if ($this->userInfo['role'] == 0 && $this->globalConfig['user_cancel_message'] && $this->globalConfig['user_cancel_message']) {
  790. $redoTime=$this->globalConfig['user_cancel_message_time'] * 60;
  791. } elseif ($this->userInfo['role'] != 0 && $this->globalConfig['kefu_cancel_message']) {
  792. $redoTime=$this->globalConfig['kefu_cancel_message'] * 60;
  793. }
  794. if(time()-$createTime>$redoTime && $message['is_group']==0){
  795. return warning(lang('im.redoLimitTime',['time'=>floor($redoTime/60)]));
  796. }
  797. $text = lang('im.redo');
  798. $fromUserName = lang('im.other');
  799. $toContactId = $message['to_user'];
  800. if ($message['is_group'] == 1) {
  801. $fromUserName = $this->userInfo['realname'];
  802. $toContactId = explode('-', $message['chat_identify'])[1];
  803. // 如果是群聊消息撤回,需要判断是否是群主或者管理员,如果是则可以撤回
  804. if($message['from_user']!=$this->userInfo['user_id']){
  805. $groupUser=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$toContactId])->find();
  806. if(!$groupUser || !in_array($groupUser['role'],[1,2])){
  807. return warning(lang('system.notAuth'));
  808. }
  809. $text=lang('im.manageRedo');
  810. }
  811. }
  812. $message->content = str_encipher($text);
  813. $message->type = 'event';
  814. $message->is_undo = 1;
  815. //@的数据清空
  816. $message->at = '';
  817. $message->save();
  818. $info = $message->toArray();
  819. // $data = $info;
  820. $data['content'] = $fromUserName . $text;
  821. $data['sendTime'] = $createTime * 1000;
  822. $data['id'] = $info['id'];
  823. $data['from_user'] = $info['from_user'];
  824. $data['msg_id'] = $info['msg_id'];
  825. $data['status'] = $info['status'];
  826. $data['type'] = 'event';
  827. $data['is_last'] = $info['is_last'];
  828. $data['toContactId'] = $message['is_group'] == 1 ? $info['chat_identify'] : $toContactId;
  829. $data['isMobile'] = $this->request->isMobile() ? 1 : 0;
  830. wsSendMsg($toContactId, 'undoMessage', $data, $info['is_group']);
  831. if($info['is_group']==0){
  832. // 给自己也发一份推送,多端同步
  833. $data['content'] =lang('im.you'). $text;
  834. wsSendMsg($this->userInfo['user_id'], 'undoMessage', $data, $info['is_group']);
  835. }
  836. return success('');
  837. } else {
  838. return warning();
  839. }
  840. }
  841. // 删除消息
  842. public function removeMessage()
  843. {
  844. $param = $this->request->param();
  845. $id = $param['id'];
  846. $map = ['id' => $id];
  847. $message = Message::where($map)->find();
  848. if ($message) {
  849. $message->del_user = $this->userInfo['user_id'];
  850. if ($message['is_group'] == 1) {
  851. if ($message['del_user']) {
  852. $message->del_user .= ',' . $this->userInfo['user_id'];
  853. }
  854. } else {
  855. if ($message['del_user'] > 0) {
  856. $message->where($map)->delete();
  857. return success(lang('system.delOk'));
  858. }
  859. }
  860. $message->save();
  861. return success('');
  862. } else {
  863. return warning('');
  864. }
  865. }
  866. // 消息免打扰
  867. public function isNotice()
  868. {
  869. $param = $this->request->param();
  870. $user_id = $this->userInfo['user_id'];
  871. $id = $param['id'];
  872. if ($param['is_group'] == 1) {
  873. $group_id = explode('-', $param['id'])[1];
  874. GroupUser::update(['is_notice' => $param['is_notice']], ['user_id' => $user_id, 'group_id' => $group_id]);
  875. } else {
  876. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  877. $friend = Friend::where($map)->find();
  878. try {
  879. if ($friend) {
  880. $friend->is_notice = $param['is_notice'];
  881. $friend->save();
  882. } else {
  883. $info = [
  884. 'create_user' => $user_id,
  885. 'friend_user_id' => $id,
  886. 'is_notice' => $param['is_notice']
  887. ];
  888. Friend::create($info);
  889. }
  890. return success('');
  891. } catch (Exception $e) {
  892. return error($e->getMessage());
  893. }
  894. }
  895. wsSendMsg($user_id,"setIsNotice",['id'=>$id,'is_notice'=>$param['is_notice'],'is_group'=>$param['is_group']]);
  896. return success('');
  897. }
  898. // 设置聊天置顶
  899. public function setChatTop()
  900. {
  901. $param = $this->request->param();
  902. $user_id = $this->userInfo['user_id'];
  903. $is_group = $param['is_group'] ?: 0;
  904. $id = $param['id'];
  905. try {
  906. if ($is_group == 1) {
  907. $group_id = explode('-', $param['id'])[1];
  908. GroupUser::update(['is_top' => $param['is_top']], ['user_id' => $user_id, 'group_id' => $group_id]);
  909. } else {
  910. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  911. $friend = Friend::where($map)->find();
  912. if ($friend) {
  913. $friend->is_top = $param['is_top'];
  914. $friend->save();
  915. } else {
  916. $info = [
  917. 'create_user' => $user_id,
  918. 'friend_user_id' => $id,
  919. 'is_top' => $param['is_top']
  920. ];
  921. Friend::create($info);
  922. }
  923. }
  924. wsSendMsg($user_id,"setChatTop",['id'=>$id,'is_top'=>$param['is_top'],'is_group'=>$is_group]);
  925. return success('');
  926. } catch (Exception $e) {
  927. return error($e->getMessage());
  928. }
  929. }
  930. // 删除聊天
  931. public function delChat()
  932. {
  933. $param = $this->request->param();
  934. $user_id = $this->userInfo['user_id'];
  935. $is_group = $param['is_group'] ?: 0;
  936. $id = $param['id'];
  937. $data=[
  938. 'user_id'=>$user_id,
  939. 'is_group'=>$is_group,
  940. 'to_user'=>$id
  941. ];
  942. ChatDelog::create($data);
  943. ChatDelog::updateCache($user_id);
  944. return success('');
  945. }
  946. // 向用户发送消息
  947. public function sendToMsg(){
  948. $param=$this->request->param();
  949. $toContactId=$param['toContactId'];
  950. $type=$param['type'];
  951. $status=$param['status'];
  952. $event=$param['event'] ?? 'calling';
  953. if($event=='calling'){
  954. $status=3;
  955. }
  956. $sdp=$param['sdp'] ?? '';
  957. $iceCandidate=$param['iceCandidate'] ?? '';
  958. $callTime=$param['callTime'] ?? '';
  959. $msg_id=$param['msg_id'] ?? '';
  960. $id=$param['id'] ?? '';
  961. $code=($param['code'] ?? '') ?: 901;
  962. // 如果该用户不在线,则发送忙线
  963. Gateway::$registerAddress = config('gateway.registerAddress');
  964. if(!Gateway::isUidOnline($toContactId)){
  965. $toContactId=$this->userInfo['user_id'];
  966. $code=907;
  967. $event='busy';
  968. sleep(1);
  969. }
  970. switch($code){
  971. case 902:
  972. $content=lang('webRtc.cancel');
  973. break;
  974. case 903:
  975. $content=lang('webRtc.refuse');
  976. break;
  977. case 905:
  978. $content=lang('webRtc.notConnected');
  979. break;
  980. case 906:
  981. $content=lang('webRtc.duration',['time'=>date("i:s",$callTime)]);
  982. break;
  983. case 907:
  984. $content=lang('webRtc.busy');
  985. break;
  986. case 908:
  987. $content=lang('webRtc.other');
  988. break;
  989. default:
  990. $content=$type==1 ?lang('webRtc.video') : lang('webRtc.audio');
  991. break;
  992. }
  993. switch($event){
  994. case 'calling':
  995. $content=$type==1 ?lang('webRtc.video'): lang('webRtc.audio');
  996. break;
  997. case 'acceptRtc':
  998. $content=lang('webRtc.answer');
  999. break;
  1000. case 'iceCandidate':
  1001. $content=lang('webRtc.exchange');
  1002. break;
  1003. }
  1004. $userInfo=$this->userInfo;
  1005. $userInfo['id']=$userInfo['user_id'];
  1006. $user = new User();
  1007. $data=[
  1008. 'id'=>$id,
  1009. 'msg_id'=>$msg_id,
  1010. 'sendTime'=>time()*1000,
  1011. 'toContactId'=>$toContactId,
  1012. 'content'=>$content,
  1013. 'type'=>'webrtc',
  1014. 'status'=>'succeed',
  1015. 'is_group'=>0,
  1016. 'is_read'=>0,
  1017. 'fromUser'=>$userInfo,
  1018. 'at'=>[],
  1019. 'extends'=>[
  1020. 'type'=>$type, //通话类型,1视频,0语音。
  1021. 'status'=>$status, //,1拨打方,2接听方
  1022. 'event'=>$event,
  1023. 'callTime'=>$callTime,
  1024. 'sdp'=>$sdp,
  1025. 'code'=>$code, //通话状态:呼叫901,取消902,拒绝903,接听904,未接通905,接通后挂断906,忙线907,其他端操作908
  1026. 'iceCandidate'=>$iceCandidate,
  1027. 'isMobile'=>$this->request->isMobile() ? 1 : 0,
  1028. ]
  1029. ];
  1030. if($event=='calling'){
  1031. $chat_identify=chat_identify($userInfo['id'],$toContactId);
  1032. $msg=[
  1033. 'from_user'=>$userInfo['id'],
  1034. 'to_user'=>$toContactId,
  1035. 'id'=>$id,
  1036. 'content'=>str_encipher($content),
  1037. 'chat_identify'=>$chat_identify,
  1038. 'create_time'=>time(),
  1039. 'type'=>$data['type'],
  1040. 'is_group'=>0,
  1041. 'is_read'=>0,
  1042. 'extends'=>$data['extends'],
  1043. ];
  1044. $message=new Message();
  1045. $message->update(['is_last'=>0],['chat_identify'=>$chat_identify]);
  1046. $message->save($msg);
  1047. $msg_id=$message->msg_id;
  1048. $data['msg_id']=$msg_id;
  1049. // 将接收人设置为发送人才能定位到该消息
  1050. $data['toContactId']=$userInfo['id'];
  1051. $data['toUser']=$toContactId;
  1052. }elseif($event=='hangup'){
  1053. $message=Message::where(['id'=>$id])->find();
  1054. if(!$message){
  1055. return error(lang('webRtc.fail'));
  1056. }
  1057. if($message){
  1058. $message->content=str_encipher($content);
  1059. $extends=$message->extends;
  1060. $extends['code']=$code;
  1061. $extends['callTime']=$callTime;
  1062. $message->extends=$extends;
  1063. $message->save();
  1064. }
  1065. }
  1066. wsSendMsg($toContactId,'webrtc',$data);
  1067. $wsData=$data;
  1068. if(in_array($event,['calling','acceptRtc','hangup'])){
  1069. if(in_array($event,['acceptRtc','hangup'])){
  1070. $data['extends']['event']='otherOpt'; //其他端操作
  1071. }
  1072. $data['toContactId']=$toContactId;
  1073. $data['contactInfo']=$user->setContact($toContactId,0,'webrtc',$content) ? : [];
  1074. wsSendMsg($userInfo['id'],'webrtc',$data);
  1075. }
  1076. return success('',$wsData);
  1077. }
  1078. // 修改密码
  1079. public function editPassword()
  1080. {
  1081. if(env('app.demon_mode',false)){
  1082. return warning(lang('system.demoMode'));
  1083. }
  1084. $user_id = $this->userInfo['user_id'];
  1085. $user=User::find($user_id);
  1086. if(!$user){
  1087. return warning(lang('user.exist'));
  1088. }
  1089. $account=$user->account;
  1090. $code=$this->request->param('code','');
  1091. $originalPassword = $this->request->param('originalPassword', '');
  1092. if($code){
  1093. if(Cache::get($account)!=$code){
  1094. return warning(lang('user.codeErr'));
  1095. }
  1096. }elseif($originalPassword){
  1097. if(password_hash_tp($originalPassword,$user->salt)!= $user->password){
  1098. return warning(lang('user.passErr'));
  1099. }
  1100. }else{
  1101. return warning(lang('system.parameterError'));
  1102. }
  1103. try{
  1104. $password = $this->request->param('password','');
  1105. if($password){
  1106. $salt=$user->salt;
  1107. $user->password= password_hash_tp($password,$salt);
  1108. }
  1109. $user->save();
  1110. return success(lang('system.editOk'));
  1111. }catch (\Exception $e){
  1112. return error(lang('system.editFail'));
  1113. }
  1114. }
  1115. // 修改用户信息
  1116. public function updateUserInfo(){
  1117. try{
  1118. $data = $this->request->param();
  1119. $user=User::find($this->uid);
  1120. if(!$user){
  1121. return warning(lang('user.exist'));
  1122. }
  1123. // 接入用户名检测服务
  1124. event('GreenText',['content'=>$data['realname'],'service'=>"nickname_detection"]);
  1125. // 个性签名检测服务
  1126. event('GreenText',['content'=>$data['motto'],'service'=>"comment_detection"]);
  1127. $user->realname =$data['realname'];
  1128. $user->email =$data['email'];
  1129. $user->motto=$data['motto'];
  1130. $user->sex =$data['sex'];
  1131. $user->name_py= pinyin_sentence($data['realname']);
  1132. $user->save();
  1133. return success(lang('system.editOk'), $data);
  1134. }catch (\Exception $e){
  1135. return error($e->getMessage());
  1136. }
  1137. }
  1138. // 修改账户
  1139. public function editAccount(){
  1140. if(env('app.demon_mode',false)){
  1141. return warning(lang('system.demoMode'));
  1142. }
  1143. $code=$this->request->param('code','');
  1144. $newCode=$this->request->param('newCode','');
  1145. $account=$this->request->param('account','');
  1146. $isUser=User::where('account',$account)->find();
  1147. if($isUser){
  1148. return warning(lang('user.already'));
  1149. }
  1150. $user=User::find($this->uid);
  1151. if(!$user){
  1152. return warning(lang('user.exist'));
  1153. }
  1154. // 如果已经认证过了,则需要验证验证码
  1155. if($user->is_auth){
  1156. if(Cache::get($user->account)!=$code){
  1157. return warning(lang('user.codeErr'));
  1158. }
  1159. }
  1160. if(Cache::get($account)!=$newCode){
  1161. return warning(lang('user.newCodeErr'));
  1162. }
  1163. try{
  1164. $user->account=$account;
  1165. $user->is_auth=1;
  1166. $user->save();
  1167. return success(lang('system.editOk'));
  1168. }catch (\Exception $e){
  1169. return error(lang('system.editFail'));
  1170. }
  1171. }
  1172. // 阅读@消息
  1173. public function readAtMsg(){
  1174. $param = $this->request->param();
  1175. $atList=Db::name('message')->where(['chat_identify'=>$param['toContactId'],'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select();
  1176. $atData=$this->recombileMsg($atList,false);
  1177. Message::setAtRead($atData,$this->userInfo['user_id']);
  1178. // $message=Message::where('msg_id',$param['msg_id'])->select();
  1179. // $atList=($message ?? null) ? explode(',',$message): [];
  1180. // // 两个数组取差集
  1181. // $newAtList = array_diff($atList, [$this->userInfo['user_id']]);
  1182. // Message::where('msg_id',$param['msg_id'])->update(['at'=>implode(',',$newAtList)]);
  1183. return success('');
  1184. }
  1185. // 获取系统公告
  1186. public function getAdminNotice(){
  1187. $data=Message::where(['chat_identify'=>'admin_notice'])->order('msg_id desc')->find();
  1188. $extends=$data['extends'] ?? [];
  1189. if(!$extends){
  1190. $extends['title']='';
  1191. }
  1192. $createTime=$data['create_time'] ?? 0;
  1193. if(!$createTime){
  1194. $extends['create_time']=$createTime;
  1195. }else{
  1196. $extends['create_time']=is_string($data['create_time']) ? strtotime($data['create_time']) : $data['create_time'];
  1197. }
  1198. return success('',$extends);
  1199. }
  1200. // 双向删除消息
  1201. public function delMessage(){
  1202. $param = $this->request->param();
  1203. $id = $param['id'];
  1204. if(!$this->globalConfig['chatInfo']['dbDelMsg']){
  1205. return warning(lang('system.notAuth'));
  1206. }
  1207. $message = Message::where(['id' => $id])->find();
  1208. if ($message) {
  1209. if($message['from_user']!=$this->userInfo['user_id']){
  1210. return warning(lang('system.notAuth'));
  1211. }
  1212. Message::where(['id' => $id])->delete();
  1213. // 如果是最后一条消息,需要将上一条设置为最后一条
  1214. if($message['is_last']){
  1215. Message::where(['chat_identify'=>$message['chat_identify']])->order('msg_id desc')->limit(1)->update(['is_last'=>1]);
  1216. }
  1217. $toContactId = $message['to_user'];
  1218. if ($message['is_group'] == 1) {
  1219. $toContactId = explode('-', $message['chat_identify'])[1];
  1220. }
  1221. wsSendMsg($toContactId, 'delMessage', $message, $message['is_group']);
  1222. return success('');
  1223. } else {
  1224. return warning(lang('im.exist'));
  1225. }
  1226. }
  1227. }