Im.php 51 KB

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