MessageService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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['message'])? mb_substr($data['message'],0,20,'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:message: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.chat_key','a.from_user_id','a.to_user_id','a.msg_type','a.create_time','a.video_time','a.is_connect','a.is_read','a.from_is_show','a.to_is_show','a.status','b.avatar as from_avatar','b.nickname as from_nickname','c.avatar as to_avatar','c.nickname as to_nickname'];
  200. $datas = $this->model->from('imchat as a')
  201. ->where($where)
  202. ->where('a.chat_key','>', 0)
  203. ->where('a.create_time','>=', time() - $expire)
  204. ->where(function($query) use($params){
  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. })
  218. ->select($field)
  219. ->groupBy('chat_key')
  220. ->orderBy('a.create_time','desc')
  221. ->orderBy('a.id','desc')
  222. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  223. $datas = $datas ? $datas->toArray() : [];
  224. $unReadCount = 0;
  225. if ($datas) {
  226. foreach ($datas['data'] as &$item) {
  227. $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');
  228. $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');
  229. $data = $this->getNewMessage(0,$item['chat_key']);
  230. $item['description'] = isset($data['description']) && $data['description']? $data['description'] : (isset($data['message'])? mb_substr($data['message'],0,20,'utf-8'):lang('有新消息'));
  231. $item['create_time'] = isset($data['create_time']) && $data['create_time']? $data['create_time'] : '';
  232. $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
  233. $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  234. $item['unread'] = $this->getUnreadCount($userId, $item['chat_key'], 0);
  235. $unReadCount += intval($item['unread']);
  236. }
  237. unset($item);
  238. $datas['unReadCount'] = $unReadCount;
  239. RedisService::set($cacheKey, $datas, rand(3, 5));
  240. }
  241. return [
  242. 'unread'=> $unReadCount,
  243. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  244. 'list'=> isset($datas['data'])? $datas['data'] : [],
  245. 'pageSize'=> $pageSize,
  246. 'cache'=> false,
  247. ];
  248. }
  249. /**
  250. * 获取最新消息
  251. * @param $chatKey
  252. * @return mixed
  253. */
  254. public function getNewMessage($type=0, $chatKey=0, $userId=0)
  255. {
  256. $cacheKey = "caches:messages:new_{$type}_{$chatKey}_{$userId}";
  257. $data = RedisService::get($cacheKey);
  258. if($data){
  259. return $data;
  260. }
  261. $where = ['status'=>1,'mark'=>1];
  262. if($type){
  263. $where['type'] = $type;
  264. }
  265. if($chatKey){
  266. $where['chat_key'] = $chatKey;
  267. }
  268. if($userId){
  269. $where['to_uid'] = $userId;
  270. }
  271. $data = $this->model->where($where)->select('id','description','msg_type','content','create_time')
  272. ->orderBy('create_time','desc')
  273. ->orderBy('id','desc')
  274. ->first();
  275. $data = $data? $data->toArray() : [];
  276. if($data){
  277. if($data['msg_type'] ==2){
  278. $data['description'] = '[图片]';
  279. } else if($data['msg_type'] == 3){
  280. $data['description'] = '[视频聊天]';
  281. } else if($data['msg_type'] == 4){
  282. $data['description'] = '[直播间分享]';
  283. }
  284. RedisService::set($cacheKey, $data, rand(3, 5));
  285. }
  286. return $data;
  287. }
  288. /**
  289. * 获取未读消息数量
  290. * @param $userId
  291. * @return array|mixed
  292. */
  293. public function getBarCount($userId, $type=0)
  294. {
  295. $cacheKey = "caches:messages:barCount:{$userId}_{$type}";
  296. $data = RedisService::get($cacheKey);
  297. if($data){
  298. return $data;
  299. }
  300. $data1 = $this->getUnreadCount($userId, $type);
  301. $data1 = $data1? intval($data1) : 0;
  302. $data2 = ImChatService::make()->getUnreadCount($userId);
  303. $data = $data1+$data2;
  304. RedisService::set($cacheKey, $data, rand(3, 5));
  305. return $data;
  306. }
  307. /**
  308. * 获取
  309. * @param $userId
  310. * @return array|mixed
  311. */
  312. public function getUnreadCount($userId, $chatKey=0, $type=0)
  313. {
  314. $cacheKey = "caches:messages:unReadCount:{$userId}_{$chatKey}_{$type}";
  315. $data = RedisService::get($cacheKey);
  316. if(RedisService::exists($cacheKey)){
  317. return $data;
  318. }
  319. $where = ['to_uid'=> $userId,'status'=>1,'is_read'=>2,'mark'=>1];
  320. if($type>0){
  321. $where['type'] = $type;
  322. }
  323. if($chatKey){
  324. $where['chat_key'] = $chatKey;
  325. }
  326. $data = $this->model->where($where)->count('id');
  327. RedisService::set($cacheKey, $data, rand(3, 5));
  328. return $data;
  329. }
  330. /**
  331. * 验证发送消息或者内容是否有屏蔽词
  332. * @param $message 消息或内容
  333. * @param $type 是否返回屏蔽后内容:1-是
  334. * @return bool
  335. */
  336. public function filterMessage($message, $type = 1)
  337. {
  338. $filter = ConfigService::make()->getConfigByCode('chat_sensitive');
  339. $filter = !empty($filter)? explode('、', $filter) : [];
  340. $filter = array_filter($filter);
  341. if($filter){
  342. if($type != 2){
  343. foreach ($filter as $kw){
  344. $message = preg_replace("/{$kw}/",'***', $message);
  345. }
  346. }else{
  347. foreach ($filter as $kw){
  348. if(preg_match("/{$kw}/", $message)){
  349. return false;
  350. }
  351. }
  352. }
  353. // 手机号、邮箱、网址
  354. if($type == 1){
  355. $message = preg_replace("/^(1[3-9][0-9]{9})$/", '***',$message);
  356. $message = preg_replace("/([a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+)/is", '***',$message);
  357. $message = str_replace(['https:','http:','.com','.cn','.net','.top','www.'], '***',$message);
  358. $message = preg_replace("/([a-zA-Z0-9][a-zA-Z0-9\_]{6,20})/", '***',$message);
  359. $message = preg_replace("/\*{3}\*{1,}/",'***', $message);
  360. }
  361. }
  362. return $type == 3 && $message === '***'? '' : $message;
  363. }
  364. /**
  365. * 已读
  366. * @param $userId 用户ID
  367. * @param $chatKey 聊天窗口ID
  368. * @return bool
  369. */
  370. public function setRead($userId, $type=0, $chatKey='')
  371. {
  372. $where = ['to_uid'=> $userId];
  373. if($type){
  374. $where['type'] = $type;
  375. }
  376. if($chatKey){
  377. $where['chat_key'] = $chatKey;
  378. }
  379. $this->model->where($where)->update(['is_read'=>1,'update_time'=>time()]);
  380. // 清除缓存
  381. RedisService::keyDel("caches:messages:bar*");
  382. RedisService::keyDel("caches:messages:new_*");
  383. RedisService::keyDel("caches:messages:topList_{$userId}");
  384. return true;
  385. }
  386. /**
  387. * 隐藏
  388. * @param $userId
  389. * @param int $expire
  390. * @return mixed
  391. */
  392. public function setHide($userId, $type)
  393. {
  394. $this->model->where(['to_uid'=>$userId,'type'=> $type,'status'=> 1,'mark'=>1])
  395. ->update(['update_time'=>time(),'is_read'=>1,'status'=> 3]);
  396. // 清除缓存
  397. RedisService::keyDel("caches:messages:bar*");
  398. RedisService::keyDel("caches:messages:new_*");
  399. RedisService::keyDel("caches:messages:topList_{$userId}");
  400. return true;
  401. }
  402. /**
  403. * 清除历史
  404. * @param $userId
  405. * @param int $expire
  406. * @return mixed
  407. */
  408. public function clear($userId, $msgType)
  409. {
  410. $this->model->where(['to_uid'=>$userId,'type'=> $msgType,'mark'=>1])
  411. ->update(['update_time'=>time(),'mark'=>0]);
  412. // 清除缓存
  413. RedisService::keyDel("caches:messages:bar*");
  414. RedisService::keyDel("caches:messages:new_*");
  415. RedisService::keyDel("caches:messages:topList_{$userId}");
  416. return true;
  417. }
  418. /**
  419. * 清除历史
  420. * @param $userId
  421. * @param int $expire
  422. * @return mixed
  423. */
  424. public function clearAll($userId)
  425. {
  426. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  427. $expire = $expire>0? $expire : 60;
  428. $this->model->where(['to_uid'=>$userId,'mark'=>0])
  429. ->where('update_time','<', time() - 7*86400)
  430. ->delete();
  431. // 清除缓存
  432. RedisService::keyDel("caches:messages:bar*");
  433. RedisService::keyDel("caches:messages:new_*");
  434. RedisService::keyDel("caches:messages:topList_{$userId}");
  435. return $this->model->where(['to_uid'=>$userId,'mark'=>1])
  436. ->where('create_time','<', time() -$expire*86400)
  437. ->update(['update_time'=>time(),'mark'=>0]);
  438. }
  439. }