MessageService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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'){
  137. $types[] = 2;
  138. }else if ($k == 'receive_account'){
  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:messages:barCount:{$userId}_{$type}";
  308. $data = RedisService::get($cacheKey);
  309. if($data){
  310. return $data;
  311. }
  312. $data1 = $this->getUnreadCount($userId, $type);
  313. $data1 = $data1? intval($data1) : 0;
  314. $data2 = ImChatService::make()->getUnreadCount($userId);
  315. $data = $data1+$data2;
  316. RedisService::set($cacheKey, $data, rand(3, 5));
  317. return $data;
  318. }
  319. /**
  320. * 获取
  321. * @param $userId
  322. * @return array|mixed
  323. */
  324. public function getUnreadCount($userId, $chatKey=0, $type=0)
  325. {
  326. $cacheKey = "caches:messages:unReadCount:{$userId}_{$chatKey}_{$type}";
  327. $data = RedisService::get($cacheKey);
  328. if(RedisService::exists($cacheKey)){
  329. return $data;
  330. }
  331. $where = ['to_uid'=> $userId,'status'=>1,'is_read'=>2,'mark'=>1];
  332. if($type>0){
  333. $where['type'] = $type;
  334. }
  335. if($chatKey){
  336. $where['chat_key'] = $chatKey;
  337. }
  338. $data = $this->model->where($where)->count('id');
  339. RedisService::set($cacheKey, $data, rand(3, 5));
  340. return $data;
  341. }
  342. /**
  343. * 验证发送消息或者内容是否有屏蔽词
  344. * @param $message 消息或内容
  345. * @param $type 是否返回屏蔽后内容:1-是
  346. * @return bool
  347. */
  348. public function filterMessage($message, $type = 1)
  349. {
  350. $filter = ConfigService::make()->getConfigByCode('chat_sensitive');
  351. $filter = !empty($filter)? explode('、', $filter) : [];
  352. $filter = array_filter($filter);
  353. if($filter){
  354. if($type != 2){
  355. foreach ($filter as $kw){
  356. $message = preg_replace("/{$kw}/",'***', $message);
  357. }
  358. }else{
  359. foreach ($filter as $kw){
  360. if(preg_match("/{$kw}/", $message)){
  361. return false;
  362. }
  363. }
  364. }
  365. // 手机号、邮箱、网址
  366. if($type == 1){
  367. $message = preg_replace("/^(1[3-9][0-9]{9})$/", '***',$message);
  368. $message = preg_replace("/([a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+)/is", '***',$message);
  369. $message = str_replace(['https:','http:','.com','.cn','.net','.top','www.'], '***',$message);
  370. $message = preg_replace("/([a-zA-Z0-9][a-zA-Z0-9\_]{6,20})/", '***',$message);
  371. $message = preg_replace("/\*{3}\*{1,}/",'***', $message);
  372. }
  373. }
  374. return $type == 3 && $message === '***'? '' : $message;
  375. }
  376. /**
  377. * 已读
  378. * @param $userId 用户ID
  379. * @param $chatKey 聊天窗口ID
  380. * @return bool
  381. */
  382. public function setRead($userId, $type=0, $chatKey='')
  383. {
  384. $where = ['to_uid'=> $userId];
  385. if($type){
  386. $where['type'] = $type;
  387. }
  388. if($chatKey){
  389. $where['chat_key'] = $chatKey;
  390. }
  391. $this->model->where($where)->update(['is_read'=>1,'update_time'=>time()]);
  392. // 清除缓存
  393. RedisService::keyDel("caches:messages:bar*");
  394. RedisService::keyDel("caches:messages:new_*");
  395. RedisService::keyDel("caches:messages:topList_{$userId}");
  396. return true;
  397. }
  398. /**
  399. * 隐藏
  400. * @param $userId
  401. * @param int $expire
  402. * @return mixed
  403. */
  404. public function setHide($userId, $type)
  405. {
  406. $this->model->where(['to_uid'=>$userId,'type'=> $type,'status'=> 1,'mark'=>1])
  407. ->update(['update_time'=>time(),'is_read'=>1,'status'=> 3]);
  408. // 清除缓存
  409. RedisService::keyDel("caches:messages:bar*");
  410. RedisService::keyDel("caches:messages:new_*");
  411. RedisService::keyDel("caches:messages:topList_{$userId}");
  412. return true;
  413. }
  414. /**
  415. * 清除历史
  416. * @param $userId
  417. * @param int $expire
  418. * @return mixed
  419. */
  420. public function clear($userId, $msgType)
  421. {
  422. $this->model->where(['to_uid'=>$userId,'type'=> $msgType,'mark'=>1])
  423. ->update(['update_time'=>time(),'mark'=>0]);
  424. // 清除缓存
  425. RedisService::keyDel("caches:messages:bar*");
  426. RedisService::keyDel("caches:messages:new_*");
  427. RedisService::keyDel("caches:messages:topList_{$userId}");
  428. return true;
  429. }
  430. /**
  431. * 清除历史
  432. * @param $userId
  433. * @param int $expire
  434. * @return mixed
  435. */
  436. public function clearAll($userId)
  437. {
  438. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  439. $expire = $expire>0? $expire : 60;
  440. $this->model->where(['to_uid'=>$userId,'mark'=>0])
  441. ->where('update_time','<', time() - 7*86400)
  442. ->delete();
  443. // 清除缓存
  444. RedisService::keyDel("caches:messages:bar*");
  445. RedisService::keyDel("caches:messages:new_*");
  446. RedisService::keyDel("caches:messages:topList_{$userId}");
  447. return $this->model->where(['to_uid'=>$userId,'mark'=>1])
  448. ->where('create_time','<', time() -$expire*86400)
  449. ->update(['update_time'=>time(),'mark'=>0]);
  450. }
  451. }