Im.php 50 KB

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