MessageService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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\MessageModel;
  13. use App\Services\BaseService;
  14. use App\Services\ConfigService;
  15. use App\Services\RedisService;
  16. /**
  17. * 消息服务-服务类
  18. * @author laravel开发员
  19. * @since 2020/11/11
  20. * @package App\Services\Api
  21. */
  22. class MessageService extends BaseService
  23. {
  24. // 静态对象
  25. protected static $instance = null;
  26. /**
  27. * 构造函数
  28. * @author laravel开发员
  29. * @since 2020/11/11
  30. * NoticeService constructor.
  31. */
  32. public function __construct()
  33. {
  34. $this->model = new MessageModel();
  35. }
  36. /**
  37. * 静态入口
  38. */
  39. public static function make()
  40. {
  41. if (!self::$instance) {
  42. self::$instance = new static();
  43. }
  44. return self::$instance;
  45. }
  46. /**
  47. * @param $params
  48. * @param int $pageSize
  49. * @return array
  50. */
  51. public function getDataList($params, $pageSize = 20)
  52. {
  53. $query = $this->getQuery($params);
  54. $list = $query->select(['a.*'])
  55. ->orderBy('a.create_time','desc')
  56. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  57. $list = $list? $list->toArray() :[];
  58. if($list){
  59. foreach($list['data'] as &$item){
  60. $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H.i.s') : '';
  61. $item['time_text'] = $item['create_time']? dateFormat($item['create_time']) : '';
  62. $msgType = $item['msg_type']? $item['msg_type'] : 1;
  63. if($msgType == 1 || $msgType == 3){
  64. $item['content'] = format_message($item['content']);
  65. }else if($msgType==2){
  66. $item['content'] = $item['content']? get_image_url($item['content']) : '';
  67. }else if($msgType == 4){
  68. $item['content'] = $item['content']? json_decode($item['content'], true) : [];
  69. }
  70. if(isset($item['from_user']) && $item['from_user']){
  71. $item['from_user_name'] = $item['from_user']['realname']? $item['from_user']['realname'] : '用户'.$item['from_uid'];
  72. $item['from_user_avatar'] = $item['from_user']['avatar']? get_image_url($item['from_user']['avatar']) : get_image_url('/images/member/logo.png');
  73. }else if($item['from_uid'] <=1){
  74. $item['from_user_name'] = '客服';
  75. $item['from_user_avatar'] = get_image_url('/images/member/custom.png');
  76. }
  77. if(isset($item['to_user']) && $item['to_user']){
  78. $item['to_user_name'] = $item['to_user']['realname']? $item['to_user']['realname'] : '用户'.$item['to_uid'];
  79. $item['to_user_avatar'] = $item['to_user']['avatar']? get_image_url($item['to_user']['avatar']) : get_image_url('/images/member/logo.png');
  80. }else if($item['to_uid'] <=1){
  81. $item['to_user_name'] = '客服';
  82. $item['to_user_avatar'] = get_image_url('/images/member/custom.png');
  83. }
  84. }
  85. if(count($list['data'])) {
  86. $this->model->where(['chat_key' => $list['data'][0]['chat_key'], 'is_read' => 2, 'mark' => 1])->where('id', '<=', $list['data'][0]['id'])->update(['is_read' => 1, 'update_time' => time()]);
  87. RedisService::keyDel("caches:messages:unread_count*");
  88. }
  89. }
  90. return [
  91. 'pageSize'=> $pageSize,
  92. 'total'=>isset($list['total'])? $list['total'] : 0,
  93. 'list'=> isset($list['data'])? array_reverse($list['data']) : []
  94. ];
  95. }
  96. /**
  97. * 查询
  98. * @param $params
  99. * @return mixed
  100. */
  101. public function getQuery($params)
  102. {
  103. $where = ['a.mark' => 1];
  104. $status = isset($params['status'])? $params['status'] : 0;
  105. $type = isset($params['type'])? $params['type'] : 0;
  106. if($status>0){
  107. $where['a.status'] = $status;
  108. }
  109. if($type>0){
  110. $where['a.type'] = $type;
  111. }
  112. return $this->model->with(['fromUser','toUser'])->from('message as a')
  113. ->where($where)
  114. ->where(function ($query) use($params){
  115. $keyword = isset($params['keyword'])? $params['keyword'] : '';
  116. if($keyword){
  117. $query->where('a.title','like',"%{$keyword}%");
  118. }
  119. $fromUserId= isset($params['from_uid'])? intval($params['from_uid']) : 0;
  120. if($fromUserId>0){
  121. $query->where('a.from_uid', $fromUserId);
  122. }
  123. $toUserId= isset($params['to_uid'])? intval($params['to_uid']) : 0;
  124. if($fromUserId>0){
  125. $query->where('a.to_uid', $toUserId);
  126. }
  127. $isRead= isset($params['is_read'])? intval($params['is_read']) : 0;
  128. if($isRead>0){
  129. $query->where('a.is_read', $isRead);
  130. }
  131. }) ->where(function ($query) use($params){
  132. $userId = isset($params['user_id'])? intval($params['user_id']) : 0;
  133. if($userId>0){
  134. $query->where('a.from_uid',$userId)->orWhere('a.to_uid', $userId);
  135. }
  136. });
  137. }
  138. /**
  139. * 消息分类数据
  140. * @param $userId
  141. * @return array|array[]|mixed
  142. */
  143. public function getIndexList($userId)
  144. {
  145. $cacheKey = "caches:message:index_{$userId}";
  146. $datas = RedisService::get($cacheKey);
  147. if($datas){
  148. return $datas;
  149. }
  150. $datas = [
  151. 6=>['id'=>6,'code'=>'trade','title'=>'交易通知','count'=>0],
  152. 5=>['id'=>5,'code'=>'activity','title'=>'活动通知','count'=>0],
  153. 4=>['id'=>4,'code'=>'love','title'=>'互动通知','count'=>0],
  154. 2=>['id'=>2,'code'=>'notice','title'=>'系统消息','count'=>0],
  155. 1=>['id'=>1,'code'=>'custom','title'=>'客服消息','count'=>0],
  156. 3=>['id'=>3,'code'=>'service','title'=>'服务通知','count'=>0],
  157. ];
  158. $counts = $this->model->where(['to_uid'=>$userId,'status'=>1,'mark'=>1])
  159. ->selectRaw('count(id) as count,type')
  160. ->groupBy('type')
  161. ->get();
  162. $counts = $counts?$counts->toArray() :[];
  163. if($counts){
  164. foreach ($counts as $item){
  165. $type = isset($item['type'])?$item['type']:0;
  166. if(isset($datas[$type])){
  167. $datas[$type]['count'] = isset($item['count'])?$item['count']:0;
  168. }
  169. }
  170. }
  171. $datas = array_values($datas);
  172. RedisService::set($cacheKey, $datas, rand(10,20));
  173. return $datas;
  174. }
  175. /**
  176. * 设置全部已读
  177. * @param $id
  178. * @param $userId
  179. * @return bool
  180. */
  181. public function readAll($userId)
  182. {
  183. $this->model->where(['to_id'=>$userId])->update(['is_read'=>1,'update_time'=>time()]);
  184. $this->error = '设置成功';
  185. return true;
  186. }
  187. /**
  188. * 消息推送处理
  189. * @param $userId 用户
  190. * @param $msgData 消息数据
  191. * @return bool
  192. */
  193. public function pushMessage($userId, $msgData)
  194. {
  195. try {
  196. $msgData = [
  197. 'title' => isset($msgData['title'])?$msgData['title'] : '',
  198. 'from_uid' => isset($msgData['from_uid']) && $msgData['from_uid']?$msgData['from_uid'] : 0,
  199. 'to_uid' => $userId,
  200. 'type' => isset($msgData['type'])?$msgData['type'] : 1,
  201. 'msg_type' => isset($msgData['msg_type'])?$msgData['msg_type'] : 1,
  202. 'description' => isset($msgData['description'])?$msgData['description'] : '',
  203. 'content' => isset($msgData['content'])?json_encode($msgData['content'],256) : '',
  204. 'order_no' => isset($msgData['order_no'])?$msgData['order_no'] : '',
  205. 'chat_key' => getChatKey(0,$userId),
  206. 'create_time' => time(),
  207. 'update_time' => time(),
  208. 'is_read' => 2,
  209. 'status' => 1
  210. ];
  211. if(!$id = $this->model->insertGetId($msgData)){
  212. $this->error = '消息推送失败';
  213. return false;
  214. }
  215. $this->error = '消息推送成功';
  216. return $id;
  217. } catch (\Exception $exception){
  218. $this->error = '消息推送失败:'.$exception->getMessage();
  219. return false;
  220. }
  221. }
  222. /**
  223. * 未读通知消息
  224. * @param $type
  225. * @return array|mixed
  226. */
  227. public function getUnreadCount($userId)
  228. {
  229. $cacheKey = "caches:messages:unread_count_{$userId}";
  230. $count = RedisService::get($cacheKey);
  231. if($count){
  232. return $count;
  233. }
  234. $count = $this->model->where(function($query) use($userId){
  235. if($userId){
  236. $query->where('to_uid',$userId);
  237. }
  238. })->where(['is_read'=>2,'type'=>1,'status'=>1,'mark'=>1])
  239. ->count('id');
  240. if($count){
  241. RedisService::set($cacheKey, $count, rand(300,600));
  242. }
  243. return $count;
  244. }
  245. /**
  246. * 验证是否有敏感词
  247. * @param $message
  248. * @return bool
  249. */
  250. public function checkMessage($message)
  251. {
  252. $chatSensitive = ConfigService::make()->getConfigByCode('chat_sensitive','');
  253. $chatSensitiveList = $chatSensitive? explode('、', $chatSensitive) : [];
  254. if(empty($chatSensitiveList)){
  255. return $message;
  256. }
  257. $pattern = '/\b(' . implode('|', array_map('preg_quote', $chatSensitiveList)) . ')\b/iu';
  258. $result = preg_replace($pattern, '***', $message);
  259. return !preg_match("/^\*+$/",$result)? $result : '';
  260. }
  261. }