Im.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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 League\Flysystem\Util;
  10. use think\facade\Cache;
  11. class Im extends BaseController
  12. {
  13. protected $fileType = ['file', 'image','video','voice','emoji'];
  14. // 获取联系人列表
  15. public function getContacts()
  16. {
  17. $data = User::getUserList([['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]], $this->userInfo['user_id']);
  18. $count=Friend::where(['status'=>2,'friend_user_id'=>$this->uid])->count();
  19. $time=Friend::where(['friend_user_id'=>$this->uid,'is_invite'=>1])->order('create_time desc')->value('create_time');
  20. return success('', $data,$count,$time*1000);
  21. }
  22. // 获取聊天列表
  23. public function getChatList()
  24. {
  25. $data = User::getChatList($this->userInfo['user_id']);
  26. $count=Friend::where(['status'=>2,'friend_user_id'=>$this->uid])->count();
  27. $time=Friend::where(['friend_user_id'=>$this->uid,'is_invite'=>1])->order('create_time desc')->value('create_time');
  28. return success('', $data,$count,$time*1000);
  29. }
  30. // 获取好友列表
  31. public function getFriendList()
  32. {
  33. $data = User::getFriendList([['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]],$this->userInfo['user_id']);
  34. return success('', $data);
  35. }
  36. // 获取群聊列表
  37. public function getGroupList()
  38. {
  39. $data = User::getGroupList($this->userInfo['user_id']);
  40. return success('', $data);
  41. }
  42. // 获取单个人员的信息
  43. public function getContactInfo(){
  44. $id = $this->request->param('id');
  45. $is_group = is_string($id) ? 1 : 0;
  46. $user=new User;
  47. $data=$user->setContact($id,$is_group);
  48. if(!$data){
  49. return warning($user->getError());
  50. }
  51. return success('',$data);
  52. }
  53. //发送消息
  54. public function sendMessage()
  55. {
  56. $param = $this->request->param();
  57. $param['user_id'] = $this->userInfo['user_id'];
  58. $message=new Message();
  59. $data = $message->sendMessage($param,$this->globalConfig);
  60. if ($data) {
  61. return success('', $data);
  62. } else {
  63. return warning($message->getError());
  64. }
  65. }
  66. //转发消息
  67. public function forwardMessage()
  68. {
  69. $param = $this->request->param();
  70. $userIds=$param['user_ids'] ?? [];
  71. if(!$userIds || count($userIds)>5){
  72. return warning(lang('im.forwardLimit',['count'=>5]));
  73. }
  74. $msg_id=$param['msg_id'] ?? 0;
  75. $message=Message::find($msg_id);
  76. if(!$message){
  77. return warning(lang('im.exist'));
  78. }
  79. $msg=$message->toArray();
  80. $userInfo=$this->userInfo;
  81. queuePush([
  82. 'action'=>'forwardMessage',
  83. 'message'=>$msg,
  84. 'user_ids'=>$userIds,
  85. 'config'=>$this->globalConfig,
  86. 'userInfo'=>$userInfo
  87. ]);
  88. return success(lang('im.forwardOk'));
  89. }
  90. // 获取用户信息
  91. public function getUserInfo()
  92. {
  93. $user_id = $this->request->param('user_id');
  94. $group_id = $this->request->param('group_id');
  95. $groupInfo=[];
  96. if($group_id){
  97. $group_id = explode('-', $group_id)[1];
  98. $groupInfo=Group::where(['group_id'=>$group_id])->find();
  99. if($groupInfo){
  100. // 查询操作对象的角色
  101. $groupInfo['userInfo']=GroupUser::where(['user_id'=>$user_id,'group_id'=>$group_id])->find() ?: [];
  102. // 查询我的角色
  103. $groupInfo['manageRole']=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$group_id])->value('role') ?: 3;
  104. }
  105. }
  106. $user=User::find($user_id);
  107. if(!$user){
  108. return error(lang('user.exist'));
  109. }
  110. $user->avatar=avatarUrl($user->avatar,$user->realname,$user->user_id,120);
  111. // 账号前面截取3位,后面截取两位,中间星号展示
  112. $user->account=substr($user->account, 0, 3).'******'.substr($user->account, -2, 2);
  113. // 查询好友关系
  114. $friend=Friend::where(['friend_user_id'=>$user_id,'create_user'=>$this->userInfo['user_id'],'status'=>1])->find();
  115. $user->friend=$friend ? : '';
  116. $location='';
  117. if($user->last_login_ip){
  118. $location=implode(" ", \Ip::find($user->last_login_ip));
  119. }
  120. $user->location=$location;
  121. $user->groupInfo=$groupInfo ? : [];
  122. $user->password='';
  123. $userModel=new User;
  124. $user->contactInfo=$userModel->setContact($user_id,0) ?? [];
  125. return success('', $user);
  126. }
  127. // 扫码登录,向客户端推送数据
  128. public function tokenLogin(){
  129. $param = $this->request->param();
  130. $token=$param['token'] ?? '';
  131. $client_id='';
  132. if($token){
  133. $client_id=authcode(urldecode($token),"DECODE", config('app.app_id'));
  134. if(!$client_id){
  135. return warning(lang('user.loginError'));
  136. }
  137. }else{
  138. return warning(lang('user.loginError'));
  139. }
  140. $userInfo=$this->userInfo;
  141. if(!$userInfo){
  142. return warning(lang('user.loginError'));
  143. }
  144. // 如果用户已经有设置
  145. $setting=$userInfo['setting'] ?: '';
  146. if($setting){
  147. $setting['hideMessageName']= $setting['hideMessageName']=='true' ? true : false;
  148. $setting['hideMessageTime']= $setting['hideMessageTime']=='true' ? true : false;
  149. $setting['avatarCricle']= $setting['avatarCricle']=='true' ? true : false;
  150. $setting['isVoice']= $setting['isVoice']=='true' ? true : false;
  151. $setting['sendKey']=(int)$setting['sendKey'];
  152. }
  153. $userInfo['setting']=$setting;
  154. Gateway::$registerAddress = config('gateway.registerAddress');
  155. //如果登录信息中含有client——id则自动进行绑定
  156. if($client_id){
  157. $user_id=$userInfo['user_id'];
  158. // 如果当前ID在线,将其他地方登陆挤兑下线
  159. if(Gateway::isUidOnline($user_id)){
  160. wsSendMsg($user_id,'offline',['id'=>$user_id,'client_id'=>$client_id,'isMobile'=>false]);
  161. }
  162. Gateway::bindUid($client_id, $user_id);
  163. // 查询团队,如果有团队则加入团队
  164. $group=Group::getMyGroup(['gu.user_id'=>$user_id,'gu.status'=>1]);
  165. if($group){
  166. $group=$group->toArray();
  167. $group_ids=arrayToString($group,'group_id',false);
  168. foreach($group_ids as $v){
  169. Gateway::joinGroup($client_id, $v);
  170. }
  171. }
  172. }
  173. $update=[
  174. 'last_login_time'=>time(),
  175. 'last_login_ip'=>$this->request->ip(),
  176. 'login_count'=>Db::raw('login_count+1')
  177. ];
  178. User::where('user_id',$userInfo['user_id'])->update($update);
  179. $authToken=User::refreshToken($userInfo,'web');
  180. $data=[
  181. 'sessionId'=>Session::getId(),
  182. 'authToken'=>$authToken,
  183. 'userInfo'=>$userInfo
  184. ];
  185. Gateway::sendToClient($client_id, json_encode(array(
  186. 'type' => 'tokenLogin',
  187. 'data' => $data,
  188. )));
  189. return success(lang('user.loginOk'),$data);
  190. }
  191. // 搜索用户
  192. public function searchUser(){
  193. $keywords=$this->request->param('keywords','');
  194. if(!$keywords){
  195. return success('',[]);
  196. }
  197. $map=['status'=>1,'account'=>$keywords];
  198. $list=User::where($map)->field(User::$defaultField)->where([['account','<>',$this->userInfo['account']]])->select()->toArray();
  199. if($list){
  200. $ids=array_column($list,'user_id');
  201. $friendList=Friend::getFriend([['create_user','=',$this->uid],['friend_user_id','in',$ids]]);
  202. foreach($list as $k=>$v){
  203. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  204. $list[$k]['friend']=$friendList[$v['user_id']] ?? '';
  205. }
  206. }
  207. return success('', $list);
  208. }
  209. // 获取系统所有人员加搜索
  210. public function userList(){
  211. $keywords=$this->request->param('keywords','');
  212. $listRows=$this->request->param('limit',20);
  213. $page=$this->request->param('page',1);
  214. $map=['status'=>1];
  215. $field="user_id,realname,avatar";
  216. if(!$keywords){
  217. $list=User::where($map)->field($field)->order('user_id asc')->limit(20)->paginate(['list_rows'=>$listRows,'page'=>$page]);;
  218. if($list){
  219. $list=$list->toArray()['data'];
  220. }
  221. }else{
  222. $list=User::where($map)->field($field)->where([['account','<>',$this->userInfo['account']]])->whereLike('account|realname|name_py','%'.$keywords.'%')->select()->toArray();
  223. }
  224. if($list){
  225. foreach($list as $k=>$v){
  226. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  227. $list[$k]['id']=$v['user_id'];
  228. }
  229. }
  230. return success('', $list);
  231. }
  232. // 获取聊天记录
  233. public function getMessageList()
  234. {
  235. $param = $this->request->param();
  236. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  237. // 如果toContactId是数字,绝对是单聊
  238. $is_group = is_numeric($param['toContactId']) ? 0 : $is_group;
  239. // 设置当前聊天消息为已读
  240. $chat_identify = $this->setIsRead($is_group, $param['toContactId']);
  241. $type = isset($param['type']) ? $param['type'] : '';
  242. $is_at = isset($param['is_at']) ? $param['is_at'] : '';
  243. $map = ['chat_identify' => $chat_identify, 'status' => 1];
  244. $where = [];
  245. if ($type && $type != "all") {
  246. $map['type'] = $type;
  247. } else {
  248. if (isset($param['type'])) {
  249. $where[] = ['type', '<>', 'event'];
  250. }
  251. }
  252. $groupManage=[];
  253. // 群聊查询入群时间以后的消息
  254. if($is_group==1){
  255. $group_id = explode('-', $param['toContactId'])[1];
  256. $group=Group::where(['group_id'=> $group_id])->find();
  257. $groupManage=GroupUser::getGroupManage($group_id);
  258. if($group && $group['setting']){
  259. $groupSetting=json_decode($group['setting'],true);
  260. $history=$groupSetting['history'] ?? false;
  261. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  262. if(!$history){
  263. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  264. $where[] = ['create_time', '>=', $createTime ? : 0];
  265. }
  266. }
  267. }
  268. $keywords = isset($param['keywords']) ? $param['keywords'] : '';
  269. if ($keywords && in_array($type, ['text', 'all'])) {
  270. $where[] = ['content', 'like', '%' . $keywords . '%'];
  271. }
  272. // 如果是查询@数据
  273. if($is_at){
  274. $atList=Db::name('message')->where($map)->where($where)->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  275. if($atList){
  276. $data = $this->recombileMsg($atList,false);
  277. Message::setAtread($data,$this->userInfo['user_id']);
  278. return success('', $data, count($data));
  279. }else{
  280. return success('', [], 0);
  281. }
  282. }
  283. $listRows = $param['limit'] ?: 20;
  284. $pageSize = $param['page'] ?: 1;
  285. $last_id = $param['last_id'] ?? 0;
  286. if($last_id){
  287. $where[]=['msg_id','<',$last_id];
  288. $pageSize=1;
  289. }
  290. $list = Message::getList($map, $where, 'msg_id desc', $listRows, $pageSize);
  291. $data = $this->recombileMsg($list,true,$groupManage);
  292. // 如果是群聊并且是第一页消息,需要推送@数据给用户
  293. if($param['is_group']==1 && $param['page']==1){
  294. $isPush=Cache::get('atMsgPush'.$chat_identify) ?? '';
  295. $atList=Db::name('message')->where(['chat_identify'=>$chat_identify,'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  296. $msgIda=array_column($atList,'msg_id');
  297. // 如果两次推送at数据的列表不一样,则推送
  298. if($isPush!=json_encode($msgIda)){
  299. $atData=$this->recombileMsg($atList,false);
  300. wsSendMsg($this->userInfo['user_id'],'atMsgList',[
  301. 'list'=>$atData,
  302. 'count'=>count($atData),
  303. 'toContactId'=>$param['toContactId']
  304. ]);
  305. Cache::set('atMsgPush'.$chat_identify,json_encode($msgIda),60);
  306. }
  307. }
  308. // 如果是消息管理器则不用倒序
  309. if (!isset($param['type'])) {
  310. $data = array_reverse($data);
  311. }
  312. return success('', $data, $list->total());
  313. }
  314. // 获取单条消息详情
  315. public function getMessageInfo()
  316. {
  317. $param = $this->request->param();
  318. $id = $param['msg_id'] ?? 0;
  319. $message = Message::where(['msg_id' => $id])->find();
  320. if ($message) {
  321. $data = $this->recombileMsg([$message], false);
  322. return success('', $data);
  323. } else {
  324. return warning(lang('im.exist'));
  325. }
  326. }
  327. // 获取单条消息上下文
  328. public function getMessageContext()
  329. {
  330. $param = $this->request->param();
  331. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  332. $id = $param['msg_id'] ?? 0;
  333. $direction = $param['direction'] ?? 0;
  334. $message = Message::where(['msg_id' => $id])->find();
  335. if (!$message) {
  336. return warning(lang('im.exist'));
  337. }
  338. $groupManage=[];
  339. $where = [];
  340. $map = ['chat_identify' => $message['chat_identify'], 'status' => 1];
  341. if($is_group==1 && $direction<2){
  342. $group_id = $message['to_user'];
  343. $group=Group::where(['group_id'=> $group_id])->find();
  344. $groupManage=GroupUser::getGroupManage($group_id);
  345. if($group && $group['setting']){
  346. $groupSetting=json_decode($group['setting'],true);
  347. $history=$groupSetting['history'] ?? false;
  348. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  349. if(!$history){
  350. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  351. $where[] = ['create_time', '>=', $createTime ? : 0];
  352. }
  353. }
  354. }
  355. if($direction==0){
  356. $where[] = ['msg_id', '<', $id];
  357. $beforeList = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  358. $beforeList = array_reverse($beforeList);
  359. $where2 = [];
  360. $where2[] = ['msg_id', '>=', $id];
  361. $afterList = Message::where($map)->where($where2)->order('msg_id asc')->limit(5)->select()->toArray();
  362. $data = array_merge($beforeList, $afterList);
  363. }elseif($direction==1){
  364. $where[] = ['msg_id', '<', $id];
  365. $data = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  366. $data = array_reverse($data);
  367. }else{
  368. $where[] = ['msg_id', '>', $id];
  369. $data = Message::where($map)->where($where)->order('msg_id asc')->limit(5)->select()->toArray();
  370. }
  371. if($data){
  372. $data = $this->recombileMsg($data, false,$groupManage);
  373. }
  374. return success('', $data);
  375. }
  376. protected function recombileMsg($list,$isPagination=true,$manage=[])
  377. {
  378. $data = [];
  379. $userInfo = $this->userInfo;
  380. if ($list) {
  381. $listData = $isPagination ? $list->toArray()['data'] : $list;
  382. $userList = User::matchUser($listData, true, 'from_user', 120);
  383. foreach ($listData as $k => $v) {
  384. // 屏蔽已删除的消息
  385. if ($v['del_user']) {
  386. $delUser = explode(',', $v['del_user']);
  387. if (in_array($userInfo['user_id'], $delUser)) {
  388. unset($list[$k]);
  389. continue;
  390. // $v['type']="event";
  391. // $v['content']="删除了一条消息";
  392. }
  393. }
  394. $content = str_encipher($v['content'],false);
  395. $preview = '';
  396. $ext='';
  397. if (in_array($v['type'], $this->fileType)) {
  398. $content = getFileUrl($content);
  399. $preview = previewUrl($content);
  400. $ext=getExtUrl($content);
  401. }
  402. $fromUser = $userList[$v['from_user']];
  403. // 处理撤回的消息
  404. if ($v['type'] == "event" && $v['is_undo']==1) {
  405. if ($v['from_user'] == $userInfo['user_id']) {
  406. $content = lang('im.you'). $content;
  407. } elseif ($v['is_group'] == 1) {
  408. $content = $fromUser['realname'] . $content;
  409. } else {
  410. $content = lang('im.other') . $content;
  411. }
  412. }
  413. $toContactId=$v['is_group'] ==1 ? 'group-'.$v['to_user'] : $v['to_user'];
  414. $atList=($v['at'] ?? null) ? explode(',',$v['at']): [];
  415. $role=$manage[$v['from_user']] ?? 3;
  416. $data[] = [
  417. 'msg_id' => $v['msg_id'],
  418. 'id' => $v['id'],
  419. 'status' => "succeed",
  420. 'type' => $v['type'],
  421. 'sendTime' => (is_string($v['create_time']) ? strtotime($v['create_time']) : $v['create_time'])* 1000,
  422. 'content' => $content,
  423. 'preview' => $preview,
  424. 'download' => $v['file_id'] ? getMainHost().'/filedown/'.encryptIds($v['file_id']) : '',
  425. 'is_read' => $v['is_read'],
  426. 'is_group' => $v['is_group'],
  427. 'at' => $atList,
  428. 'toContactId' => $toContactId,
  429. 'from_user' => $v['from_user'],
  430. 'file_id' => $v['file_id'],
  431. 'file_cate' => $v['file_cate'],
  432. 'fileName' => $v['file_name'],
  433. 'fileSize' => $v['file_size'],
  434. 'fromUser' => $fromUser,
  435. 'extUrl'=>$ext,
  436. 'role'=>$role,
  437. 'extends'=>is_string($v['extends'])?json_decode($v['extends'],true) : $v['extends']
  438. ];
  439. }
  440. }
  441. return $data;
  442. }
  443. // 设置当前窗口的消息默认为已读
  444. public function setMsgIsRead()
  445. {
  446. $param = $this->request->param();
  447. // 判断是否是一个二维数组
  448. if (is_array($param['messages'][0] ?? '')) {
  449. $messages=$param['messages'];
  450. } else {
  451. $messages=[$param['messages']];
  452. }
  453. $this->setIsRead($param['is_group'], $param['toContactId'],$messages);
  454. if (!$param['is_group']) {
  455. wsSendMsg($param['fromUser'], 'isRead', $messages, 0);
  456. }
  457. return success('');
  458. }
  459. // 设置全部为已读
  460. public function readAllMsg()
  461. {
  462. // 阅读所有单聊
  463. $map = ['to_user' => $this->userInfo['user_id'], 'is_read' => 0, 'is_group' => 0];
  464. Message::where($map)->update(['is_read' => 1]);
  465. // 阅读所有群聊
  466. GroupUser::where(['user_id' => $this->userInfo['user_id'], 'status' => 1])->update(['unread'=>0]);
  467. return success('');
  468. }
  469. // 设置消息已读
  470. protected function setIsRead($is_group, $to_user,$messages=[])
  471. {
  472. if ($is_group==1) {
  473. $chat_identify = $to_user;
  474. } else if($is_group==0) {
  475. $chat_identify = chat_identify($this->userInfo['user_id'], $to_user);
  476. } else if($is_group==2){
  477. $chat_identify = $to_user;
  478. }
  479. $data=[
  480. 'action'=>'setIsRead',
  481. 'is_group'=>$is_group,
  482. 'to_user'=>$to_user,
  483. 'messages'=>$messages,
  484. 'user_id'=>$this->userInfo['user_id']
  485. ];
  486. queuePush($data,3);
  487. return $chat_identify;
  488. }
  489. // 聊天设置
  490. public function setting()
  491. {
  492. $param = $this->request->param();
  493. if ($param) {
  494. User::where(['user_id' => $this->userInfo['user_id']])->update(['setting' => $param]);
  495. return success('');
  496. }
  497. return warning('');
  498. }
  499. // 撤回消息
  500. public function undoMessage()
  501. {
  502. $param = $this->request->param();
  503. $id = $param['id'];
  504. $message = Message::where(['id' => $id])->find();
  505. if ($message) {
  506. // 如果时间超过了2分钟也不能撤回
  507. $createTime=is_string($message['create_time']) ? strtotime($message['create_time']) : $message['create_time'];
  508. $redoTime=$this->globalConfig['chatInfo']['redoTime'] ?? 120;
  509. if(time()-$createTime>$redoTime && $message['is_group']==0){
  510. return warning(lang('im.redoLimitTime',['time'=>floor($redoTime/60)]));
  511. }
  512. $text = lang('im.redo');
  513. $fromUserName = lang('im.other');
  514. $toContactId = $message['to_user'];
  515. if ($message['is_group'] == 1) {
  516. $fromUserName = $this->userInfo['realname'];
  517. $toContactId = explode('-', $message['chat_identify'])[1];
  518. // 如果是群聊消息撤回,需要判断是否是群主或者管理员,如果是则可以撤回
  519. if($message['from_user']!=$this->userInfo['user_id']){
  520. $groupUser=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$toContactId])->find();
  521. if(!$groupUser || !in_array($groupUser['role'],[1,2])){
  522. return warning(lang('system.notAuth'));
  523. }
  524. $text=lang('im.manageRedo');
  525. }
  526. }
  527. $message->content = str_encipher($text);
  528. $message->type = 'event';
  529. $message->is_undo = 1;
  530. //@的数据清空
  531. $message->at = '';
  532. $message->save();
  533. $info = $message->toArray();
  534. // $data = $info;
  535. $data['content'] = $fromUserName . $text;
  536. $data['sendTime'] = $createTime * 1000;
  537. $data['id'] = $info['id'];
  538. $data['from_user'] = $info['from_user'];
  539. $data['msg_id'] = $info['msg_id'];
  540. $data['status'] = $info['status'];
  541. $data['type'] = 'event';
  542. $data['is_last'] = $info['is_last'];
  543. $data['toContactId'] = $message['is_group'] == 1 ? $info['chat_identify'] : $toContactId;
  544. $data['isMobile'] = $this->request->isMobile() ? 1 : 0;
  545. wsSendMsg($toContactId, 'undoMessage', $data, $info['is_group']);
  546. if($info['is_group']==0){
  547. // 给自己也发一份推送,多端同步
  548. $data['content'] =lang('im.you'). $text;
  549. wsSendMsg($this->userInfo['user_id'], 'undoMessage', $data, $info['is_group']);
  550. }
  551. return success('');
  552. } else {
  553. return warning();
  554. }
  555. }
  556. // 删除消息
  557. public function removeMessage()
  558. {
  559. $param = $this->request->param();
  560. $id = $param['id'];
  561. $map = ['id' => $id];
  562. $message = Message::where($map)->find();
  563. if ($message) {
  564. $message->del_user = $this->userInfo['user_id'];
  565. if ($message['is_group'] == 1) {
  566. if ($message['del_user']) {
  567. $message->del_user .= ',' . $this->userInfo['user_id'];
  568. }
  569. } else {
  570. if ($message['del_user'] > 0) {
  571. $message->where($map)->delete();
  572. return success(lang('system.delOk'));
  573. }
  574. }
  575. $message->save();
  576. return success('');
  577. } else {
  578. return warning('');
  579. }
  580. }
  581. // 消息免打扰
  582. public function isNotice()
  583. {
  584. $param = $this->request->param();
  585. $user_id = $this->userInfo['user_id'];
  586. $id = $param['id'];
  587. if ($param['is_group'] == 1) {
  588. $group_id = explode('-', $param['id'])[1];
  589. GroupUser::update(['is_notice' => $param['is_notice']], ['user_id' => $user_id, 'group_id' => $group_id]);
  590. } else {
  591. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  592. $friend = Friend::where($map)->find();
  593. try {
  594. if ($friend) {
  595. $friend->is_notice = $param['is_notice'];
  596. $friend->save();
  597. } else {
  598. $info = [
  599. 'create_user' => $user_id,
  600. 'friend_user_id' => $id,
  601. 'is_notice' => $param['is_notice']
  602. ];
  603. Friend::create($info);
  604. }
  605. return success('');
  606. } catch (Exception $e) {
  607. return error($e->getMessage());
  608. }
  609. }
  610. wsSendMsg($user_id,"setIsNotice",['id'=>$id,'is_notice'=>$param['is_notice'],'is_group'=>$param['is_group']]);
  611. return success('');
  612. }
  613. // 设置聊天置顶
  614. public function setChatTop()
  615. {
  616. $param = $this->request->param();
  617. $user_id = $this->userInfo['user_id'];
  618. $is_group = $param['is_group'] ?: 0;
  619. $id = $param['id'];
  620. try {
  621. if ($is_group == 1) {
  622. $group_id = explode('-', $param['id'])[1];
  623. GroupUser::update(['is_top' => $param['is_top']], ['user_id' => $user_id, 'group_id' => $group_id]);
  624. } else {
  625. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  626. $friend = Friend::where($map)->find();
  627. if ($friend) {
  628. $friend->is_top = $param['is_top'];
  629. $friend->save();
  630. } else {
  631. $info = [
  632. 'create_user' => $user_id,
  633. 'friend_user_id' => $id,
  634. 'is_top' => $param['is_top']
  635. ];
  636. Friend::create($info);
  637. }
  638. }
  639. wsSendMsg($user_id,"setChatTop",['id'=>$id,'is_top'=>$param['is_top'],'is_group'=>$is_group]);
  640. return success('');
  641. } catch (Exception $e) {
  642. return error($e->getMessage());
  643. }
  644. }
  645. // 删除聊天
  646. public function delChat()
  647. {
  648. $param = $this->request->param();
  649. $user_id = $this->userInfo['user_id'];
  650. $is_group = $param['is_group'] ?: 0;
  651. $id = $param['id'];
  652. $data=[
  653. 'user_id'=>$user_id,
  654. 'is_group'=>$is_group,
  655. 'to_user'=>$id
  656. ];
  657. ChatDelog::create($data);
  658. ChatDelog::updateCache($user_id);
  659. return success('');
  660. }
  661. // 向用户发送消息
  662. public function sendToMsg(){
  663. $param=$this->request->param();
  664. $toContactId=$param['toContactId'];
  665. $type=$param['type'];
  666. $status=$param['status'];
  667. $event=$param['event'] ?? 'calling';
  668. if($event=='calling'){
  669. $status=3;
  670. }
  671. $sdp=$param['sdp'] ?? '';
  672. $iceCandidate=$param['iceCandidate'] ?? '';
  673. $callTime=$param['callTime'] ?? '';
  674. $msg_id=$param['msg_id'] ?? '';
  675. $id=$param['id'] ?? '';
  676. $code=($param['code'] ?? '') ?: 901;
  677. // 如果该用户不在线,则发送忙线
  678. Gateway::$registerAddress = config('gateway.registerAddress');
  679. if(!Gateway::isUidOnline($toContactId)){
  680. $toContactId=$this->userInfo['user_id'];
  681. $code=907;
  682. $event='busy';
  683. sleep(1);
  684. }
  685. switch($code){
  686. case 902:
  687. $content=lang('webRtc.cancel');
  688. break;
  689. case 903:
  690. $content=lang('webRtc.refuse');
  691. break;
  692. case 905:
  693. $content=lang('webRtc.notConnected');
  694. break;
  695. case 906:
  696. $content=lang('webRtc.duration',['time'=>date("i:s",$callTime)]);
  697. break;
  698. case 907:
  699. $content=lang('webRtc.busy');
  700. break;
  701. case 908:
  702. $content=lang('webRtc.other');
  703. break;
  704. default:
  705. $content=$type==1 ?lang('webRtc.video') : lang('webRtc.audio');
  706. break;
  707. }
  708. switch($event){
  709. case 'calling':
  710. $content=$type==1 ?lang('webRtc.video'): lang('webRtc.audio');
  711. break;
  712. case 'acceptRtc':
  713. $content=lang('webRtc.answer');
  714. break;
  715. case 'iceCandidate':
  716. $content=lang('webRtc.exchange');
  717. break;
  718. }
  719. $userInfo=$this->userInfo;
  720. $userInfo['id']=$userInfo['user_id'];
  721. $user = new User();
  722. $data=[
  723. 'id'=>$id,
  724. 'msg_id'=>$msg_id,
  725. 'sendTime'=>time()*1000,
  726. 'toContactId'=>$toContactId,
  727. 'content'=>$content,
  728. 'type'=>'webrtc',
  729. 'status'=>'succeed',
  730. 'is_group'=>0,
  731. 'is_read'=>0,
  732. 'fromUser'=>$userInfo,
  733. 'at'=>[],
  734. 'extends'=>[
  735. 'type'=>$type, //通话类型,1视频,0语音。
  736. 'status'=>$status, //,1拨打方,2接听方
  737. 'event'=>$event,
  738. 'callTime'=>$callTime,
  739. 'sdp'=>$sdp,
  740. 'code'=>$code, //通话状态:呼叫901,取消902,拒绝903,接听904,未接通905,接通后挂断906,忙线907,其他端操作908
  741. 'iceCandidate'=>$iceCandidate,
  742. 'isMobile'=>$this->request->isMobile() ? 1 : 0,
  743. ]
  744. ];
  745. if($event=='calling'){
  746. $chat_identify=chat_identify($userInfo['id'],$toContactId);
  747. $msg=[
  748. 'from_user'=>$userInfo['id'],
  749. 'to_user'=>$toContactId,
  750. 'id'=>$id,
  751. 'content'=>str_encipher($content),
  752. 'chat_identify'=>$chat_identify,
  753. 'create_time'=>time(),
  754. 'type'=>$data['type'],
  755. 'is_group'=>0,
  756. 'is_read'=>0,
  757. 'extends'=>$data['extends'],
  758. ];
  759. $message=new Message();
  760. $message->update(['is_last'=>0],['chat_identify'=>$chat_identify]);
  761. $message->save($msg);
  762. $msg_id=$message->msg_id;
  763. $data['msg_id']=$msg_id;
  764. // 将接收人设置为发送人才能定位到该消息
  765. $data['toContactId']=$userInfo['id'];
  766. $data['toUser']=$toContactId;
  767. }elseif($event=='hangup'){
  768. $message=Message::where(['id'=>$id])->find();
  769. if(!$message){
  770. return error(lang('webRtc.fail'));
  771. }
  772. if($message){
  773. $message->content=str_encipher($content);
  774. $extends=$message->extends;
  775. $extends['code']=$code;
  776. $extends['callTime']=$callTime;
  777. $message->extends=$extends;
  778. $message->save();
  779. }
  780. }
  781. wsSendMsg($toContactId,'webrtc',$data);
  782. $wsData=$data;
  783. if(in_array($event,['calling','acceptRtc','hangup'])){
  784. if(in_array($event,['acceptRtc','hangup'])){
  785. $data['extends']['event']='otherOpt'; //其他端操作
  786. }
  787. $data['toContactId']=$toContactId;
  788. $data['contactInfo']=$user->setContact($toContactId,0,'webrtc',$content) ? : [];
  789. wsSendMsg($userInfo['id'],'webrtc',$data);
  790. }
  791. return success('',$wsData);
  792. }
  793. // 修改密码
  794. public function editPassword()
  795. {
  796. if(env('app.demon_mode',false)){
  797. return warning(lang('system.demoMode'));
  798. }
  799. $user_id = $this->userInfo['user_id'];
  800. $user=User::find($user_id);
  801. if(!$user){
  802. return warning(lang('user.exist'));
  803. }
  804. $account=$user->account;
  805. $code=$this->request->param('code','');
  806. $originalPassword = $this->request->param('originalPassword', '');
  807. if($code){
  808. if(Cache::get($account)!=$code){
  809. return warning(lang('user.codeErr'));
  810. }
  811. }elseif($originalPassword){
  812. if(password_hash_tp($originalPassword,$user->salt)!= $user->password){
  813. return warning(lang('user.passErr'));
  814. }
  815. }else{
  816. return warning(lang('system.parameterError'));
  817. }
  818. try{
  819. $password = $this->request->param('password','');
  820. if($password){
  821. $salt=$user->salt;
  822. $user->password= password_hash_tp($password,$salt);
  823. }
  824. $user->save();
  825. return success(lang('system.editOk'));
  826. }catch (\Exception $e){
  827. return error(lang('system.editFail'));
  828. }
  829. }
  830. // 修改用户信息
  831. public function updateUserInfo(){
  832. try{
  833. $data = $this->request->param();
  834. $user=User::find($this->uid);
  835. if(!$user){
  836. return warning(lang('user.exist'));
  837. }
  838. // 接入用户名检测服务
  839. event('GreenText',['content'=>$data['realname'],'service'=>"nickname_detection"]);
  840. // 个性签名检测服务
  841. event('GreenText',['content'=>$data['motto'],'service'=>"comment_detection"]);
  842. $user->realname =$data['realname'];
  843. $user->email =$data['email'];
  844. $user->motto=$data['motto'];
  845. $user->sex =$data['sex'];
  846. $user->name_py= pinyin_sentence($data['realname']);
  847. $user->save();
  848. return success(lang('system.editOk'), $data);
  849. }catch (\Exception $e){
  850. return error($e->getMessage());
  851. }
  852. }
  853. // 修改账户
  854. public function editAccount(){
  855. if(env('app.demon_mode',false)){
  856. return warning(lang('system.demoMode'));
  857. }
  858. $code=$this->request->param('code','');
  859. $newCode=$this->request->param('newCode','');
  860. $account=$this->request->param('account','');
  861. $isUser=User::where('account',$account)->find();
  862. if($isUser){
  863. return warning(lang('user.already'));
  864. }
  865. $user=User::find($this->uid);
  866. if(!$user){
  867. return warning(lang('user.exist'));
  868. }
  869. // 如果已经认证过了,则需要验证验证码
  870. if($user->is_auth){
  871. if(Cache::get($user->account)!=$code){
  872. return warning(lang('user.codeErr'));
  873. }
  874. }
  875. if(Cache::get($account)!=$newCode){
  876. return warning(lang('user.newCodeErr'));
  877. }
  878. try{
  879. $user->account=$account;
  880. $user->is_auth=1;
  881. $user->save();
  882. return success(lang('system.editOk'));
  883. }catch (\Exception $e){
  884. return error(lang('system.editFail'));
  885. }
  886. }
  887. // 阅读@消息
  888. public function readAtMsg(){
  889. $param = $this->request->param();
  890. $atList=Db::name('message')->where(['chat_identify'=>$param['toContactId'],'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select();
  891. $atData=$this->recombileMsg($atList,false);
  892. Message::setAtRead($atData,$this->userInfo['user_id']);
  893. // $message=Message::where('msg_id',$param['msg_id'])->select();
  894. // $atList=($message ?? null) ? explode(',',$message): [];
  895. // // 两个数组取差集
  896. // $newAtList = array_diff($atList, [$this->userInfo['user_id']]);
  897. // Message::where('msg_id',$param['msg_id'])->update(['at'=>implode(',',$newAtList)]);
  898. return success('');
  899. }
  900. // 获取系统公告
  901. public function getAdminNotice(){
  902. $data=Message::where(['chat_identify'=>'admin_notice'])->order('msg_id desc')->find();
  903. $extends=$data['extends'] ?? [];
  904. if(!$extends){
  905. $extends['title']='';
  906. }
  907. $createTime=$data['create_time'] ?? 0;
  908. if(!$createTime){
  909. $extends['create_time']=$createTime;
  910. }else{
  911. $extends['create_time']=is_string($data['create_time']) ? strtotime($data['create_time']) : $data['create_time'];
  912. }
  913. return success('',$extends);
  914. }
  915. // 双向删除消息
  916. public function delMessage(){
  917. $param = $this->request->param();
  918. $id = $param['id'];
  919. if(!$this->globalConfig['chatInfo']['dbDelMsg']){
  920. return warning(lang('system.notAuth'));
  921. }
  922. $message = Message::where(['id' => $id])->find();
  923. if ($message) {
  924. if($message['from_user']!=$this->userInfo['user_id']){
  925. return warning(lang('system.notAuth'));
  926. }
  927. Message::where(['id' => $id])->delete();
  928. // 如果是最后一条消息,需要将上一条设置为最后一条
  929. if($message['is_last']){
  930. Message::where(['chat_identify'=>$message['chat_identify']])->order('msg_id desc')->limit(1)->update(['is_last'=>1]);
  931. }
  932. $toContactId = $message['to_user'];
  933. if ($message['is_group'] == 1) {
  934. $toContactId = explode('-', $message['chat_identify'])[1];
  935. }
  936. wsSendMsg($toContactId, 'delMessage', $message, $message['is_group']);
  937. return success('');
  938. } else {
  939. return warning(lang('im.exist'));
  940. }
  941. }
  942. }