Im.php 50 KB

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