Im.php 49 KB

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