Im.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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', $this->lang),
  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. $param['language_code'] = $this->lang;
  300. if ($this->userInfo['role'] != 0 && $param['type'] == 'text') {
  301. //客服或管理员给用户发送消息,需要按照用户的语言做翻译
  302. $toContactId = $param['to_contact_id'];
  303. $toUser = User::where('user_id', $toContactId)->field(['role', 'language_code'])->find();
  304. if ($toUser && $toUser['role'] == 0 && $toUser['language_code']) {
  305. //谷歌翻译
  306. $param['translate_content'] = google_translate($param['content'], $toUser['language_code']);
  307. $param['language_code'] = $toUser['language_code'];
  308. }
  309. }
  310. $param['language_code'] = $this->lang;
  311. $message=new Message();
  312. $data = $message->sendMessage($param,$this->globalConfig);
  313. if ($data) {
  314. return success('', $data);
  315. } else {
  316. return warning($message->getError());
  317. }
  318. }
  319. //转发消息
  320. public function forwardMessage()
  321. {
  322. $param = $this->request->param();
  323. $userIds=$param['user_ids'] ?? [];
  324. if(!$userIds || count($userIds)>5){
  325. return warning(lang('im.forwardLimit',['count'=>5]));
  326. }
  327. $msg_id=$param['msg_id'] ?? 0;
  328. $message=Message::find($msg_id);
  329. if(!$message){
  330. return warning(lang('im.exist'));
  331. }
  332. $msg=$message->toArray();
  333. $userInfo=$this->userInfo;
  334. queuePush([
  335. 'action'=>'forwardMessage',
  336. 'message'=>$msg,
  337. 'user_ids'=>$userIds,
  338. 'config'=>$this->globalConfig,
  339. 'userInfo'=>$userInfo
  340. ]);
  341. return success(lang('im.forwardOk'));
  342. }
  343. // 获取用户信息
  344. public function getUserInfo()
  345. {
  346. $user_id = $this->request->param('user_id');
  347. $group_id = $this->request->param('group_id');
  348. $groupInfo=[];
  349. if($group_id){
  350. $group_id = explode('-', $group_id)[1];
  351. $groupInfo=Group::where(['group_id'=>$group_id])->find();
  352. if($groupInfo){
  353. // 查询操作对象的角色
  354. $groupInfo['userInfo']=GroupUser::where(['user_id'=>$user_id,'group_id'=>$group_id])->find() ?: [];
  355. // 查询我的角色
  356. $groupInfo['manageRole']=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$group_id])->value('role') ?: 3;
  357. }
  358. }
  359. $user=User::find($user_id);
  360. if(!$user){
  361. return error(lang('user.exist'));
  362. }
  363. $user->avatar=avatarUrl($user->avatar,$user->realname,$user->user_id,120);
  364. // 账号前面截取3位,后面截取两位,中间星号展示
  365. $user->account=substr($user->account, 0, 3).'******'.substr($user->account, -2, 2);
  366. // 查询好友关系
  367. $friend=Friend::where(['friend_user_id'=>$user_id,'create_user'=>$this->userInfo['user_id'],'status'=>1])->find();
  368. $user->friend=$friend ? : '';
  369. $location='';
  370. if($user->last_login_ip){
  371. $location=implode(" ", \Ip::find($user->last_login_ip));
  372. }
  373. $user->location=$location;
  374. $user->groupInfo=$groupInfo ? : [];
  375. $user->password='';
  376. $userModel=new User;
  377. $user->contactInfo=$userModel->setContact($user_id,0) ?? [];
  378. return success('', $user);
  379. }
  380. // 扫码登录,向客户端推送数据
  381. public function tokenLogin(){
  382. $param = $this->request->param();
  383. $token=$param['token'] ?? '';
  384. $client_id='';
  385. if($token){
  386. $client_id=authcode(urldecode($token),"DECODE", config('app.app_id'));
  387. if(!$client_id){
  388. return warning(lang('user.loginError'));
  389. }
  390. }else{
  391. return warning(lang('user.loginError'));
  392. }
  393. $userInfo=$this->userInfo;
  394. if(!$userInfo){
  395. return warning(lang('user.loginError'));
  396. }
  397. // 如果用户已经有设置
  398. $setting=$userInfo['setting'] ?: '';
  399. if($setting){
  400. $setting['hideMessageName']= $setting['hideMessageName']=='true' ? true : false;
  401. $setting['hideMessageTime']= $setting['hideMessageTime']=='true' ? true : false;
  402. $setting['avatarCricle']= $setting['avatarCricle']=='true' ? true : false;
  403. $setting['isVoice']= $setting['isVoice']=='true' ? true : false;
  404. $setting['sendKey']=(int)$setting['sendKey'];
  405. }
  406. $userInfo['setting']=$setting;
  407. Gateway::$registerAddress = config('gateway.registerAddress');
  408. //如果登录信息中含有client——id则自动进行绑定
  409. if($client_id){
  410. $user_id=$userInfo['user_id'];
  411. // 如果当前ID在线,将其他地方登陆挤兑下线
  412. if(Gateway::isUidOnline($user_id)){
  413. wsSendMsg($user_id,'offline',['id'=>$user_id,'client_id'=>$client_id,'isMobile'=>false]);
  414. }
  415. Gateway::bindUid($client_id, $user_id);
  416. // 查询团队,如果有团队则加入团队
  417. $group=Group::getMyGroup(['gu.user_id'=>$user_id,'gu.status'=>1]);
  418. if($group){
  419. $group=$group->toArray();
  420. $group_ids=arrayToString($group,'group_id',false);
  421. foreach($group_ids as $v){
  422. Gateway::joinGroup($client_id, $v);
  423. }
  424. }
  425. }
  426. $update=[
  427. 'last_login_time'=>time(),
  428. 'last_login_ip'=>$this->request->ip(),
  429. 'login_count'=>Db::raw('login_count+1')
  430. ];
  431. User::where('user_id',$userInfo['user_id'])->update($update);
  432. $authToken=User::refreshToken($userInfo,'web');
  433. $data=[
  434. 'sessionId'=>Session::getId(),
  435. 'authToken'=>$authToken,
  436. 'userInfo'=>$userInfo
  437. ];
  438. Gateway::sendToClient($client_id, json_encode(array(
  439. 'type' => 'tokenLogin',
  440. 'data' => $data,
  441. )));
  442. return success(lang('user.loginOk'),$data);
  443. }
  444. // 搜索用户
  445. public function searchUser(){
  446. $keywords=$this->request->param('keywords','');
  447. if(!$keywords){
  448. return success('',[]);
  449. }
  450. $map=['status'=>1,'account'=>$keywords];
  451. $list=User::where($map)->field(User::$defaultField)->where([['account','<>',$this->userInfo['account']]])->select()->toArray();
  452. if($list){
  453. $ids=array_column($list,'user_id');
  454. $friendList=Friend::getFriend([['create_user','=',$this->uid],['friend_user_id','in',$ids]]);
  455. foreach($list as $k=>$v){
  456. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  457. $list[$k]['friend']=$friendList[$v['user_id']] ?? '';
  458. }
  459. }
  460. return success('', $list);
  461. }
  462. // 获取系统所有人员加搜索
  463. public function userList(){
  464. $keywords=$this->request->param('keywords','');
  465. $listRows=$this->request->param('limit',20);
  466. $page=$this->request->param('page',1);
  467. $map=['status'=>1];
  468. $field="user_id,realname,avatar";
  469. if(!$keywords){
  470. $list=User::where($map)->field($field)->order('user_id asc')->limit(20)->paginate(['list_rows'=>$listRows,'page'=>$page]);;
  471. if($list){
  472. $list=$list->toArray()['data'];
  473. }
  474. }else{
  475. $list=User::where($map)->field($field)->where([['account','<>',$this->userInfo['account']]])->whereLike('account|realname|name_py','%'.$keywords.'%')->select()->toArray();
  476. }
  477. if($list){
  478. foreach($list as $k=>$v){
  479. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  480. $list[$k]['id']=$v['user_id'];
  481. }
  482. }
  483. return success('', $list);
  484. }
  485. // 获取聊天记录
  486. public function getMessageList()
  487. {
  488. $param = $this->request->param();
  489. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  490. // 如果toContactId是数字,绝对是单聊
  491. $is_group = is_numeric($param['toContactId']) ? 0 : $is_group;
  492. // 设置当前聊天消息为已读
  493. $chat_identify = $this->setIsRead($is_group, $param['toContactId']);
  494. $type = isset($param['type']) ? $param['type'] : '';
  495. $is_at = isset($param['is_at']) ? $param['is_at'] : '';
  496. $map = ['chat_identify' => $chat_identify, 'status' => 1];
  497. $where = [];
  498. if ($type && $type != "all") {
  499. $map['type'] = $type;
  500. } else {
  501. if (isset($param['type'])) {
  502. $where[] = ['type', '<>', 'event'];
  503. }
  504. }
  505. $groupManage=[];
  506. // 群聊查询入群时间以后的消息
  507. if($is_group==1){
  508. $group_id = explode('-', $param['toContactId'])[1];
  509. $group=Group::where(['group_id'=> $group_id])->find();
  510. $groupManage=GroupUser::getGroupManage($group_id);
  511. if($group && $group['setting']){
  512. $groupSetting=json_decode($group['setting'],true);
  513. $history=$groupSetting['history'] ?? false;
  514. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  515. if(!$history){
  516. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  517. $where[] = ['create_time', '>=', $createTime ? : 0];
  518. }
  519. }
  520. }
  521. $keywords = isset($param['keywords']) ? $param['keywords'] : '';
  522. if ($keywords && in_array($type, ['text', 'all'])) {
  523. $where[] = ['content', 'like', '%' . $keywords . '%'];
  524. }
  525. // 如果是查询@数据
  526. if($is_at){
  527. $atList=Db::name('message')->where($map)->where($where)->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  528. if($atList){
  529. $data = $this->recombileMsg($atList,false);
  530. Message::setAtread($data,$this->userInfo['user_id']);
  531. return success('', $data, count($data));
  532. }else{
  533. return success('', [], 0);
  534. }
  535. }
  536. $listRows = $param['limit'] ?: 20;
  537. $pageSize = $param['page'] ?: 1;
  538. $last_id = $param['last_id'] ?? 0;
  539. if($last_id){
  540. $where[]=['msg_id','<',$last_id];
  541. $pageSize=1;
  542. }
  543. //判断是客服还是用户
  544. if ($this->userInfo['role'] == 0) {
  545. //用户可见历史记录的时长
  546. $hours = Config::where('field', 'user_show_message')->value('val');
  547. if ($hours > 0) {
  548. $start_time = time() - $hours * 60 * 60;
  549. $where[] = ['create_time', '>=', $start_time];
  550. }
  551. } elseif ($this->userInfo['role'] > 0) {
  552. //客服可见历史记录的时长
  553. $hours = Config::where('field', 'kefu_show_message')->value('val');
  554. if ($hours > 0) {
  555. $start_time = time() - $hours * 60 * 60;
  556. $where[] = ['create_time', '>=', $start_time];
  557. }
  558. $toUser = User::where('user_id', $param['toContactId'])->find();
  559. if ($toUser && $toUser->service_status == 1 && $toUser->cs_uid == $this->userInfo['user_id']) {
  560. //将用户待处理的状态更新成服务中
  561. $toUser->service_status = 2;
  562. $toUser->service_time = time();
  563. $toUser->save();
  564. //通知客服-会话服务中
  565. wsSendMsg(0,'handleChat',['user_id'=>$param['toContactId']]);
  566. } else {
  567. $map['chat_identify'] = $toUser->cs_uid.'-'.$param['toContactId'];
  568. }
  569. }
  570. $list = Message::getList($map, $where, 'msg_id desc', $listRows, $pageSize);
  571. $data = $this->recombileMsg($list,true,$groupManage);
  572. // 如果是群聊并且是第一页消息,需要推送@数据给用户
  573. if($param['is_group']==1 && $param['page']==1){
  574. $isPush=Cache::get('atMsgPush'.$chat_identify) ?? '';
  575. $atList=Db::name('message')->where(['chat_identify'=>$chat_identify,'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  576. $msgIda=array_column($atList,'msg_id');
  577. // 如果两次推送at数据的列表不一样,则推送
  578. if($isPush!=json_encode($msgIda)){
  579. $atData=$this->recombileMsg($atList,false);
  580. wsSendMsg($this->userInfo['user_id'],'atMsgList',[
  581. 'list'=>$atData,
  582. 'count'=>count($atData),
  583. 'toContactId'=>$param['toContactId']
  584. ]);
  585. Cache::set('atMsgPush'.$chat_identify,json_encode($msgIda),60);
  586. }
  587. }
  588. // 如果是消息管理器则不用倒序
  589. if (!isset($param['type'])) {
  590. $data = array_reverse($data);
  591. }
  592. return success('', $data, $list->total());
  593. }
  594. // 获取单条消息详情
  595. public function getMessageInfo()
  596. {
  597. $param = $this->request->param();
  598. $id = $param['msg_id'] ?? 0;
  599. $message = Message::where(['msg_id' => $id])->find();
  600. if ($message) {
  601. $data = $this->recombileMsg([$message], false);
  602. return success('', $data);
  603. } else {
  604. return warning(lang('im.exist'));
  605. }
  606. }
  607. // 获取单条消息上下文
  608. public function getMessageContext()
  609. {
  610. $param = $this->request->param();
  611. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  612. $id = $param['msg_id'] ?? 0;
  613. $direction = $param['direction'] ?? 0;
  614. $message = Message::where(['msg_id' => $id])->find();
  615. if (!$message) {
  616. return warning(lang('im.exist'));
  617. }
  618. $groupManage=[];
  619. $where = [];
  620. $map = ['chat_identify' => $message['chat_identify'], 'status' => 1];
  621. if($is_group==1 && $direction<2){
  622. $group_id = $message['to_user'];
  623. $group=Group::where(['group_id'=> $group_id])->find();
  624. $groupManage=GroupUser::getGroupManage($group_id);
  625. if($group && $group['setting']){
  626. $groupSetting=json_decode($group['setting'],true);
  627. $history=$groupSetting['history'] ?? false;
  628. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  629. if(!$history){
  630. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  631. $where[] = ['create_time', '>=', $createTime ? : 0];
  632. }
  633. }
  634. }
  635. if($direction==0){
  636. $where[] = ['msg_id', '<', $id];
  637. $beforeList = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  638. $beforeList = array_reverse($beforeList);
  639. $where2 = [];
  640. $where2[] = ['msg_id', '>=', $id];
  641. $afterList = Message::where($map)->where($where2)->order('msg_id asc')->limit(5)->select()->toArray();
  642. $data = array_merge($beforeList, $afterList);
  643. }elseif($direction==1){
  644. $where[] = ['msg_id', '<', $id];
  645. $data = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  646. $data = array_reverse($data);
  647. }else{
  648. $where[] = ['msg_id', '>', $id];
  649. $data = Message::where($map)->where($where)->order('msg_id asc')->limit(5)->select()->toArray();
  650. }
  651. if($data){
  652. $data = $this->recombileMsg($data, false,$groupManage);
  653. }
  654. return success('', $data);
  655. }
  656. protected function recombileMsg($list,$isPagination=true,$manage=[])
  657. {
  658. $data = [];
  659. $userInfo = $this->userInfo;
  660. if ($list) {
  661. $listData = $isPagination ? $list->toArray()['data'] : $list;
  662. $userList = User::matchUser($listData, true, 'from_user', 120);
  663. foreach ($listData as $k => $v) {
  664. // 屏蔽已删除的消息
  665. if ($v['del_user']) {
  666. $delUser = explode(',', $v['del_user']);
  667. if (in_array($userInfo['user_id'], $delUser)) {
  668. unset($list[$k]);
  669. continue;
  670. // $v['type']="event";
  671. // $v['content']="删除了一条消息";
  672. }
  673. }
  674. $content = str_encipher($v['content'],false);
  675. $preview = '';
  676. $ext='';
  677. if (in_array($v['type'], $this->fileType)) {
  678. $content = getFileUrl($content);
  679. $preview = previewUrl($content);
  680. $ext=getExtUrl($content);
  681. }
  682. $fromUser = $userList[$v['from_user']];
  683. // 处理撤回的消息
  684. if ($v['type'] == "event" && $v['is_undo']==1) {
  685. if ($v['from_user'] == $userInfo['user_id']) {
  686. $content = lang('im.you'). $content;
  687. } elseif ($v['is_group'] == 1) {
  688. $content = $fromUser['realname'] . $content;
  689. } else {
  690. $content = lang('im.other') . $content;
  691. }
  692. }
  693. $toContactId=$v['is_group'] ==1 ? 'group-'.$v['to_user'] : $v['to_user'];
  694. $atList=($v['at'] ?? null) ? explode(',',$v['at']): [];
  695. $role=$manage[$v['from_user']] ?? 3;
  696. $data[] = [
  697. 'msg_id' => $v['msg_id'],
  698. 'id' => $v['id'],
  699. 'status' => "succeed",
  700. 'type' => $v['type'],
  701. 'sendTime' => (is_string($v['create_time']) ? strtotime($v['create_time']) : $v['create_time'])* 1000,
  702. 'content' => $content,
  703. 'preview' => $preview,
  704. 'download' => $v['file_id'] ? getMainHost().'/filedown/'.encryptIds($v['file_id']) : '',
  705. 'is_read' => $v['is_read'],
  706. 'is_group' => $v['is_group'],
  707. 'at' => $atList,
  708. 'toContactId' => $toContactId,
  709. 'from_user' => $v['from_user'],
  710. 'file_id' => $v['file_id'],
  711. 'file_cate' => $v['file_cate'],
  712. 'fileName' => $v['file_name'],
  713. 'fileSize' => $v['file_size'],
  714. 'is_click' => $v['is_click'],
  715. 'fromUser' => $fromUser,
  716. 'extUrl'=>$ext,
  717. 'role'=>$role,
  718. 'extends'=>is_string($v['extends'])?json_decode($v['extends'],true) : $v['extends']
  719. ];
  720. }
  721. }
  722. return $data;
  723. }
  724. // 设置当前窗口的消息默认为已读
  725. public function setMsgIsRead()
  726. {
  727. $param = $this->request->param();
  728. // 判断是否是一个二维数组
  729. if (is_array($param['messages'][0] ?? '')) {
  730. $messages=$param['messages'];
  731. } else {
  732. $messages=[$param['messages']];
  733. }
  734. $this->setIsRead($param['is_group'], $param['toContactId'],$messages);
  735. if (!$param['is_group']) {
  736. wsSendMsg($param['fromUser'], 'isRead', $messages, 0);
  737. }
  738. return success('');
  739. }
  740. // 设置全部为已读
  741. public function readAllMsg()
  742. {
  743. // 阅读所有单聊
  744. $map = ['to_user' => $this->userInfo['user_id'], 'is_read' => 0, 'is_group' => 0];
  745. Message::where($map)->update(['is_read' => 1]);
  746. // 阅读所有群聊
  747. GroupUser::where(['user_id' => $this->userInfo['user_id'], 'status' => 1])->update(['unread'=>0]);
  748. return success('');
  749. }
  750. // 设置消息已读
  751. protected function setIsRead($is_group, $to_user,$messages=[])
  752. {
  753. if ($is_group==1) {
  754. $chat_identify = $to_user;
  755. } else if($is_group==0) {
  756. $chat_identify = chat_identify($this->userInfo['user_id'], $to_user);
  757. } else if($is_group==2){
  758. $chat_identify = $to_user;
  759. }
  760. $data=[
  761. 'action'=>'setIsRead',
  762. 'is_group'=>$is_group,
  763. 'to_user'=>$to_user,
  764. 'messages'=>$messages,
  765. 'user_id'=>$this->userInfo['user_id']
  766. ];
  767. queuePush($data,3);
  768. return $chat_identify;
  769. }
  770. // 聊天设置
  771. public function setting()
  772. {
  773. $param = $this->request->param();
  774. if ($param) {
  775. User::where(['user_id' => $this->userInfo['user_id']])->update(['setting' => $param]);
  776. return success('');
  777. }
  778. return warning('');
  779. }
  780. // 撤回消息
  781. public function undoMessage()
  782. {
  783. // echo Lang::getLangSet();
  784. // echo \think\facade\Lang::get('ok');
  785. // echo \think\facade\Lang::get('im.other');
  786. // die;
  787. // Lang::clear();
  788. // $setRes = Lang::setLangSet('en');
  789. // dump('设置语言是否成功:', $setRes); // 应返回 true
  790. // dump('当前语言标识:', Lang::getLangSet()); // 应返回 en
  791. // dump('已加载的语言文件:', Lang::getLoadFiles()); // 应包含 en.php 路径
  792. // dump('im.other 值:', Lang::get('im.other')); // 看实际返回值
  793. // die;
  794. $param = $this->request->param();
  795. $id = $param['id'];
  796. $message = Message::where(['id' => $id])->find();
  797. if ($message) {
  798. // 如果时间超过了2分钟也不能撤回
  799. $createTime=is_string($message['create_time']) ? strtotime($message['create_time']) : $message['create_time'];
  800. $redoTime=$this->globalConfig['chatInfo']['redoTime'] ?? 120;
  801. if ($this->userInfo['role'] == 0 && $this->globalConfig['user_cancel_message'] && $this->globalConfig['user_cancel_message']) {
  802. $redoTime=$this->globalConfig['user_cancel_message_time'] * 60;
  803. } elseif ($this->userInfo['role'] != 0 && $this->globalConfig['kefu_cancel_message']) {
  804. $redoTime=$this->globalConfig['kefu_cancel_message'] * 60;
  805. }
  806. if(time()-$createTime>$redoTime && $message['is_group']==0){
  807. return warning(lang('im.redoLimitTime',['time'=>floor($redoTime/60)]));
  808. }
  809. $text = lang('im.redo');
  810. $fromUserName = lang('im.other');
  811. $toContactId = $message['to_user'];
  812. if ($message['is_group'] == 1) {
  813. $fromUserName = $this->userInfo['realname'];
  814. $toContactId = explode('-', $message['chat_identify'])[1];
  815. // 如果是群聊消息撤回,需要判断是否是群主或者管理员,如果是则可以撤回
  816. if($message['from_user']!=$this->userInfo['user_id']){
  817. $groupUser=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$toContactId])->find();
  818. if(!$groupUser || !in_array($groupUser['role'],[1,2])){
  819. return warning(lang('system.notAuth'));
  820. }
  821. $text=lang('im.manageRedo');
  822. }
  823. }
  824. $message->content = str_encipher($text);
  825. $message->type = 'event';
  826. $message->is_undo = 1;
  827. //@的数据清空
  828. $message->at = '';
  829. $message->save();
  830. $info = $message->toArray();
  831. // $data = $info;
  832. $data['content'] = $fromUserName . $text;
  833. $data['sendTime'] = $createTime * 1000;
  834. $data['id'] = $info['id'];
  835. $data['from_user'] = $info['from_user'];
  836. $data['msg_id'] = $info['msg_id'];
  837. $data['status'] = $info['status'];
  838. $data['type'] = 'event';
  839. $data['is_last'] = $info['is_last'];
  840. $data['toContactId'] = $message['is_group'] == 1 ? $info['chat_identify'] : $toContactId;
  841. $data['isMobile'] = $this->request->isMobile() ? 1 : 0;
  842. wsSendMsg($toContactId, 'undoMessage', $data, $info['is_group']);
  843. if($info['is_group']==0){
  844. // 给自己也发一份推送,多端同步
  845. $data['content'] =lang('im.you'). $text;
  846. wsSendMsg($this->userInfo['user_id'], 'undoMessage', $data, $info['is_group']);
  847. }
  848. return success('');
  849. } else {
  850. return warning();
  851. }
  852. }
  853. // 删除消息
  854. public function removeMessage()
  855. {
  856. $param = $this->request->param();
  857. $id = $param['id'];
  858. $map = ['id' => $id];
  859. $message = Message::where($map)->find();
  860. if ($message) {
  861. $message->del_user = $this->userInfo['user_id'];
  862. if ($message['is_group'] == 1) {
  863. if ($message['del_user']) {
  864. $message->del_user .= ',' . $this->userInfo['user_id'];
  865. }
  866. } else {
  867. if ($message['del_user'] > 0) {
  868. $message->where($map)->delete();
  869. return success(lang('system.delOk'));
  870. }
  871. }
  872. $message->save();
  873. return success('');
  874. } else {
  875. return warning('');
  876. }
  877. }
  878. // 消息免打扰
  879. public function isNotice()
  880. {
  881. $param = $this->request->param();
  882. $user_id = $this->userInfo['user_id'];
  883. $id = $param['id'];
  884. if ($param['is_group'] == 1) {
  885. $group_id = explode('-', $param['id'])[1];
  886. GroupUser::update(['is_notice' => $param['is_notice']], ['user_id' => $user_id, 'group_id' => $group_id]);
  887. } else {
  888. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  889. $friend = Friend::where($map)->find();
  890. try {
  891. if ($friend) {
  892. $friend->is_notice = $param['is_notice'];
  893. $friend->save();
  894. } else {
  895. $info = [
  896. 'create_user' => $user_id,
  897. 'friend_user_id' => $id,
  898. 'is_notice' => $param['is_notice']
  899. ];
  900. Friend::create($info);
  901. }
  902. return success('');
  903. } catch (Exception $e) {
  904. return error($e->getMessage());
  905. }
  906. }
  907. wsSendMsg($user_id,"setIsNotice",['id'=>$id,'is_notice'=>$param['is_notice'],'is_group'=>$param['is_group']]);
  908. return success('');
  909. }
  910. // 设置聊天置顶
  911. public function setChatTop()
  912. {
  913. $param = $this->request->param();
  914. $user_id = $this->userInfo['user_id'];
  915. $is_group = $param['is_group'] ?: 0;
  916. $id = $param['id'];
  917. try {
  918. if ($is_group == 1) {
  919. $group_id = explode('-', $param['id'])[1];
  920. GroupUser::update(['is_top' => $param['is_top']], ['user_id' => $user_id, 'group_id' => $group_id]);
  921. } else {
  922. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  923. $friend = Friend::where($map)->find();
  924. if ($friend) {
  925. $friend->is_top = $param['is_top'];
  926. $friend->save();
  927. } else {
  928. $info = [
  929. 'create_user' => $user_id,
  930. 'friend_user_id' => $id,
  931. 'is_top' => $param['is_top']
  932. ];
  933. Friend::create($info);
  934. }
  935. }
  936. wsSendMsg($user_id,"setChatTop",['id'=>$id,'is_top'=>$param['is_top'],'is_group'=>$is_group]);
  937. return success('');
  938. } catch (Exception $e) {
  939. return error($e->getMessage());
  940. }
  941. }
  942. // 删除聊天
  943. public function delChat()
  944. {
  945. $param = $this->request->param();
  946. $user_id = $this->userInfo['user_id'];
  947. $is_group = $param['is_group'] ?: 0;
  948. $id = $param['id'];
  949. $data=[
  950. 'user_id'=>$user_id,
  951. 'is_group'=>$is_group,
  952. 'to_user'=>$id
  953. ];
  954. ChatDelog::create($data);
  955. ChatDelog::updateCache($user_id);
  956. return success('');
  957. }
  958. // 向用户发送消息
  959. public function sendToMsg(){
  960. $param=$this->request->param();
  961. $toContactId=$param['toContactId'];
  962. $type=$param['type'];
  963. $status=$param['status'];
  964. $event=$param['event'] ?? 'calling';
  965. if($event=='calling'){
  966. $status=3;
  967. }
  968. $sdp=$param['sdp'] ?? '';
  969. $iceCandidate=$param['iceCandidate'] ?? '';
  970. $callTime=$param['callTime'] ?? '';
  971. $msg_id=$param['msg_id'] ?? '';
  972. $id=$param['id'] ?? '';
  973. $code=($param['code'] ?? '') ?: 901;
  974. // 如果该用户不在线,则发送忙线
  975. Gateway::$registerAddress = config('gateway.registerAddress');
  976. if(!Gateway::isUidOnline($toContactId)){
  977. $toContactId=$this->userInfo['user_id'];
  978. $code=907;
  979. $event='busy';
  980. sleep(1);
  981. }
  982. switch($code){
  983. case 902:
  984. $content=lang('webRtc.cancel');
  985. break;
  986. case 903:
  987. $content=lang('webRtc.refuse');
  988. break;
  989. case 905:
  990. $content=lang('webRtc.notConnected');
  991. break;
  992. case 906:
  993. $content=lang('webRtc.duration',['time'=>date("i:s",$callTime)]);
  994. break;
  995. case 907:
  996. $content=lang('webRtc.busy');
  997. break;
  998. case 908:
  999. $content=lang('webRtc.other');
  1000. break;
  1001. default:
  1002. $content=$type==1 ?lang('webRtc.video') : lang('webRtc.audio');
  1003. break;
  1004. }
  1005. switch($event){
  1006. case 'calling':
  1007. $content=$type==1 ?lang('webRtc.video'): lang('webRtc.audio');
  1008. break;
  1009. case 'acceptRtc':
  1010. $content=lang('webRtc.answer');
  1011. break;
  1012. case 'iceCandidate':
  1013. $content=lang('webRtc.exchange');
  1014. break;
  1015. }
  1016. $userInfo=$this->userInfo;
  1017. $userInfo['id']=$userInfo['user_id'];
  1018. $user = new User();
  1019. $data=[
  1020. 'id'=>$id,
  1021. 'msg_id'=>$msg_id,
  1022. 'sendTime'=>time()*1000,
  1023. 'toContactId'=>$toContactId,
  1024. 'content'=>$content,
  1025. 'type'=>'webrtc',
  1026. 'status'=>'succeed',
  1027. 'is_group'=>0,
  1028. 'is_read'=>0,
  1029. 'fromUser'=>$userInfo,
  1030. 'at'=>[],
  1031. 'extends'=>[
  1032. 'type'=>$type, //通话类型,1视频,0语音。
  1033. 'status'=>$status, //,1拨打方,2接听方
  1034. 'event'=>$event,
  1035. 'callTime'=>$callTime,
  1036. 'sdp'=>$sdp,
  1037. 'code'=>$code, //通话状态:呼叫901,取消902,拒绝903,接听904,未接通905,接通后挂断906,忙线907,其他端操作908
  1038. 'iceCandidate'=>$iceCandidate,
  1039. 'isMobile'=>$this->request->isMobile() ? 1 : 0,
  1040. ]
  1041. ];
  1042. if($event=='calling'){
  1043. $chat_identify=chat_identify($userInfo['id'],$toContactId);
  1044. $msg=[
  1045. 'from_user'=>$userInfo['id'],
  1046. 'to_user'=>$toContactId,
  1047. 'id'=>$id,
  1048. 'content'=>str_encipher($content),
  1049. 'chat_identify'=>$chat_identify,
  1050. 'create_time'=>time(),
  1051. 'type'=>$data['type'],
  1052. 'is_group'=>0,
  1053. 'is_read'=>0,
  1054. 'extends'=>$data['extends'],
  1055. ];
  1056. $message=new Message();
  1057. $message->update(['is_last'=>0],['chat_identify'=>$chat_identify]);
  1058. $message->save($msg);
  1059. $msg_id=$message->msg_id;
  1060. $data['msg_id']=$msg_id;
  1061. // 将接收人设置为发送人才能定位到该消息
  1062. $data['toContactId']=$userInfo['id'];
  1063. $data['toUser']=$toContactId;
  1064. }elseif($event=='hangup'){
  1065. $message=Message::where(['id'=>$id])->find();
  1066. if(!$message){
  1067. return error(lang('webRtc.fail'));
  1068. }
  1069. if($message){
  1070. $message->content=str_encipher($content);
  1071. $extends=$message->extends;
  1072. $extends['code']=$code;
  1073. $extends['callTime']=$callTime;
  1074. $message->extends=$extends;
  1075. $message->save();
  1076. }
  1077. }
  1078. wsSendMsg($toContactId,'webrtc',$data);
  1079. $wsData=$data;
  1080. if(in_array($event,['calling','acceptRtc','hangup'])){
  1081. if(in_array($event,['acceptRtc','hangup'])){
  1082. $data['extends']['event']='otherOpt'; //其他端操作
  1083. }
  1084. $data['toContactId']=$toContactId;
  1085. $data['contactInfo']=$user->setContact($toContactId,0,'webrtc',$content) ? : [];
  1086. wsSendMsg($userInfo['id'],'webrtc',$data);
  1087. }
  1088. return success('',$wsData);
  1089. }
  1090. // 修改密码
  1091. public function editPassword()
  1092. {
  1093. if(env('app.demon_mode',false)){
  1094. return warning(lang('system.demoMode'));
  1095. }
  1096. $user_id = $this->userInfo['user_id'];
  1097. $user=User::find($user_id);
  1098. if(!$user){
  1099. return warning(lang('user.exist'));
  1100. }
  1101. $account=$user->account;
  1102. $code=$this->request->param('code','');
  1103. $originalPassword = $this->request->param('originalPassword', '');
  1104. if($code){
  1105. if(Cache::get($account)!=$code){
  1106. return warning(lang('user.codeErr'));
  1107. }
  1108. }elseif($originalPassword){
  1109. if(password_hash_tp($originalPassword,$user->salt)!= $user->password){
  1110. return warning(lang('user.passErr'));
  1111. }
  1112. }else{
  1113. return warning(lang('system.parameterError'));
  1114. }
  1115. try{
  1116. $password = $this->request->param('password','');
  1117. if($password){
  1118. $salt=$user->salt;
  1119. $user->password= password_hash_tp($password,$salt);
  1120. }
  1121. $user->save();
  1122. return success(lang('system.editOk'));
  1123. }catch (\Exception $e){
  1124. return error(lang('system.editFail'));
  1125. }
  1126. }
  1127. // 修改用户信息
  1128. public function updateUserInfo(){
  1129. try{
  1130. $data = $this->request->param();
  1131. $user=User::find($this->uid);
  1132. if(!$user){
  1133. return warning(lang('user.exist'));
  1134. }
  1135. // 接入用户名检测服务
  1136. event('GreenText',['content'=>$data['realname'],'service'=>"nickname_detection"]);
  1137. // 个性签名检测服务
  1138. event('GreenText',['content'=>$data['motto'],'service'=>"comment_detection"]);
  1139. $user->realname =$data['realname'];
  1140. $user->email =$data['email'];
  1141. $user->motto=$data['motto'];
  1142. $user->sex =$data['sex'];
  1143. $user->name_py= pinyin_sentence($data['realname']);
  1144. $user->save();
  1145. return success(lang('system.editOk'), $data);
  1146. }catch (\Exception $e){
  1147. return error($e->getMessage());
  1148. }
  1149. }
  1150. // 修改账户
  1151. public function editAccount(){
  1152. if(env('app.demon_mode',false)){
  1153. return warning(lang('system.demoMode'));
  1154. }
  1155. $code=$this->request->param('code','');
  1156. $newCode=$this->request->param('newCode','');
  1157. $account=$this->request->param('account','');
  1158. $isUser=User::where('account',$account)->find();
  1159. if($isUser){
  1160. return warning(lang('user.already'));
  1161. }
  1162. $user=User::find($this->uid);
  1163. if(!$user){
  1164. return warning(lang('user.exist'));
  1165. }
  1166. // 如果已经认证过了,则需要验证验证码
  1167. if($user->is_auth){
  1168. if(Cache::get($user->account)!=$code){
  1169. return warning(lang('user.codeErr'));
  1170. }
  1171. }
  1172. if(Cache::get($account)!=$newCode){
  1173. return warning(lang('user.newCodeErr'));
  1174. }
  1175. try{
  1176. $user->account=$account;
  1177. $user->is_auth=1;
  1178. $user->save();
  1179. return success(lang('system.editOk'));
  1180. }catch (\Exception $e){
  1181. return error(lang('system.editFail'));
  1182. }
  1183. }
  1184. // 阅读@消息
  1185. public function readAtMsg(){
  1186. $param = $this->request->param();
  1187. $atList=Db::name('message')->where(['chat_identify'=>$param['toContactId'],'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select();
  1188. $atData=$this->recombileMsg($atList,false);
  1189. Message::setAtRead($atData,$this->userInfo['user_id']);
  1190. // $message=Message::where('msg_id',$param['msg_id'])->select();
  1191. // $atList=($message ?? null) ? explode(',',$message): [];
  1192. // // 两个数组取差集
  1193. // $newAtList = array_diff($atList, [$this->userInfo['user_id']]);
  1194. // Message::where('msg_id',$param['msg_id'])->update(['at'=>implode(',',$newAtList)]);
  1195. return success('');
  1196. }
  1197. // 获取系统公告
  1198. public function getAdminNotice(){
  1199. $data=Message::where(['chat_identify'=>'admin_notice'])->order('msg_id desc')->find();
  1200. $extends=$data['extends'] ?? [];
  1201. if(!$extends){
  1202. $extends['title']='';
  1203. }
  1204. $createTime=$data['create_time'] ?? 0;
  1205. if(!$createTime){
  1206. $extends['create_time']=$createTime;
  1207. }else{
  1208. $extends['create_time']=is_string($data['create_time']) ? strtotime($data['create_time']) : $data['create_time'];
  1209. }
  1210. return success('',$extends);
  1211. }
  1212. // 双向删除消息
  1213. public function delMessage(){
  1214. $param = $this->request->param();
  1215. $id = $param['id'];
  1216. if(!$this->globalConfig['chatInfo']['dbDelMsg']){
  1217. return warning(lang('system.notAuth'));
  1218. }
  1219. $message = Message::where(['id' => $id])->find();
  1220. if ($message) {
  1221. if($message['from_user']!=$this->userInfo['user_id']){
  1222. return warning(lang('system.notAuth'));
  1223. }
  1224. Message::where(['id' => $id])->delete();
  1225. // 如果是最后一条消息,需要将上一条设置为最后一条
  1226. if($message['is_last']){
  1227. Message::where(['chat_identify'=>$message['chat_identify']])->order('msg_id desc')->limit(1)->update(['is_last'=>1]);
  1228. }
  1229. $toContactId = $message['to_user'];
  1230. if ($message['is_group'] == 1) {
  1231. $toContactId = explode('-', $message['chat_identify'])[1];
  1232. }
  1233. wsSendMsg($toContactId, 'delMessage', $message, $message['is_group']);
  1234. return success('');
  1235. } else {
  1236. return warning(lang('im.exist'));
  1237. }
  1238. }
  1239. }