MessageService.php 17 KB

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