Im.php 50 KB

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