| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services\Api;
- use App\Models\GoodsModel;
- use App\Models\GroupUserSettingModel;
- use App\Models\LiveChatModel;
- use App\Models\MemberModel;
- use App\Models\MessageModel;
- use App\Models\VideoCollectModel;
- use App\Models\VideoModel;
- use App\Services\BaseService;
- use App\Services\ConfigService;
- use App\Services\RedisService;
- use Illuminate\Support\Facades\DB;
- /**
- * 站内消息服务管理-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * Class MessageService
- * @package App\Services\Api
- */
- class MessageService extends BaseService
- {
- // 静态对象
- protected static $instance = null;
- /**
- * 构造函数
- * @author laravel开发员
- * @since 2020/11/11
- * MessageService constructor.
- */
- public function __construct()
- {
- $this->model = new MessageModel();
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = (new static());
- }
- return self::$instance;
- }
- /**
- * 消息列表
- * @param $userId
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getDataList($userId, $params, $pageSize = 0)
- {
- $page = request()->post('page', 1);
- $cacheKey = "caches:messages:history_{$page}_" . md5($userId . json_encode($params) . $pageSize);
- $datas = RedisService::get($cacheKey);
- if ($datas) {
- return $datas;
- }
- $where = ['a.status' => 1, 'a.mark' => 1];
- $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.group_id', 'a.from_uid', 'a.to_user_name', 'a.to_user_avatar','a.video_id','a.goods_id','a.live_id', 'a.to_uid', 'a.create_time', 'a.is_read', 'a.pages', 'a.status','d.nickname'];
- $model = $this->model->with(['goods','video','live'])->from('message as a')
- ->leftJoin('member as b', 'b.id', '=', 'a.from_uid')
- ->leftJoin('member as c', 'c.id', '=', 'a.to_uid')
- ->leftJoin('groups_user_setting as d',function($join){
- $join->on('d.user_id', '=', 'a.from_uid')->on('d.group_id','a.group_id');
- })
- ->where($where)
- ->where(function ($query) use ($params, $userId) {
- $fromUid = isset($params['from_uid']) ? intval($params['from_uid']) : 0;
- if ($fromUid) {
- $query->where('a.from_uid', $fromUid);
- }
- $type = isset($params['type']) ? intval($params['type']) : 0;
- if ($type) {
- $query->where('a.type', $type);
- }
- if ($type != 9) {
- $query->where('a.to_uid', $userId);
- }else {
- $groupId = isset($params['group_id']) ? intval($params['group_id']) : 0;
- $clearTime = GroupUserSettingModel::where(['user_id'=>$userId,'group_id'=>$groupId])->value('clear_time');
- $clearTime = $clearTime? $clearTime : 0;
- if ($groupId) {
- $query->where('a.group_id', $groupId)->where(function($query) use($clearTime){
- $query->whereRaw("lev_a.create_time >= {$clearTime}");
- });
- }else{
- $query->where(function ($query) use ($userId) {
- $query->where(function($query) use($userId){
- $query->where(['a.from_uid' => $userId,'a.from_show'=>1]);
- })->orWhere(function($query) use($userId){
- $query->where(['a.to_uid' => $userId,'a.to_show'=>1]);
- });
- });
- }
- }
- $chatType = isset($params['chat_type']) ? intval($params['chat_type']) : 0;
- if ($chatType) {
- $query->where('a.chat_type', $chatType);
- }
- $chatKey = isset($params['chat_key']) ? trim($params['chat_key']) : '';
- if ($chatKey) {
- $query->where('a.chat_key', $chatKey);
- }
- });
- $countModel = clone $model;
- $datas = $model->select($field)
- ->orderBy('a.create_time', 'desc')
- ->orderBy('a.id', 'desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $datas = $datas ? $datas->toArray() : [];
- if ($datas) {
- $ids = [];
- $awardWaitRate = ConfigService::make()->getConfigByCode('shop_award_score_rate', 0);
- $awardWaitRate = $awardWaitRate > 0 && $awardWaitRate < 1000 ? $awardWaitRate : 0;
- $waitRate = ConfigService::make()->getConfigByCode('day_wait_score_rate', 0);
- $waitRate = $waitRate > 0 && $waitRate < 100 ? $waitRate : 0;
- foreach ($datas['data'] as &$item) {
- // 已读
- if($item['to_uid'] == $userId){
- $ids[] = $item['id'];
- }
- $item['show_time']= 0;
- if($item['create_time'] < time() - 3600 ){
- $item['show_time'] = 1;
- }
- if($item['nickname']){
- $item['from_user_name'] = $item['nickname'];
- }
- $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateForWeek($item['create_time']) : '';
- $item['content'] = $item['msg_type'] == 2 ? get_images_preview(json_decode($item['content'], true), '') : str_replace("\n","<br>", $item['content']);
- $item['from_user_avatar'] = $item['from_user_avatar'] ? get_image_url($item['from_user_avatar']) : get_image_url('/images/member/logo.png');
- $item['to_user_avatar'] = $item['to_user_avatar'] ? get_image_url($item['to_user_avatar']) : get_image_url('/images/member/logo.png');
- if(isset($item['video']) && !is_null($item['video'])){
- $item['video']['thumb'] = get_image_url($item['video']['thumb']);
- $item['video']['file_url'] = get_image_url($item['video']['file_url']);
- }
- if(isset($item['goods']) && !is_null($item['goods'])){
- $item['goods']['main_img'] = get_image_url($item['goods']['main_img']);
- if (isset($item['goods']['retail_price']) && $item['goods']['retail_price']) {
- $item['goods']['retail_price1'] = $item['goods']['retail_price'];
- $item['goods']['retail_price'] = GoodsService::make()->getRealSalePrice($item['goods']['cost_price']);
- $item['goods']['wait_score'] = moneyFormat($item['goods']['retail_price'] * $awardWaitRate / 100 * $waitRate / 100, 2);
- }
- }
- $item['live'] = !is_null($item['live'])? [] : $item['live'];
- }
- unset($item);
- // 更新已读
- $type = isset($params['type'])? $params['type'] : 0;
- $chatKey = isset($params['chat_key']) ? trim($params['chat_key']) : '';
- $groupId = isset($params['group_id']) ? intval($params['group_id']) : 0;
- if($groupId>0){
- $this->model->where(['group_id'=> $groupId])->update(['is_read' => 1, 'update_time' => time()]);
- RedisService::clear("caches:message:topList_{$userId}");
- RedisService::keyDel("caches:messages:un_*");
- }
- else if($type == 9){
- $this->model->where(['to_uid'=> $userId,'chat_key'=>$chatKey,'type'=>9])->update(['is_read' => 1, 'update_time' => time()]);
- RedisService::clear("caches:message:topList_{$userId}");
- RedisService::keyDel("caches:messages:un_*");
- }
- else if ($ids) {
- $this->model->whereIn('id', $ids)->update(['is_read' => 1, 'update_time' => time()]);
- RedisService::clear("caches:message:topList_{$userId}");
- RedisService::keyDel("caches:messages:un_*");
- }
- $datas['unread'] = $countModel->where(['a.is_read'=>2])->count('a.id');
- arsort($datas['data'], true);
- $sort = isset($params['sort'])? $params['sort'] : 1;
- if($sort != 2){
- $datas['data'] = array_reverse($datas['data'], false);
- }
- RedisService::set($cacheKey, $datas, rand(3, 5));
- }
- return [
- 'list' => isset($datas['data']) ? $datas['data'] : [],
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'unread' => isset($datas['unread']) ? $datas['unread'] : 0,
- 'pageSize' => $pageSize
- ];
- }
- /**
- * 直播间消息列表
- * @param $userId
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getLiveDataList($userId, $params, $pageSize = 0)
- {
- $page = request()->post('page', 1);
- $liveId = request()->post('live_id', 0);
- $cacheKey = "caches:messages:live_{$liveId}_{$page}_" . md5(json_encode($params) . $pageSize);
- $datas = RedisService::get($cacheKey);
- if ($datas) {
- return $datas;
- }
- $where = ['a.status' => 1, 'a.mark' => 1];
- $field = ['a.id', 'a.msg_type','a.chat_key','a.live_id', 'a.description', 'a.message','b.nickname', 'a.from_uid','b.avatar as from_user_avatar', 'a.to_uid', 'a.create_time', 'a.status'];
- $datas = LiveChatModel::with(['member'])->from('live_chat as a')
- ->leftJoin('member as b', 'b.id', '=', 'a.from_uid')
- ->leftJoin('member as c', 'c.id', '=', 'a.to_uid')
- ->where($where)
- ->where(function ($query) use ($params, $userId) {
- $fromUid = isset($params['from_uid']) ? intval($params['from_uid']) : 0;
- if ($fromUid) {
- $query->where('a.from_uid', $fromUid);
- }
- $liveId = isset($params['live_id']) ? intval($params['live_id']) : 0;
- if ($liveId) {
- $query->where('a.live_id', $liveId);
- }
- $chatKey = isset($params['chat_key']) ? trim($params['chat_key']) : '';
- if ($chatKey) {
- $query->where('a.chat_key', $chatKey);
- }
- })->select($field)
- ->orderBy('a.create_time', 'desc')
- ->orderBy('a.id', 'desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $datas = $datas ? $datas->toArray() : [];
- if ($datas) {
- foreach ($datas['data'] as &$item) {
- $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateForWeek($item['create_time']) : '';
- $item['member']['avatar'] = $item['from_user_avatar']? get_image_url($item['from_user_avatar']) : '/images/member/logo.png';
- }
- unset($item);
- arsort($datas['data'], true);
- $datas['data'] = array_reverse($datas['data'], false);
- RedisService::set($cacheKey, $datas, rand(3, 5));
- }
- return [
- 'list' => isset($datas['data']) ? $datas['data'] : [],
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'pageSize' => $pageSize
- ];
- }
- /**
- * 获取站内消息窗口列表
- * @param $userId
- * @return array|mixed
- */
- public function getGroupList($userId, $cache = false)
- {
- $cachekey = "caches:message:topList_{$userId}";
- $datas = RedisService::get($cachekey);
- if ($datas && $cache) {
- $datas['cache'] = true;
- return $datas;
- }
- $types = [1, 4, 5];
- $setting = MemberSettingService::make()->getSetting($userId);
- $pushStatus = false;
- if ($setting) {
- foreach ($setting as $k => $v) {
- if ($v == 1) {
- if ($k == 'receive_app') {
- $pushStatus = true;
- } else if ($k == 'receive_order') {
- $types[] = 2;
- } else if ($k == 'receive_account') {
- $types[] = 3;
- }
- }
- }
- asort($types);
- } else {
- $pushStatus = true;
- $types = [1, 2, 3, 4, 5];
- }
- // 关闭系统APP消息
- if (!$pushStatus) {
- return ['list' => [], 'total' => 0, 'types' => []];
- }
- $field = ['title', 'type', 'to_uid', 'description', 'is_read', 'create_time'];
- $datas = $this->model->where(['to_uid' => $userId, 'status' => 1, 'mark' => 1])
- ->whereIn('type', $types)
- ->groupBy('type')
- ->orderBy('type', 'asc')
- ->orderBy('is_read', 'desc')
- ->orderBy('create_time', 'desc')
- ->select($field)
- ->get();
- $datas = $datas ? $datas->toArray() : [];
- $total = 0;
- if ($datas) {
- $titles = [1 => '公告通知', 2 => '订单通知', 3 => '账户通知', 4 => '客服通知', 5 => '互动消息'];
- foreach ($datas as &$item) {
- $item['title'] = isset($titles[$item['type']]) ? $titles[$item['type']] : '消息通知';
- $data = $this->getNewMessage($item['type'], 0, $userId);
- $item['description'] = isset($data['description']) && $data['description'] ? $data['description'] : (isset($data['content']) ? mb_substr($data['content'], 0, 56, 'utf-8') . '...' : lang('有新消息'));
- $item['create_time'] = isset($data['create_time']) && $data['create_time'] ? $data['create_time'] : '';
- $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
- $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
- $unread = $this->getUnreadCount($userId, 0, $item['type']);
- $item['unread'] = intval($unread);
- $total += intval($unread);
- }
- RedisService::set($cachekey, ['list' => $datas, 'total' => $total, 'types' => $types], rand(2, 3));
- }
- return ['list' => $datas, 'total' => $total, 'types' => $types];
- }
- /**
- * 聊天分组消息
- * @param $userId
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getDataListFromatKey($userId, $params, $pageSize = 0)
- {
- $page = request()->post('page', 1);
- $cacheKey = "caches:m_chat:{$page}_" . md5($userId . json_encode($params) . $pageSize);
- $datas = RedisService::get($cacheKey);
- $data = isset($datas['data']) ? $datas['data'] : [];
- if ($datas && $data) {
- return [
- 'unread' => isset($datas['unReadCount']) ? $datas['unReadCount'] : 0,
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'list' => $data,
- 'pageSize' => $pageSize,
- 'cache' => true,
- ];
- }
- // 不接收则不显示聊天消息
- $receiveCustom = MemberSettingService::make()->getSetting($userId, 'receive_custom', 1);
- if ($receiveCustom != 1) {
- return [
- 'unread' => 0,
- 'total' => 0,
- 'list' => [],
- 'pageSize' => $pageSize,
- 'close' => true,
- ];
- }
- $where = ['a.type' => 9, 'a.status' => 1, 'a.mark' => 1];
- $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
- $expire = $expire ? $expire * 86400 : 60 * 86400;
- $field = ['a.id', 'a.title', 'a.type', 'a.msg_type','a.to_show', 'a.chat_key', 'a.chat_type', 'a.description','a.group_id', '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.status','b.name as group_name','b.thumb as group_thumb','b.group_users'];
- $datas = $this->model->from('message as a')
- ->leftJoin('groups as b', function($join) use($userId){
- $join->on('b.id','=','a.group_id')->where('a.group_id','>',0);
- })
- ->leftJoin('groups_user_setting as c',function($join) use($userId){
- $join->on('c.group_id','a.group_id')->where('c.user_id', '=', $userId);
- })
- ->where($where)
- ->where('a.chat_key', '!=', '')
- ->where('a.create_time', '>=', time() - $expire)
- ->where(function ($query) use ($params, $userId) {
- $chatKey = isset($params['chat_key']) ? trim($params['chat_key']) : '';
- if ($chatKey) {
- $query->where('a.chat_key', $chatKey);
- }
- $isRead = isset($params['is_read']) ? intval($params['is_read']) : 0;
- if ($isRead) {
- $query->where('a.is_read', $isRead);
- }
- $chatType = isset($params['chat_type']) ? intval($params['chat_type']) : 0;
- if ($chatType) {
- $query->where('a.chat_type', $chatType);
- }
- if ($userId) {
- $query->where(function ($query) use ($userId) {
- $query->where(function($query) use($userId){
- $query->where(['a.from_uid' => $userId,'a.from_show'=>1]);
- })->orWhere(function($query) use($userId){
- $query->where(['a.to_uid' => $userId,'a.to_show'=>1]);
- })->orWhere(function($query) use($userId){
- $query->where('a.group_id','>',0)->where(function($query){
- $query->whereRaw('lev_a.create_time >= lev_c.clear_time and lev_c.clear_time > 0')->orWhere('c.clear_time',0)->orWhereNull('c.id');
- })->whereRaw('FIND_IN_SET(?,lev_b.group_users)', $userId);
- });
- });
- }
- })
- ->select($field)
- ->groupBy('chat_key')
- ->orderBy('a.create_time', 'desc')
- ->orderBy('a.id', 'desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $datas = $datas ? $datas->toArray() : [];
- $unReadCount = 0;
- if ($datas) {
- $messageList = [];
- foreach ($datas['data'] as $k => &$item) {
- $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');
- $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');
- $data = $this->getNewMessage($item['type'], $item['chat_key'], $userId, $item['group_id']);
- $item['description'] = isset($data['description']) && $data['description'] ? $data['description'] : (isset($data['content']) ? mb_substr($data['content'], 0, 30, 'utf-8') : ($data? web_lang('有新消息') : ''));
- $item['create_time'] = isset($data['create_time']) && $data['create_time'] ? $data['create_time'] : $item['create_time'];
- $item['msg_type'] = isset($data['msg_type']) && $data['msg_type']? $data['msg_type'] : $item['msg_type'];
- $item['time_text'] = isset($item['create_time']) && $item['create_time'] ? dateFormat($item['create_time']) : '';
- $timeKey = $item['create_time']? strtotime($item['create_time']) : time();
- $item['create_time'] = isset($item['create_time']) ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
- $item['unread'] = $this->getUnreadCount($userId, $item['chat_key'], 0);
- if ($item['from_uid'] == $userId) {
- $item['from_user_name'] = $item['to_user_name'];
- $item['from_user_avatar'] = $item['to_user_avatar'];
- $item['tuid'] = $item['to_uid'];
- } else {
- $item['tuid'] = $item['from_uid'];
- }
- if($item['group_id']>0){
- $groupUsers = $item['group_users']? explode(',', $item['group_users']) : [];
- $item['group_user_count'] = $groupUsers? count($groupUsers) : 1;
- $item['from_user_name'] = $item['group_name']? $item['group_name'] : '';
- $item['from_user_avatar'] = $item['group_thumb']? get_image_url($item['group_thumb']) : '';
- if($item['from_user_avatar'] == '' ){
- $userIds = $groupUsers? array_slice($groupUsers,0,9) : [$userId];
- $item['group_users'] = GroupService::make()->getGroupUsers($item['id'], $userIds);
- }
- }else{
- $item['group_users'] = [];
- }
- $unReadCount += intval($item['unread']);
- $messageList[$timeKey.'_'.$k] = $item;
- }
- unset($item);
- krsort($messageList);
- $datas['data'] = array_values($messageList);
- $datas['unReadCount'] = $unReadCount;
- RedisService::set($cacheKey, $datas, rand(3, 5));
- }
- return [
- 'unread' => $unReadCount,
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'list' => isset($datas['data']) ? $datas['data'] : [],
- 'pageSize' => $pageSize,
- 'cache' => false,
- ];
- }
- /**
- * 获取最新消息
- * @param $chatKey
- * @return mixed
- */
- public function getNewMessage($type = 0, $chatKey = 0, $userId = 0, $groupId=0)
- {
- $cacheKey = "caches:messages:new_{$type}_{$chatKey}_{$userId}_{$groupId}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return $data;
- }
- $where = ['status' => 1, 'mark' => 1];
- if ($type) {
- $where['type'] = $type;
- }
- if ($chatKey) {
- $where['chat_key'] = $chatKey;
- }
- if ($userId && $chatKey==0) {
- $where['to_uid'] = $userId;
- }
- if($groupId){
- $clearTime = GroupUserSettingModel::where(['user_id'=>$userId,'group_id'=>$groupId])->value('clear_time');
- $clearTime = $clearTime? $clearTime : 0;
- $data = $this->model->where($where)
- ->where('create_time','>=', $clearTime)
- ->select('id', 'title', 'description', 'msg_type', 'content', 'create_time')
- ->orderBy('create_time', 'desc')
- ->orderBy('id', 'desc')
- ->first();
- }else{
- $data = $this->model->where($where)->select('id', 'title', 'description', 'msg_type', 'content', 'create_time')
- ->orderBy('create_time', 'desc')
- ->orderBy('id', 'desc')
- ->first();
- }
- $data = $data ? $data->toArray() : [];
- if ($data) {
- if ($data['msg_type'] == 2) {
- $data['description'] = '[图片]';
- } else if ($data['msg_type'] == 3) {
- $data['description'] = '[视频聊天]';
- } else if ($data['msg_type'] == 4) {
- $data['description'] = '[直播间分享]';
- }else if($data['msg_type'] == 6){
- $data['description'] = '[群消息]';
- }
- RedisService::set($cacheKey, $data, rand(3, 5));
- }
- return $data;
- }
- /**
- * 获取未读消息数量
- * @param $userId
- * @return array|mixed
- */
- public function getBarCount($userId, $type = 0)
- {
- $cacheKey = "caches:barCount:{$userId}_{$type}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return $data;
- }
- $data = $this->getUnreadCount($userId, 0, $type);
- RedisService::set($cacheKey, $data, rand(3, 5));
- return $data;
- }
- /**
- * 推送站内消息
- * @param $userId 用户ID
- * @param $title 标题
- * @param $message 消息内容
- * @param int $type 类型:1-公告,2-订单,3-账户,4-客服,5-动态
- * @return false
- */
- public function pushMessage($userId, $title, $message, $type = 1, $fromUid = 0, $pageUrl='')
- {
- $types = [4, 5];
- $pushStatus = false;
- $datas = MemberSettingService::make()->getSetting($userId);
- if ($datas) {
- foreach ($datas as $k => $v) {
- if ($v == 1) {
- if ($k == 'receive_app') {
- $pushStatus = true;
- $types[] = 1;
- } else if ($k == 'receive_order') {
- $types[] = 2;
- } else if ($k == 'receive_account') {
- $types[] = 3;
- }
- }
- }
- } else {
- $pushStatus = true;
- $types = [1, 2, 3, 4, 5];
- }
- if ($userId && $pushStatus && in_array($type, $types)) {
- $appName = ConfigService::make()->getConfigByCode('app_name', '星链社交');
- $log = [
- 'from_uid' => $fromUid,
- 'to_uid' => $userId,
- 'from_user_name' => $appName,
- 'chat_type' => 0,
- 'msg_type' => 1,
- 'type' => $type,
- 'title' => $title,
- 'description' => $title,
- 'content' => $message,
- 'pages' => $pageUrl?$pageUrl:'',
- 'chat_key' => "0{$userId}",
- 'create_time' => time(),
- 'status' => 1,
- 'mark' => 1,
- ];
- return MessageModel::insert($log);
- }
- return false;
- }
- /**
- * 推送群聊消息
- * @param $fromUId 发送用户ID
- * @param $groupId 群ID
- * @param $title 标题
- * @param $message 消息内容
- * @param int $type 类型:1-公告,2-订单,3-账户,4-客服,5-动态
- * @return false
- */
- public function pushGroupMessage($groupId, $title, $message, $msgType = 1, $fromUid = 0, $pageUrl='')
- {
- $types = [6, 7];
- if ($groupId && in_array($msgType, $types)) {
- $appName = ConfigService::make()->getConfigByCode('app_name', '星链社交');
- $log = [
- 'from_uid' => $fromUid,
- 'to_uid' => 0,
- 'group_id' => $groupId,
- 'from_user_name' => $appName,
- 'chat_type' => 0,
- 'msg_type' => $msgType,
- 'type' => 9,
- 'title' => $title,
- 'description' => $title,
- 'content' => $message,
- 'pages' => $pageUrl?$pageUrl:'',
- 'chat_key' => "group-{$groupId}",
- 'create_time' => time(),
- 'status' => 1,
- 'mark' => 1,
- ];
- return MessageModel::insert($log);
- }
- return false;
- }
- /**
- * 获取
- * @param $userId
- * @return array|mixed
- */
- public function getUnreadCount($userId, $chatKey = 0, $type = 0)
- {
- $cacheKey = "caches:messages:un_{$userId}_{$chatKey}_{$type}";
- $data = RedisService::get($cacheKey);
- if (RedisService::exists($cacheKey)) {
- return $data;
- }
- $where = ['a.to_show'=>1, 'a.status' => 1, 'a.mark' => 1];
- if ($type > 0) {
- $where['a.type'] = $type;
- }
- if ($chatKey) {
- $where['a.chat_key'] = $chatKey;
- }
- $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
- $expire = $expire ? $expire * 86400 : 60 * 86400;
- $data = $this->model->from('message as a')
- ->leftJoin('groups as b', function($join) use($userId){
- $join->on('b.id','=','a.group_id');
- })
- ->leftJoin('groups_user_setting as c', function($join) use($userId){
- $join->on('c.group_id','=','a.group_id')->where('c.user_id','=', $userId);
- })
- ->where(function($query) use($userId){
- $query->where(function ($query) use ($userId) {
- if($userId){
- $query->where(function($query) use($userId){
- $query->where(['a.to_uid' => $userId,'a.to_show'=>1,'a.is_read' => 2])->where('a.group_id', 0);
- })->orWhere(function($query) use($userId){
- $query->where('a.group_id','>',0)->whereNotIn('a.from_uid',[$userId])->where(function($query){
- $query->whereRaw('lev_a.create_time >= lev_c.read_time and lev_c.read_time > 0')->orWhere('c.read_time',0)->orWhereNull('c.id');
- })->where(function($query){
- $query->where(['a.from_show'=>1])->orWhere(['a.to_show'=>1]);
- })->whereRaw('FIND_IN_SET(?,lev_b.group_users)', $userId);
- });
- }
- });
- })
- ->where('a.create_time', '>=', time() - $expire)
- ->where($where)
- ->count('a.id');
- RedisService::set($cacheKey, $data, rand(2, 3));
- return $data;
- }
- /**
- * 验证发送消息或者内容是否有屏蔽词
- * @param $message 消息或内容
- * @param $type 是否返回屏蔽后内容:1-是
- * @return bool
- */
- public function filterMessage($message, $type = 1)
- {
- $filter = ConfigService::make()->getConfigByCode('chat_sensitive');
- $filter = !empty($filter) ? explode('、', $filter) : [];
- $filter = array_filter($filter);
- if ($filter) {
- if ($type != 2) {
- foreach ($filter as $kw) {
- $message = preg_replace("/{$kw}/", '***', $message);
- }
- } else {
- foreach ($filter as $kw) {
- if (preg_match("/{$kw}/", $message)) {
- return false;
- }
- }
- }
- // 手机号、邮箱、网址
- if ($type == 1) {
- $message = preg_replace("/^(1[3-9][0-9]{9})$/", '***', $message);
- $message = preg_replace("/([a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+)/is", '***', $message);
- $message = str_replace(['https:', 'http:', '.com', '.cn', '.net', '.top', 'www.'], '***', $message);
- $message = preg_replace("/([a-zA-Z0-9][a-zA-Z0-9\_]{6,20})/", '***', $message);
- $message = preg_replace("/\*{3}\*{1,}/", '***', $message);
- }
- }
- return $type == 3 && $message === '***' ? '' : $message;
- }
- /**
- * 已读
- * @param $userId 用户ID
- * @param $chatKey 聊天窗口ID
- * @return bool
- */
- public function setRead($userId, $type = 0, $chatKey = '', $groupId=0)
- {
- $where = [];
- if(!$groupId){
- $where['to_uid'] = $userId;
- }else{
- $where['group_id'] = $groupId;
- }
- if ($type) {
- $where['type'] = $type;
- }
- if ($chatKey) {
- $where['chat_key'] = $chatKey;
- }
- $this->model->where($where)->update(['is_read' => 1, 'update_time' => time()]);
- // 清除缓存
- RedisService::keyDel("caches:messages:bar*");
- RedisService::keyDel("caches:messages:new_*");
- RedisService::keyDel("caches:messages:un_*");
- RedisService::keyDel("caches:messages:topList_{$userId}");
- return true;
- }
- /**
- * 隐藏
- * @param $userId
- * @param int $expire
- * @return mixed
- */
- public function setHide($userId, $type)
- {
- $this->model->where(['to_uid' => $userId, 'type' => $type, 'status' => 1, 'mark' => 1])
- ->update(['update_time' => time(),'to_show'=>2, 'is_read' => 1, 'status' => 3]);
- // 清除缓存
- RedisService::keyDel("caches:messages:bar*");
- RedisService::keyDel("caches:messages:new_*");
- RedisService::keyDel("caches:messages:un_*");
- RedisService::keyDel("caches:messages:topList_{$userId}");
- return true;
- }
- /**
- * 分享
- * @param $userId
- * @param $params
- * @return false|int[]
- */
- public function share($userId, $params)
- {
- $shareUserId = isset($params['user_id'])? intval($params['user_id']) : 0;
- $groupId = isset($params['group_id'])? intval($params['group_id']) : 0;
- $videoId = isset($params['video_id'])? intval($params['video_id']) : 0;
- $liveId = isset($params['live_id'])? intval($params['live_id']) : 0;
- $goodsId = isset($params['goods_id'])? intval($params['goods_id']) : 0;
- $type = isset($params['type'])? intval($params['type']) : 1; // 1-用户私聊分享,2-商家私聊分享,3-承兑商私聊分享,0-群聊分享
- $message = isset($params['message'])? trim($params['message']) : '';
- $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
- ->select(['id','nickname','usdt','pay_password','avatar','status'])
- ->first();
- $status = isset($userInfo['status'])? $userInfo['status'] : 0;
- if(empty($userInfo) || $status != 1){
- $this->error = 2024;
- return false;
- }
- $shareInfo = [];
- if($shareUserId){
- $shareInfo = MemberModel::where(['id'=> $shareUserId,'mark'=>1])
- ->select(['id','nickname','usdt','pay_password','avatar','status'])
- ->first();
- }
- $msgData = [
- 'from_uid' => $userId,
- 'to_uid' => $shareUserId,
- 'type' => 9,
- 'title' => '分享',
- 'msg_type' => $goodsId? 5 : 8,
- 'chat_type' => $type,
- 'from_user_name' => $userInfo['nickname'],
- 'to_user_name' => $shareInfo? $shareInfo['nickname'] : '',
- 'from_user_avatar' => $userInfo? $userInfo['avatar'] : '',
- 'to_user_avatar' => $shareInfo? $shareInfo['avatar'] : '',
- 'description' => $goodsId?'商品分享':($liveId? '直播分享': '视频分享'),
- 'content' => $message,
- 'goods_id' => $goodsId,
- 'group_id' => $groupId,
- 'live_id' => $liveId,
- 'video_id' => $videoId,
- 'chat_key' => $type==0? "group-{$groupId}" : getChatKey($userId, $shareUserId),
- 'create_time' => time(),
- 'update_time' => time(),
- 'is_read' => 2,
- 'status' => 1
- ];
- DB::beginTransaction();
- if(!$this->model->insertGetid($msgData)){
- DB::rollBack();
- $this->error = 1070;
- return false;
- }
- // 视频分享
- $num = 1;
- if($videoId){
- $videoInfo = VideoModel::where(['id'=> $videoId])->first();
- if(empty($videoInfo)){
- DB::rollBack();
- $this->error = 1070;
- return false;
- }
- $data = [
- 'user_id'=> $userId,
- 'type'=> 4,
- 'collect_id'=> $videoId,
- 'collect_uid'=> isset($videoInfo['user_id'])? $videoInfo['user_id'] : 0,
- 'tags'=> isset($videoInfo['tags'])&&$videoInfo['tags']? $videoInfo['tags'] : '',
- 'create_time'=> time(),
- 'status'=> 1,
- ];
- if(!VideoCollectModel::insertGetId($data)){
- DB::rollBack();
- $this->error = 1070;
- return false;
- }
- $updateData = ['share_num'=> DB::raw("share_num + 1"),'update_time'=>time()];
- if(!VideoModel::where(['id'=> $videoId])->update($updateData)){
- DB::rollBack();
- $this->error = 1070;
- return false;
- }
- $num = $videoInfo['share_num']+1;
- }
- // 商品分享
- else if($goodsId){
- $updateData = ['share_num'=> DB::raw("share_num + 1"),'update_time'=>time()];
- if(!GoodsModel::where(['id'=> $goodsId])->update($updateData)){
- DB::rollBack();
- $this->error = 1070;
- return false;
- }
- $num = (int)VideoModel::where(['id'=> $videoId])->value('share_num');
- }
- DB::commit();
- $this->error = 1069;
- return ['num'=> $num];
- }
- /**
- * 清除历史
- * @param $userId
- * @param int $expire
- * @return mixed
- */
- public function clear($userId, $chatKey = 0, $type = 0, $groupId=0)
- {
- $where = ['mark' => 1];
- if($groupId){
- $where['group_id'] = $groupId;
- }else{
- $where['to_uid'] = $userId;
- }
- if ($type) {
- $where['type'] = $type;
- }
- if ($chatKey) {
- $where['chat_key'] = $chatKey;
- }
- $this->model->where($where)
- ->update(['update_time' => time(), 'mark' => 0]);
- // 清除缓存
- RedisService::keyDel("caches:messages:bar*");
- RedisService::keyDel("caches:messages:new_*");
- RedisService::keyDel("caches:messages:un_*");
- RedisService::keyDel("caches:messages:topList_{$userId}");
- return true;
- }
- /**
- * 清除历史
- * @param $userId
- * @param int $expire
- * @return mixed
- */
- public function clearAll($userId, $type=0)
- {
- $expire = ConfigService::make()->getConfigByCode('chat_log_expire');
- $expire = $expire > 0 ? $expire : 60;
- $this->model->where(['to_uid' => $userId, 'mark' => 0])
- ->where('update_time', '<', time() - $expire * 86400)
- ->delete();
- // 清除缓存
- RedisService::keyDel("caches:messages:bar*");
- RedisService::keyDel("caches:messages:new_*");
- RedisService::keyDel("caches:messages:topList_{$userId}");
- // 站内消息发给我的全删
- $this->model->whereNotIn('type',[9])->where(function($query) use($userId, $type){
- $query->where(['to_uid'=> $userId,'mark'=>1]);
- if($type>0){
- $query->where('type', $type);
- }
- })->update(['update_time' => time(), 'mark' => 0]);
- if($type==9 || !$type){
- // 聊天消息我发的全删
- $this->model->where(function($query) use($userId){
- $query->where(['type'=>9,'from_uid'=> $userId,'mark'=>1]);
- })->update(['update_time' => time(), 'mark' => 0]);
- // 聊天消息发给我的,接收方全隐藏
- $this->model->where(function($query) use($userId){
- $query->where(['type'=>9,'to_uid'=> $userId,'mark'=>1]);
- })->update(['update_time' => time(),'is_read'=>1, 'to_show' => 2]);
- }
- return true;
- }
- }
|