MessageService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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.description','a.content','a.from_uid','a.to_uid','a.create_time','a.is_read','a.pages','a.status','b.nickname as from_nickname','c.nickname as to_nickname'];
  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. $status = isset($params['status'])? intval($params['status']) : 0;
  84. if($status){
  85. $query->where('a.status', $status);
  86. }
  87. })->select($field)
  88. ->orderBy('a.create_time','desc')
  89. ->orderBy('a.id','desc')
  90. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  91. $datas = $datas ? $datas->toArray() : [];
  92. if ($datas) {
  93. $ids = [];
  94. foreach ($datas['data'] as &$item) {
  95. $ids[] = $item['id'];
  96. $item['time_text'] = isset($item['create_time']) && $item['create_time']? dateForWeek($item['create_time']) : '';
  97. $item['content'] = $item['content']? json_decode($item['content'], true) : [];
  98. }
  99. unset($item);
  100. // 更新已读
  101. if($ids){
  102. $this->model->whereIn('id', $ids)->update(['is_read'=> 1,'update_time'=>time()]);
  103. }
  104. RedisService::set($cacheKey, $datas, rand(3,5));
  105. }
  106. return [
  107. 'list'=> isset($datas['data'])? $datas['data'] : [],
  108. 'total'=> isset($datas['total'])? $datas['total'] : 0,
  109. 'pageSize'=>$pageSize
  110. ];
  111. }
  112. /**
  113. * 获取站内消息窗口列表
  114. * @param $userId
  115. * @return array|mixed
  116. */
  117. public function getGroupList($userId)
  118. {
  119. $cachekey = "caches:messages:topList_{$userId}";
  120. $datas = RedisService::get($cachekey);
  121. if($datas){
  122. return $datas;
  123. }
  124. $types = [1];
  125. $setting = MemberSettingService::make()->getSetting($userId);
  126. if($setting){
  127. foreach ($setting as $k => $v){
  128. if($k == 'receive_order'){
  129. $types[] = 2;
  130. }else if ($k == 'receive_account'){
  131. $types[] = 3;
  132. }
  133. }
  134. }else{
  135. $types = [1,2,3];
  136. }
  137. $field = ['title','type','to_uid','description','is_read','create_time'];
  138. $datas = $this->model->where(['to_uid'=> $userId,'status'=>1,'mark'=>1])
  139. ->whereIn('type', $types)
  140. ->groupBy('type')
  141. ->orderBy('type','asc')
  142. ->orderBy('is_read','desc')
  143. ->orderBy('create_time','desc')
  144. ->select($field)
  145. ->get();
  146. $datas = $datas? $datas->toArray() : [];
  147. $total = 0;
  148. if($datas){
  149. $titles = [1=>'消息通知',2=>'订单通知',3=>'账户通知'];
  150. foreach($datas as &$item){
  151. $item['time_text'] = isset($item['create_time']) && $item['create_time']? dateFormat($item['create_time']) : '';
  152. $item['title'] = isset($titles[$item['type']])? $titles[$item['type']] : '消息通知';
  153. $data = $this->getNewMessage($item['type'],$userId);
  154. $item['description'] = isset($data['description']) && $data['description']? $data['description'] : (isset($data['message'])? mb_substr($data['message'],0,20,'utf-8'):'有新消息');
  155. $item['create_time'] = isset($data['create_time']) && $data['create_time']? $data['create_time'] : '';
  156. $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
  157. $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  158. $unread = $this->getUnreadCount($userId, $item['type']);
  159. $item['unread'] = intval($unread);
  160. $total += intval($unread);
  161. }
  162. RedisService::set($cachekey, ['list'=>$datas,'total'=>$total,'types'=>$types], rand(3,5));
  163. }
  164. return ['list'=>$datas,'total'=> $total,'types'=>$types];
  165. }
  166. /**
  167. * 获取最新消息
  168. * @param $chatKey
  169. * @return mixed
  170. */
  171. public function getNewMessage($type,$userId=0)
  172. {
  173. $cacheKey = "caches:messages:new_{$type}_{$userId}";
  174. $data = RedisService::get($cacheKey);
  175. if($data){
  176. return $data;
  177. }
  178. $where = ['type'=>$type,'status'=>1,'mark'=>1];
  179. if($userId){
  180. $where['to_uid'] = $userId;
  181. }
  182. $data = $this->model->where($where)->select('id','description','content','create_time')
  183. //->orderBy('is_read','desc')
  184. ->orderBy('create_time','desc')
  185. ->orderBy('id','desc')
  186. ->first();
  187. $data = $data? $data->toArray() : [];
  188. if($data){
  189. RedisService::set($cacheKey, $data, rand(3, 5));
  190. }
  191. return $data;
  192. }
  193. /**
  194. * 获取未读消息数量
  195. * @param $userId
  196. * @return array|mixed
  197. */
  198. public function getBarCount($userId, $type=0)
  199. {
  200. $cacheKey = "caches:messages:barCount:{$userId}_{$type}";
  201. $data = RedisService::get($cacheKey);
  202. if($data){
  203. return $data;
  204. }
  205. $data1 = $this->getUnreadCount($userId, $type);
  206. $data1 = $data1? intval($data1) : 0;
  207. $data2 = ImChatService::make()->getUnreadCount($userId);
  208. $data = $data1+$data2;
  209. RedisService::set($cacheKey, $data, rand(3, 5));
  210. return $data;
  211. }
  212. /**
  213. * 获取
  214. * @param $userId
  215. * @return array|mixed
  216. */
  217. public function getUnreadCount($userId, $type=0)
  218. {
  219. $cacheKey = "caches:messages:unReadCount:{$userId}_{$type}";
  220. $data = RedisService::get($cacheKey);
  221. if(RedisService::exists($cacheKey)){
  222. return $data;
  223. }
  224. $where = ['to_uid'=> $userId,'status'=>1,'is_read'=>2,'mark'=>1];
  225. if($type>0){
  226. $where['type'] = $type;
  227. }
  228. $data = $this->model->where($where)->count('id');
  229. RedisService::set($cacheKey, $data, rand(3, 5));
  230. return $data;
  231. }
  232. /**
  233. * 验证发送消息或者内容是否有屏蔽词
  234. * @param $message 消息或内容
  235. * @param $type 是否返回屏蔽后内容:1-是
  236. * @return bool
  237. */
  238. public function filterMessage($message, $type = 1)
  239. {
  240. $filter = ConfigService::make()->getConfigByCode('chat_sensitive');
  241. $filter = !empty($filter)? explode('、', $filter) : [];
  242. $filter = array_filter($filter);
  243. if($filter){
  244. if($type != 2){
  245. foreach ($filter as $kw){
  246. $message = preg_replace("/{$kw}/",'***', $message);
  247. }
  248. }else{
  249. foreach ($filter as $kw){
  250. if(preg_match("/{$kw}/", $message)){
  251. return false;
  252. }
  253. }
  254. }
  255. // 手机号、邮箱、网址
  256. if($type == 1){
  257. $message = preg_replace("/^(1[3-9][0-9]{9})$/", '***',$message);
  258. $message = preg_replace("/([a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+)/is", '***',$message);
  259. $message = str_replace(['https:','http:','.com','.cn','.net','.top','www.'], '***',$message);
  260. $message = preg_replace("/([a-zA-Z0-9][a-zA-Z0-9\_]{6,20})/", '***',$message);
  261. $message = preg_replace("/\*{3}\*{1,}/",'***', $message);
  262. }
  263. }
  264. return $type == 3 && $message === '***'? '' : $message;
  265. }
  266. /**
  267. * 已读
  268. * @param $userId 用户ID
  269. * @param $chatKey 聊天窗口ID
  270. * @return bool
  271. */
  272. public function setRead($userId, $type)
  273. {
  274. $this->model->where(['to_uid'=> $userId,'type'=> $type])
  275. ->update(['is_read'=>1,'update_time'=>time()]);
  276. // 清除缓存
  277. RedisService::keyDel("caches:messages:bar*");
  278. RedisService::keyDel("caches:messages:new_*");
  279. RedisService::keyDel("caches:messages:topList_{$userId}");
  280. return true;
  281. }
  282. /**
  283. * 隐藏
  284. * @param $userId
  285. * @param int $expire
  286. * @return mixed
  287. */
  288. public function setHide($userId, $type)
  289. {
  290. $this->model->where(['to_uid'=>$userId,'type'=> $type,'status'=> 1,'mark'=>1])
  291. ->update(['update_time'=>time(),'is_read'=>1,'status'=> 3]);
  292. // 清除缓存
  293. RedisService::keyDel("caches:messages:bar*");
  294. RedisService::keyDel("caches:messages:new_*");
  295. RedisService::keyDel("caches:messages:topList_{$userId}");
  296. return true;
  297. }
  298. /**
  299. * 清除历史
  300. * @param $userId
  301. * @param int $expire
  302. * @return mixed
  303. */
  304. public function clear($userId, $msgType)
  305. {
  306. $this->model->where(['to_uid'=>$userId,'type'=> $msgType,'mark'=>1])
  307. ->update(['update_time'=>time(),'mark'=>0]);
  308. // 清除缓存
  309. RedisService::keyDel("caches:messages:bar*");
  310. RedisService::keyDel("caches:messages:new_*");
  311. RedisService::keyDel("caches:messages:topList_{$userId}");
  312. return true;
  313. }
  314. /**
  315. * 清除历史
  316. * @param $userId
  317. * @param int $expire
  318. * @return mixed
  319. */
  320. public function clearAll($userId)
  321. {
  322. $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
  323. $expire = $expire>0? $expire : 60;
  324. $this->model->where(['to_uid'=>$userId,'mark'=>0])
  325. ->where('update_time','<', time() - 7*86400)
  326. ->delete();
  327. // 清除缓存
  328. RedisService::keyDel("caches:messages:bar*");
  329. RedisService::keyDel("caches:messages:new_*");
  330. RedisService::keyDel("caches:messages:topList_{$userId}");
  331. return $this->model->where(['to_uid'=>$userId,'mark'=>1])
  332. ->where('create_time','<', time() -$expire*86400)
  333. ->update(['update_time'=>time(),'mark'=>0]);
  334. }
  335. }