MessageService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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['content']? json_decode($item['content'], true) : [];
  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. RedisService::set($cacheKey, $datas, rand(3,5));
  111. }
  112. return [
  113. 'list'=> isset($datas['data'])? $datas['data'] : [],
  114. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  115. 'pageSize'=>$pageSize
  116. ];
  117. }
  118. /**
  119. * 获取站内消息窗口列表
  120. * @param $userId
  121. * @return array|mixed
  122. */
  123. public function getGroupList($userId)
  124. {
  125. $cachekey = "caches:messages:topList_{$userId}";
  126. $datas = RedisService::get($cachekey);
  127. if($datas){
  128. return $datas;
  129. }
  130. $types = [1,4,5];
  131. $setting = MemberSettingService::make()->getSetting($userId);
  132. if($setting){
  133. foreach ($setting as $k => $v){
  134. if($k == 'receive_order'){
  135. $types[] = 2;
  136. }else if ($k == 'receive_account'){
  137. $types[] = 3;
  138. }
  139. }
  140. asort($types);
  141. }else{
  142. $types = [1,2,3,4,5];
  143. }
  144. $field = ['title','type','to_uid','description','is_read','create_time'];
  145. $datas = $this->model->where(['to_uid'=> $userId,'status'=>1,'mark'=>1])
  146. ->whereIn('type', $types)
  147. ->groupBy('type')
  148. ->orderBy('type','asc')
  149. ->orderBy('is_read','desc')
  150. ->orderBy('create_time','desc')
  151. ->select($field)
  152. ->get();
  153. $datas = $datas? $datas->toArray() : [];
  154. $total = 0;
  155. if($datas){
  156. $titles = [1=>'公告通知',2=>'订单通知',3=>'账户通知',4=>'客服通知',5=>'互动消息'];
  157. foreach($datas as &$item){
  158. $item['title'] = isset($titles[$item['type']])? $titles[$item['type']] : '消息通知';
  159. $data = $this->getNewMessage($item['type'],0, $userId);
  160. $item['description'] = isset($data['description']) && $data['description']? $data['description'] : (isset($data['message'])? mb_substr($data['message'],0,20,'utf-8'): lang('有新消息'));
  161. $item['create_time'] = isset($data['create_time']) && $data['create_time']? $data['create_time'] : '';
  162. $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
  163. $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  164. $unread = $this->getUnreadCount($userId,0, $item['type']);
  165. $item['unread'] = intval($unread);
  166. $total += intval($unread);
  167. }
  168. RedisService::set($cachekey, ['list'=>$datas,'total'=>$total,'types'=>$types], rand(3,5));
  169. }
  170. return ['list'=>$datas,'total'=> $total,'types'=>$types];
  171. }
  172. /**
  173. * 聊天分组消息
  174. * @param $userId
  175. * @param $params
  176. * @param int $pageSize
  177. * @return array
  178. */
  179. public function getDataListFromatKey($userId, $params, $pageSize=0)
  180. {
  181. $page = request()->post('page', 1);
  182. $cacheKey = "caches:message:chat_{$page}_".md5($userId.json_encode($params).$pageSize);
  183. $datas = RedisService::get($cacheKey);
  184. $data = isset($datas['data'])? $datas['data'] : [];
  185. if($datas && $data) {
  186. return [
  187. 'unread'=> isset($datas['unReadCount'])? $datas['unReadCount'] : 0,
  188. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  189. 'list'=> $data,
  190. 'pageSize'=> $pageSize,
  191. 'cache'=> true,
  192. ];
  193. }
  194. $where = ['a.type'=>9,'a.status'=> 1,'a.mark'=>1];
  195. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  196. $expire = $expire? $expire*86400 : 60*86400;
  197. $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'];
  198. $datas = $this->model->from('imchat as a')
  199. ->where($where)
  200. ->where('a.chat_key','>', 0)
  201. ->where('a.create_time','>=', time() - $expire)
  202. ->where(function($query) use($params){
  203. $chatKey = isset($params['chat_key'])? trim($params['chat_key']) : '';
  204. if($chatKey){
  205. $query->where('a.chat_key', $chatKey);
  206. }
  207. $isRead = isset($params['is_read'])? intval($params['is_read']) : 0;
  208. if($isRead){
  209. $query->where('a.is_read', $isRead);
  210. }
  211. $chatType = isset($params['chat_type'])? intval($params['chat_type']) : 0;
  212. if($chatType){
  213. $query->where('a.chat_type', $chatType);
  214. }
  215. })
  216. ->select($field)
  217. ->groupBy('chat_key')
  218. ->orderBy('a.create_time','desc')
  219. ->orderBy('a.id','desc')
  220. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  221. $datas = $datas ? $datas->toArray() : [];
  222. $unReadCount = 0;
  223. if ($datas) {
  224. foreach ($datas['data'] as &$item) {
  225. $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');
  226. $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');
  227. $data = $this->getNewMessage(0,$item['chat_key']);
  228. $item['description'] = isset($data['description']) && $data['description']? $data['description'] : (isset($data['message'])? mb_substr($data['message'],0,20,'utf-8'):lang('有新消息'));
  229. $item['create_time'] = isset($data['create_time']) && $data['create_time']? $data['create_time'] : '';
  230. $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
  231. $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  232. $item['unread'] = $this->getUnreadCount($userId, $item['chat_key'], 0);
  233. $unReadCount += intval($item['unread']);
  234. }
  235. unset($item);
  236. $datas['unReadCount'] = $unReadCount;
  237. RedisService::set($cacheKey, $datas, rand(3, 5));
  238. }
  239. return [
  240. 'unread'=> $unReadCount,
  241. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  242. 'list'=> isset($datas['data'])? $datas['data'] : [],
  243. 'pageSize'=> $pageSize,
  244. 'cache'=> false,
  245. ];
  246. }
  247. /**
  248. * 获取最新消息
  249. * @param $chatKey
  250. * @return mixed
  251. */
  252. public function getNewMessage($type=0, $chatKey=0, $userId=0)
  253. {
  254. $cacheKey = "caches:messages:new_{$type}_{$chatKey}_{$userId}";
  255. $data = RedisService::get($cacheKey);
  256. if($data){
  257. return $data;
  258. }
  259. $where = ['status'=>1,'mark'=>1];
  260. if($type){
  261. $where['type'] = $type;
  262. }
  263. if($chatKey){
  264. $where['chat_key'] = $chatKey;
  265. }
  266. if($userId){
  267. $where['to_uid'] = $userId;
  268. }
  269. $data = $this->model->where($where)->select('id','description','content','create_time')
  270. ->orderBy('create_time','desc')
  271. ->orderBy('id','desc')
  272. ->first();
  273. $data = $data? $data->toArray() : [];
  274. if($data){
  275. RedisService::set($cacheKey, $data, rand(3, 5));
  276. }
  277. return $data;
  278. }
  279. /**
  280. * 获取未读消息数量
  281. * @param $userId
  282. * @return array|mixed
  283. */
  284. public function getBarCount($userId, $type=0)
  285. {
  286. $cacheKey = "caches:messages:barCount:{$userId}_{$type}";
  287. $data = RedisService::get($cacheKey);
  288. if($data){
  289. return $data;
  290. }
  291. $data1 = $this->getUnreadCount($userId, $type);
  292. $data1 = $data1? intval($data1) : 0;
  293. $data2 = ImChatService::make()->getUnreadCount($userId);
  294. $data = $data1+$data2;
  295. RedisService::set($cacheKey, $data, rand(3, 5));
  296. return $data;
  297. }
  298. /**
  299. * 获取
  300. * @param $userId
  301. * @return array|mixed
  302. */
  303. public function getUnreadCount($userId, $chatKey=0, $type=0)
  304. {
  305. $cacheKey = "caches:messages:unReadCount:{$userId}_{$chatKey}_{$type}";
  306. $data = RedisService::get($cacheKey);
  307. if(RedisService::exists($cacheKey)){
  308. return $data;
  309. }
  310. $where = ['to_uid'=> $userId,'status'=>1,'is_read'=>2,'mark'=>1];
  311. if($type>0){
  312. $where['type'] = $type;
  313. }
  314. if($chatKey){
  315. $where['chat_key'] = $chatKey;
  316. }
  317. $data = $this->model->where($where)->count('id');
  318. RedisService::set($cacheKey, $data, rand(3, 5));
  319. return $data;
  320. }
  321. /**
  322. * 验证发送消息或者内容是否有屏蔽词
  323. * @param $message 消息或内容
  324. * @param $type 是否返回屏蔽后内容:1-是
  325. * @return bool
  326. */
  327. public function filterMessage($message, $type = 1)
  328. {
  329. $filter = ConfigService::make()->getConfigByCode('chat_sensitive');
  330. $filter = !empty($filter)? explode('、', $filter) : [];
  331. $filter = array_filter($filter);
  332. if($filter){
  333. if($type != 2){
  334. foreach ($filter as $kw){
  335. $message = preg_replace("/{$kw}/",'***', $message);
  336. }
  337. }else{
  338. foreach ($filter as $kw){
  339. if(preg_match("/{$kw}/", $message)){
  340. return false;
  341. }
  342. }
  343. }
  344. // 手机号、邮箱、网址
  345. if($type == 1){
  346. $message = preg_replace("/^(1[3-9][0-9]{9})$/", '***',$message);
  347. $message = preg_replace("/([a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+)/is", '***',$message);
  348. $message = str_replace(['https:','http:','.com','.cn','.net','.top','www.'], '***',$message);
  349. $message = preg_replace("/([a-zA-Z0-9][a-zA-Z0-9\_]{6,20})/", '***',$message);
  350. $message = preg_replace("/\*{3}\*{1,}/",'***', $message);
  351. }
  352. }
  353. return $type == 3 && $message === '***'? '' : $message;
  354. }
  355. /**
  356. * 已读
  357. * @param $userId 用户ID
  358. * @param $chatKey 聊天窗口ID
  359. * @return bool
  360. */
  361. public function setRead($userId, $type=0, $chatKey='')
  362. {
  363. $where = ['to_uid'=> $userId];
  364. if($type){
  365. $where['type'] = $type;
  366. }
  367. if($chatKey){
  368. $where['chat_key'] = $chatKey;
  369. }
  370. $this->model->where($where)->update(['is_read'=>1,'update_time'=>time()]);
  371. // 清除缓存
  372. RedisService::keyDel("caches:messages:bar*");
  373. RedisService::keyDel("caches:messages:new_*");
  374. RedisService::keyDel("caches:messages:topList_{$userId}");
  375. return true;
  376. }
  377. /**
  378. * 隐藏
  379. * @param $userId
  380. * @param int $expire
  381. * @return mixed
  382. */
  383. public function setHide($userId, $type)
  384. {
  385. $this->model->where(['to_uid'=>$userId,'type'=> $type,'status'=> 1,'mark'=>1])
  386. ->update(['update_time'=>time(),'is_read'=>1,'status'=> 3]);
  387. // 清除缓存
  388. RedisService::keyDel("caches:messages:bar*");
  389. RedisService::keyDel("caches:messages:new_*");
  390. RedisService::keyDel("caches:messages:topList_{$userId}");
  391. return true;
  392. }
  393. /**
  394. * 清除历史
  395. * @param $userId
  396. * @param int $expire
  397. * @return mixed
  398. */
  399. public function clear($userId, $msgType)
  400. {
  401. $this->model->where(['to_uid'=>$userId,'type'=> $msgType,'mark'=>1])
  402. ->update(['update_time'=>time(),'mark'=>0]);
  403. // 清除缓存
  404. RedisService::keyDel("caches:messages:bar*");
  405. RedisService::keyDel("caches:messages:new_*");
  406. RedisService::keyDel("caches:messages:topList_{$userId}");
  407. return true;
  408. }
  409. /**
  410. * 清除历史
  411. * @param $userId
  412. * @param int $expire
  413. * @return mixed
  414. */
  415. public function clearAll($userId)
  416. {
  417. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  418. $expire = $expire>0? $expire : 60;
  419. $this->model->where(['to_uid'=>$userId,'mark'=>0])
  420. ->where('update_time','<', time() - 7*86400)
  421. ->delete();
  422. // 清除缓存
  423. RedisService::keyDel("caches:messages:bar*");
  424. RedisService::keyDel("caches:messages:new_*");
  425. RedisService::keyDel("caches:messages:topList_{$userId}");
  426. return $this->model->where(['to_uid'=>$userId,'mark'=>1])
  427. ->where('create_time','<', time() -$expire*86400)
  428. ->update(['update_time'=>time(),'mark'=>0]);
  429. }
  430. }