MessageService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Models\ImChatModel;
  13. use App\Models\MerchantModel;
  14. use App\Models\MessageModel;
  15. use App\Services\BaseService;
  16. use App\Services\ConfigService;
  17. use App\Services\RedisService;
  18. /**
  19. * 站内消息服务管理-服务类
  20. * @author laravel开发员
  21. * @since 2020/11/11
  22. * Class MessageService
  23. * @package App\Services\Api
  24. */
  25. class MessageService extends BaseService
  26. {
  27. // 静态对象
  28. protected static $instance = null;
  29. /**
  30. * 构造函数
  31. * @author laravel开发员
  32. * @since 2020/11/11
  33. * MessageService constructor.
  34. */
  35. public function __construct()
  36. {
  37. $this->model = new MessageModel();
  38. }
  39. /**
  40. * 静态入口
  41. * @return static|null
  42. */
  43. public static function make()
  44. {
  45. if (!self::$instance) {
  46. self::$instance = (new static());
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * 消息列表
  52. * @param $userId
  53. * @param $params
  54. * @param int $pageSize
  55. * @return array
  56. */
  57. public function getDataList($userId, $params, $pageSize=0)
  58. {
  59. $page = request()->post('page', 1);
  60. $cacheKey = "caches:messages:history_{$page}_".md5($userId.json_encode($params). $pageSize);
  61. $datas = RedisService::get($cacheKey);
  62. if($datas) {
  63. return $datas;
  64. }
  65. $where = ['a.status'=>1,'a.mark'=>1];
  66. $field = ['a.id','a.title','a.type','a.msg_type','a.chat_type','a.description','a.content','a.from_user_name','a.from_user_avatar','a.from_uid','a.to_user_name','a.to_user_avatar','a.to_uid','a.create_time','a.is_read','a.pages','a.status'];
  67. $datas = $this->model->from('message as a')
  68. ->leftJoin('member as b','b.id','=','a.from_uid')
  69. ->leftJoin('member as c','c.id','=','a.to_uid')
  70. ->where($where)
  71. ->where(function($query) use($params,$userId){
  72. $fromUid = isset($params['from_uid'])? intval($params['from_uid']) : 0;
  73. if($fromUid){
  74. $query->where('a.from_uid', $fromUid);
  75. }
  76. $type = isset($params['type'])? intval($params['type']) : 0;
  77. if($type){
  78. $query->where('a.type', $type);
  79. }
  80. if($type != 9){
  81. $query->where('a.to_uid', $userId);
  82. }
  83. $chatType = isset($params['chat_type'])? intval($params['chat_type']) : 0;
  84. if($chatType){
  85. $query->where('a.chat_type', $chatType);
  86. }
  87. $chatKey = isset($params['chat_key'])? trim($params['chat_key']) : '';
  88. if($chatKey){
  89. $query->where('a.chat_key', $chatKey);
  90. }
  91. })->select($field)
  92. ->orderBy('a.create_time','desc')
  93. ->orderBy('a.id','desc')
  94. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  95. $datas = $datas ? $datas->toArray() : [];
  96. if ($datas) {
  97. $ids = [];
  98. foreach ($datas['data'] as &$item) {
  99. $ids[] = $item['id'];
  100. $item['time_text'] = isset($item['create_time']) && $item['create_time']? dateForWeek($item['create_time']) : '';
  101. $item['content'] = $item['msg_type'] ==2? get_images_preview(json_decode($item['content'],true),'') : $item['content'];
  102. $item['from_user_avatar'] = $item['from_user_avatar']? get_image_url($item['from_user_avatar']) : get_image_url('/images/member/logo.png');
  103. $item['to_user_avatar'] = $item['to_user_avatar']? get_image_url($item['to_user_avatar']) : get_image_url('/images/member/logo.png');
  104. }
  105. unset($item);
  106. // 更新已读
  107. if($ids){
  108. $this->model->whereIn('id', $ids)->update(['is_read'=> 1,'update_time'=>time()]);
  109. }
  110. arsort($datas['data'], true);
  111. $datas['data'] = array_reverse($datas['data'], false);
  112. RedisService::set($cacheKey, $datas, rand(3,5));
  113. }
  114. return [
  115. 'list'=> isset($datas['data'])? $datas['data'] : [],
  116. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  117. 'pageSize'=>$pageSize
  118. ];
  119. }
  120. /**
  121. * 获取站内消息窗口列表
  122. * @param $userId
  123. * @return array|mixed
  124. */
  125. public function getGroupList($userId)
  126. {
  127. $cachekey = "caches:messages:topList_{$userId}";
  128. $datas = RedisService::get($cachekey);
  129. if($datas){
  130. return $datas;
  131. }
  132. $types = [1,4,5];
  133. $setting = MemberSettingService::make()->getSetting($userId);
  134. if($setting){
  135. foreach ($setting as $k => $v){
  136. if($k == 'receive_order' && $v==1){
  137. $types[] = 2;
  138. }else if ($k == 'receive_account' && $v==1){
  139. $types[] = 3;
  140. }
  141. }
  142. asort($types);
  143. }else{
  144. $types = [1,2,3,4,5];
  145. }
  146. $field = ['title','type','to_uid','description','is_read','create_time'];
  147. $datas = $this->model->where(['to_uid'=> $userId,'status'=>1,'mark'=>1])
  148. ->whereIn('type', $types)
  149. ->groupBy('type')
  150. ->orderBy('type','asc')
  151. ->orderBy('is_read','desc')
  152. ->orderBy('create_time','desc')
  153. ->select($field)
  154. ->get();
  155. $datas = $datas? $datas->toArray() : [];
  156. $total = 0;
  157. if($datas){
  158. $titles = [1=>'公告通知',2=>'订单通知',3=>'账户通知',4=>'客服通知',5=>'互动消息'];
  159. foreach($datas as &$item){
  160. $item['title'] = isset($titles[$item['type']])? $titles[$item['type']] : '消息通知';
  161. $data = $this->getNewMessage($item['type'],0, $userId);
  162. $item['description'] = isset($data['description']) && $data['description']? $data['description'] : (isset($data['content'])? mb_substr($data['content'],0,56,'utf-8').'...': lang('有新消息'));
  163. $item['create_time'] = isset($data['create_time']) && $data['create_time']? $data['create_time'] : '';
  164. $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
  165. $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  166. $unread = $this->getUnreadCount($userId,0, $item['type']);
  167. $item['unread'] = intval($unread);
  168. $total += intval($unread);
  169. }
  170. RedisService::set($cachekey, ['list'=>$datas,'total'=>$total,'types'=>$types], rand(3,5));
  171. }
  172. return ['list'=>$datas,'total'=> $total,'types'=>$types];
  173. }
  174. /**
  175. * 聊天分组消息
  176. * @param $userId
  177. * @param $params
  178. * @param int $pageSize
  179. * @return array
  180. */
  181. public function getDataListFromatKey($userId, $params, $pageSize=0)
  182. {
  183. $page = request()->post('page', 1);
  184. $cacheKey = "caches:m_chat:{$page}_".md5($userId.json_encode($params).$pageSize);
  185. $datas = RedisService::get($cacheKey);
  186. $data = isset($datas['data'])? $datas['data'] : [];
  187. if($datas && $data) {
  188. return [
  189. 'unread'=> isset($datas['unReadCount'])? $datas['unReadCount'] : 0,
  190. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  191. 'list'=> $data,
  192. 'pageSize'=> $pageSize,
  193. 'cache'=> true,
  194. ];
  195. }
  196. $where = ['a.type'=>9,'a.status'=> 1,'a.mark'=>1];
  197. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  198. $expire = $expire? $expire*86400 : 60*86400;
  199. $field = ['a.id','a.title','a.type','a.msg_type','a.chat_key','a.chat_type','a.description','a.content','a.from_user_name','a.from_user_avatar','a.from_uid','a.to_user_name','a.to_user_avatar','a.to_uid','a.create_time','a.is_read','a.status'];
  200. $datas = $this->model->from('message as a')
  201. ->where($where)
  202. ->where('a.chat_key','>', 0)
  203. ->where('a.create_time','>=', time() - $expire)
  204. ->where(function($query) use($params, $userId){
  205. $chatKey = isset($params['chat_key'])? trim($params['chat_key']) : '';
  206. if($chatKey){
  207. $query->where('a.chat_key', $chatKey);
  208. }
  209. $isRead = isset($params['is_read'])? intval($params['is_read']) : 0;
  210. if($isRead){
  211. $query->where('a.is_read', $isRead);
  212. }
  213. $chatType = isset($params['chat_type'])? intval($params['chat_type']) : 0;
  214. if($chatType){
  215. $query->where('a.chat_type', $chatType);
  216. }
  217. if($userId){
  218. $query->where(function($query) use($userId){
  219. $query->where(['a.from_uid'=>$userId])->orWhere(['a.to_uid'=>$userId]);
  220. });
  221. }
  222. })
  223. ->select($field)
  224. ->groupBy('chat_key')
  225. ->orderBy('a.create_time','desc')
  226. ->orderBy('a.id','desc')
  227. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  228. $datas = $datas ? $datas->toArray() : [];
  229. $unReadCount = 0;
  230. if ($datas) {
  231. foreach ($datas['data'] as &$item) {
  232. $item['from_user_avatar'] = isset($item['from_user_avatar']) && $item['from_user_avatar'] ? get_image_url($item['from_user_avatar']) : get_image_url('/images/member/logo.png');
  233. $item['to_user_avatar'] = isset($item['to_user_avatar']) && $item['to_user_avatar'] ? get_image_url($item['to_user_avatar']) : get_image_url('/images/member/logo.png');
  234. $data = $this->getNewMessage(0,$item['chat_key']);
  235. $item['description'] = isset($data['description']) && $data['description']? $data['description'] : (isset($data['content'])? mb_substr($data['content'],0,30,'utf-8'):lang('有新消息'));
  236. $item['create_time'] = isset($data['create_time']) && $data['create_time']? $data['create_time'] : '';
  237. $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
  238. $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  239. $item['unread'] = $this->getUnreadCount($userId, $item['chat_key'], 0);
  240. if($item['from_uid'] == $userId){
  241. $item['from_user_name'] = $item['to_user_name'];
  242. $item['from_user_avatar'] = $item['to_user_avatar'];
  243. $item['tuid'] = $item['to_uid'];
  244. }else{
  245. $item['tuid'] = $item['from_uid'];
  246. }
  247. $unReadCount += intval($item['unread']);
  248. }
  249. unset($item);
  250. $datas['unReadCount'] = $unReadCount;
  251. RedisService::set($cacheKey, $datas, rand(3, 5));
  252. }
  253. return [
  254. 'unread'=> $unReadCount,
  255. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  256. 'list'=> isset($datas['data'])? $datas['data'] : [],
  257. 'pageSize'=> $pageSize,
  258. 'cache'=> false,
  259. ];
  260. }
  261. /**
  262. * 获取最新消息
  263. * @param $chatKey
  264. * @return mixed
  265. */
  266. public function getNewMessage($type=0, $chatKey=0, $userId=0)
  267. {
  268. $cacheKey = "caches:messages:new_{$type}_{$chatKey}_{$userId}";
  269. $data = RedisService::get($cacheKey);
  270. if($data){
  271. return $data;
  272. }
  273. $where = ['status'=>1,'mark'=>1];
  274. if($type){
  275. $where['type'] = $type;
  276. }
  277. if($chatKey){
  278. $where['chat_key'] = $chatKey;
  279. }
  280. if($userId){
  281. $where['to_uid'] = $userId;
  282. }
  283. $data = $this->model->where($where)->select('id','title','description','msg_type','content','create_time')
  284. ->orderBy('create_time','desc')
  285. ->orderBy('id','desc')
  286. ->first();
  287. $data = $data? $data->toArray() : [];
  288. if($data){
  289. if($data['msg_type'] ==2){
  290. $data['description'] = '[图片]';
  291. } else if($data['msg_type'] == 3){
  292. $data['description'] = '[视频聊天]';
  293. } else if($data['msg_type'] == 4){
  294. $data['description'] = '[直播间分享]';
  295. }
  296. RedisService::set($cacheKey, $data, rand(3, 5));
  297. }
  298. return $data;
  299. }
  300. /**
  301. * 获取未读消息数量
  302. * @param $userId
  303. * @return array|mixed
  304. */
  305. public function getBarCount($userId, $type=0)
  306. {
  307. $cacheKey = "caches:barCount:{$userId}_{$type}";
  308. $data = RedisService::get($cacheKey);
  309. if($data){
  310. return $data;
  311. }
  312. $data = $this->getUnreadCount($userId,0, $type);
  313. RedisService::set($cacheKey, $data, rand(3, 5));
  314. return $data;
  315. }
  316. /**
  317. * 推送站内消息
  318. * @param $userId 用户ID
  319. * @param $title 标题
  320. * @param $message 消息内容
  321. * @param int $type 类型:1-公告,2-订单,3-账户,4-客服,5-动态
  322. * @return false
  323. */
  324. public function pushMessage($userId, $title, $message, $type=1, $fromUid=0)
  325. {
  326. $types = [4,5];
  327. $pushStatus = false;
  328. $datas = MemberSettingService::make()->getSetting($userId);
  329. if($datas){
  330. foreach ($datas as $k => $v){
  331. if($v==1){
  332. if($k == 'receive_app'){
  333. $pushStatus = true;
  334. $types[] = 1;
  335. }else if ($k == 'receive_order'){
  336. $types[] = 2;
  337. }else if ($k == 'receive_account'){
  338. $types[] = 3;
  339. }
  340. }
  341. }
  342. }else{
  343. $pushStatus = true;
  344. $types = [1,2,3,4,5];
  345. }
  346. if($userId && $pushStatus && in_array($type, $types)){
  347. $appName = ConfigService::make()->getConfigByCode('app_name', '星链社交');
  348. $log = [
  349. 'from_uid'=> $fromUid,
  350. 'to_uid'=> $userId,
  351. 'from_user_name'=> $appName,
  352. 'chat_type'=> 0,
  353. 'msg_type'=> 1,
  354. 'type'=> $type,
  355. 'title'=> $title,
  356. 'description'=> $title,
  357. 'content'=> $message,
  358. 'chat_key'=> "0{$userId}",
  359. 'create_time'=> time(),
  360. 'status'=> 1,
  361. 'mark'=> 1,
  362. ];
  363. return MessageModel::insert($log);
  364. }
  365. return false;
  366. }
  367. /**
  368. * 获取
  369. * @param $userId
  370. * @return array|mixed
  371. */
  372. public function getUnreadCount($userId, $chatKey=0, $type=0)
  373. {
  374. $cacheKey = "caches:messages:unReadCount:{$userId}_{$chatKey}_{$type}";
  375. $data = RedisService::get($cacheKey);
  376. if(RedisService::exists($cacheKey)){
  377. return $data;
  378. }
  379. $where = ['to_uid'=> $userId,'status'=>1,'is_read'=>2,'mark'=>1];
  380. if($type>0){
  381. $where['type'] = $type;
  382. }
  383. if($chatKey){
  384. $where['chat_key'] = $chatKey;
  385. }
  386. $data = $this->model->where($where)->count('id');
  387. RedisService::set($cacheKey, $data, rand(3, 5));
  388. return $data;
  389. }
  390. /**
  391. * 验证发送消息或者内容是否有屏蔽词
  392. * @param $message 消息或内容
  393. * @param $type 是否返回屏蔽后内容:1-是
  394. * @return bool
  395. */
  396. public function filterMessage($message, $type = 1)
  397. {
  398. $filter = ConfigService::make()->getConfigByCode('chat_sensitive');
  399. $filter = !empty($filter)? explode('、', $filter) : [];
  400. $filter = array_filter($filter);
  401. if($filter){
  402. if($type != 2){
  403. foreach ($filter as $kw){
  404. $message = preg_replace("/{$kw}/",'***', $message);
  405. }
  406. }else{
  407. foreach ($filter as $kw){
  408. if(preg_match("/{$kw}/", $message)){
  409. return false;
  410. }
  411. }
  412. }
  413. // 手机号、邮箱、网址
  414. if($type == 1){
  415. $message = preg_replace("/^(1[3-9][0-9]{9})$/", '***',$message);
  416. $message = preg_replace("/([a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+)/is", '***',$message);
  417. $message = str_replace(['https:','http:','.com','.cn','.net','.top','www.'], '***',$message);
  418. $message = preg_replace("/([a-zA-Z0-9][a-zA-Z0-9\_]{6,20})/", '***',$message);
  419. $message = preg_replace("/\*{3}\*{1,}/",'***', $message);
  420. }
  421. }
  422. return $type == 3 && $message === '***'? '' : $message;
  423. }
  424. /**
  425. * 已读
  426. * @param $userId 用户ID
  427. * @param $chatKey 聊天窗口ID
  428. * @return bool
  429. */
  430. public function setRead($userId, $type=0, $chatKey='')
  431. {
  432. $where = ['to_uid'=> $userId];
  433. if($type){
  434. $where['type'] = $type;
  435. }
  436. if($chatKey){
  437. $where['chat_key'] = $chatKey;
  438. }
  439. $this->model->where($where)->update(['is_read'=>1,'update_time'=>time()]);
  440. // 清除缓存
  441. RedisService::keyDel("caches:messages:bar*");
  442. RedisService::keyDel("caches:messages:new_*");
  443. RedisService::keyDel("caches:messages:topList_{$userId}");
  444. return true;
  445. }
  446. /**
  447. * 隐藏
  448. * @param $userId
  449. * @param int $expire
  450. * @return mixed
  451. */
  452. public function setHide($userId, $type)
  453. {
  454. $this->model->where(['to_uid'=>$userId,'type'=> $type,'status'=> 1,'mark'=>1])
  455. ->update(['update_time'=>time(),'is_read'=>1,'status'=> 3]);
  456. // 清除缓存
  457. RedisService::keyDel("caches:messages:bar*");
  458. RedisService::keyDel("caches:messages:new_*");
  459. RedisService::keyDel("caches:messages:topList_{$userId}");
  460. return true;
  461. }
  462. /**
  463. * 清除历史
  464. * @param $userId
  465. * @param int $expire
  466. * @return mixed
  467. */
  468. public function clear($userId, $msgType)
  469. {
  470. $this->model->where(['to_uid'=>$userId,'type'=> $msgType,'mark'=>1])
  471. ->update(['update_time'=>time(),'mark'=>0]);
  472. // 清除缓存
  473. RedisService::keyDel("caches:messages:bar*");
  474. RedisService::keyDel("caches:messages:new_*");
  475. RedisService::keyDel("caches:messages:topList_{$userId}");
  476. return true;
  477. }
  478. /**
  479. * 清除历史
  480. * @param $userId
  481. * @param int $expire
  482. * @return mixed
  483. */
  484. public function clearAll($userId)
  485. {
  486. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  487. $expire = $expire>0? $expire : 60;
  488. $this->model->where(['to_uid'=>$userId,'mark'=>0])
  489. ->where('update_time','<', time() - 7*86400)
  490. ->delete();
  491. // 清除缓存
  492. RedisService::keyDel("caches:messages:bar*");
  493. RedisService::keyDel("caches:messages:new_*");
  494. RedisService::keyDel("caches:messages:topList_{$userId}");
  495. return $this->model->where(['to_uid'=>$userId,'mark'=>1])
  496. ->where('create_time','<', time() -$expire*86400)
  497. ->update(['update_time'=>time(),'mark'=>0]);
  498. }
  499. }