推拉函数与queue

This commit is contained in:
cano
2024-03-03 09:39:06 +08:00
parent f5f7168009
commit 66d88ea2b3
15 changed files with 476 additions and 108 deletions

View File

@ -29,7 +29,7 @@ class DailyCheckUserActiveStatus extends Command
$this->info('每日更新用户活跃状态'); $this->info('每日更新用户活跃状态');
$this->info('开始...'); $this->info('开始...');
$oCustomerUserExtendModelExtend = new CustomerUserExtendModel(); $oCustomerUserExtendModelExtend = new CustomerUserExtendModel();
$oCustomerUserExtendModelExtend->updateUserActiveStatus(); $oCustomerUserExtendModelExtend->updateAllUserActiveStatus();
$this->info('结束...'); $this->info('结束...');
} }
} }

View File

@ -4,8 +4,56 @@
namespace App\Http\Controllers\Post; namespace App\Http\Controllers\Post;
use App\Http\Controllers\Base\BaseController; use App\Http\Controllers\Base\BaseController;
use App\Models\Post\PostModel;
use App\Models\Post\PostPushBoxModel;
use App\Service\AuthService;
class PostController extends BaseController class PostController extends BaseController
{ {
//$uid, $content = null, $media = null,$mid = null,$sBachSn = null
public array $validateMethodParams = [
'addPost' => [
'type' => 'required|numeric|max:2',
'content' => 'required|numeric|max:255',
'media' => 'json',
],
'pullPostList' => [
'lastId' => 'numeric|max:10',
'limit' => 'numeric|max:5',
],
];
public function addPost(): \Illuminate\Http\JsonResponse
{
$aParams = request()->only([
'type',
'content',
'media',
]);
if (!in_array($aParams['type'], [PostModel::TYPE_POST, PostModel::TYPE_REPOST])) return $this->error('type params error');
$oAuthService = new AuthService();
$aUser = $oAuthService->getCurrentUser();
$oFollowModel = new PostModel();
$aParams['uid'] = $aUser['id'];
$oFollowModel->addBatchPost([$aParams]);
return $this->success();
}
function pullPostList()
{
$aParams = request()->only([
'lastId',
'limit',
]);
$oAuthService = new AuthService();
$aUser = $oAuthService->getCurrentUser();
$oPostModel = new PostPushBoxModel();
$aPostList = $oPostModel->getPushBoxList($aUser['id'],$aParams['lastId']??0,$aParams['limit']??15);
return $this->success($aPostList);
}
} }

35
app/Jobs/AddPostQueue.php Normal file
View File

@ -0,0 +1,35 @@
<?php
namespace App\Jobs;
use App\Exceptions\ModelException;
use App\Models\Post\PostPushBoxModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class AddPostQueue implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
//
}
/**
* Execute the job.
* @throws ModelException
*/
public function handle(array $params): void
{
$oPostPushBoxModel = new PostPushBoxModel();
$oPostPushBoxModel->addPostQueueConsumer($params);
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Jobs;
use App\Models\Customer\CustomerUserExtendModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class UserActiveStatusQueue implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
//
}
/**
* Execute the job.
*/
public function handle(array $params): void
{
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oCustomerUserExtendModel->activeUserStatusQueueConsumer($params);
}
}

View File

@ -27,6 +27,14 @@ class BaseModel extends Model
return $this->newQuery()->create($aItem); return $this->newQuery()->create($aItem);
} }
function addItemWithCreateTime($aItem,$col = 'created_at'): Model|\Illuminate\Database\Eloquent\Builder|bool
{
$aItem = $this->checkColInFill($aItem);
if (empty($aItem)) return false;
$aItem[$col] = date('Y-m-d H:i:s');
return $this->newQuery()->create($aItem);
}
function delItem($id) function delItem($id)
{ {
return $this->newQuery()->where($this->primaryKey, $id)->delete(); return $this->newQuery()->where($this->primaryKey, $id)->delete();

View File

@ -0,0 +1,23 @@
<?php
namespace App\Models\Comment;
use App\Exceptions\ModelException;
use App\Models\Base\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
class PostCommentModel extends BaseModel
{
use SoftDeletes;
protected $table = 'customer_post_comment';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'pid',
'uid',
'content',
'created_at',
'deleted_at',
];
}

View File

@ -47,4 +47,20 @@ class CustomerChangeInfoLogModel extends CustomerBaseModel
return $this->addItem($aItem); return $this->addItem($aItem);
} }
function addUserActiveStatusLog($uid,$beforeValue,$value,$remark_key): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
$aLogInsert = [
'type' => CustomerChangeInfoLogModel::TYPE_CHANG_USER_ACTIVE_STATUS,
'uid' => $uid,
'column' => CustomerUserExtendModel::COL_IS_ACTIVE,
'before_value' => $beforeValue,
'pid' => CustomerChangeInfoLogModel::PID_SYSTEM,
'value' => $value,
'after_value' => $value,
'remark_key' => $remark_key,
'remark_desc' => CustomerChangeInfoLogModel::REMARK[$remark_key],
];
return $this->addLog($aLogInsert);
}
} }

View File

@ -2,9 +2,13 @@
namespace App\Models\Customer; namespace App\Models\Customer;
use App\Const\Queue;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Jobs\UserActiveStatusQueue;
use App\Models\Base\CustomerBaseModel; use App\Models\Base\CustomerBaseModel;
use App\Models\Post\PostPushBoxModel;
use App\Models\WebSocket\CustomerWsHistoryModel; use App\Models\WebSocket\CustomerWsHistoryModel;
use App\Structs\QueueUserActiveStatusStruct;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@ -36,8 +40,8 @@ class CustomerUserExtendModel extends CustomerBaseModel
//增加用户扩展信息 //增加用户扩展信息
function addExtend($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null function addExtend($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{ {
if(empty($aItem['uid'])) throw new ModelException('uid error'); if (empty($aItem['uid'])) throw new ModelException('uid error');
if($this->findItem($aItem['uid'],['uid'])) return null; //已存在 if ($this->findItem($aItem['uid'], ['uid'])) return null; //已存在
$sDateTime = date('Y-m-d H:i:s'); $sDateTime = date('Y-m-d H:i:s');
$aItem['updated_at'] = $sDateTime; $aItem['updated_at'] = $sDateTime;
return $this->addItem($aItem); return $this->addItem($aItem);
@ -46,33 +50,33 @@ class CustomerUserExtendModel extends CustomerBaseModel
//增加当前粉丝总数 //增加当前粉丝总数
function incrFansNum($uid): int function incrFansNum($uid): int
{ {
$oExtend = $this->findItem($uid,'uid'); $oExtend = $this->findItem($uid, 'uid');
if(!$oExtend) throw new ModelException('user extend not found'); if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->increment('fans_num'); return $this->newQuery()->where('uid', $uid)->increment('fans_num');
} }
//减去当前追随者总数 //减去当前追随者总数
function decrFansNum($uid): int function decrFansNum($uid): int
{ {
$oExtend = $this->findItem($uid,'uid'); $oExtend = $this->findItem($uid, 'uid');
if(!$oExtend) throw new ModelException('user extend not found'); if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->decrement('fans_num'); return $this->newQuery()->where('uid', $uid)->decrement('fans_num');
} }
//增加当前订阅总数 //增加当前订阅总数
function incrFollowNum($uid): int function incrFollowNum($uid): int
{ {
$oExtend = $this->findItem($uid,'uid'); $oExtend = $this->findItem($uid, 'uid');
if(!$oExtend) throw new ModelException('user extend not found'); if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->increment('follow_num'); return $this->newQuery()->where('uid', $uid)->increment('follow_num');
} }
//减去当前订阅总数 //减去当前订阅总数
function decrFollowNum($uid): int function decrFollowNum($uid): int
{ {
$oExtend = $this->findItem($uid,'uid'); $oExtend = $this->findItem($uid, 'uid');
if(!$oExtend) throw new ModelException('user extend not found'); if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->decrement('follow_num'); return $this->newQuery()->where('uid', $uid)->decrement('follow_num');
} }
//获取用户活跃信息 //获取用户活跃信息
@ -86,69 +90,92 @@ class CustomerUserExtendModel extends CustomerBaseModel
} }
//检测所有用户活跃状态 //检测所有用户活跃状态
function updateUserActiveStatus($date = null): void function updateAllUserActiveStatus($date = null): void
{ {
if(empty($date)) $date = Carbon::yesterday()->toDateString(); if (empty($date)) $date = Carbon::yesterday()->toDateString();
$oCustomerWsHistoryModel = new CustomerWsHistoryModel(); $oCustomerWsHistoryModel = new CustomerWsHistoryModel();
$aActiveUserIdList = $oCustomerWsHistoryModel->getActiveUserIdList($date); //三日内活跃用户 $aActiveUserIdList = $oCustomerWsHistoryModel->getActiveUserIdList($date); //三日内活跃用户
if(empty($aActiveUserIdList)) return; if (empty($aActiveUserIdList)) return;
$oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel(); $oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel();
$nowUid = 0; $nowUid = 0;
while (true){ while (true) {
try{ try {
Db::beginTransaction(); Db::beginTransaction();
$aUserList = $this->getUserActiveListLimit($nowUid, 500); $aUserExtendList = $this->getUserActiveListLimit($nowUid, 500);
if(empty($aUserList)) break; if (empty($aUserExtendList)) break;
$nowUid = max($aUserList->pluck('uid')->toArray()); $nowUid = max($aUserExtendList->pluck('uid')->toArray());
foreach ($aUserList as $oUser){ foreach ($aUserExtendList as $oUserExtend) {
$isChanged = false; if (in_array($oUserExtend->uid, $aActiveUserIdList)) { //在活跃列表中
$aLogInsert = [ if ($oUserExtend->is_active == self::IS_ACTIVE_YES) continue; //已经是活跃用户
'type' => CustomerChangeInfoLogModel::TYPE_CHANG_USER_ACTIVE_STATUS,
'uid' => $oUser->uid,
'column' => self::COL_IS_ACTIVE,
'before_value' => $oUser->is_active,
'pid' => CustomerChangeInfoLogModel::PID_SYSTEM,
];
if(in_array($oUser->uid, $aActiveUserIdList)){ //在活跃列表中
if($oUser->is_active == self::IS_ACTIVE_YES) continue; //已经是活跃用户
//变更用户状态 //变更用户状态
$res = $this->newQuery()->where('uid',$oUser->uid)->update(['is_active'=>self::IS_ACTIVE_YES]); $res = $this->newQuery()->where('uid', $oUserExtend->uid)->update(['is_active' => self::IS_ACTIVE_YES]);
if($res) { if ($res) {
$isChanged = true; //记录日志
$aLogInsert['value'] = self::IS_ACTIVE_YES; $oCustomerChangeInfoLogModel->addUserActiveStatusLog($oUserExtend->uid, $oUserExtend->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES);
$aLogInsert['after_value'] = self::IS_ACTIVE_YES; $this->activeUserStatusToQueueProducer($oUserExtend->uid); //投递到消息队列
$aLogInsert['remark_key'] = CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES;
$aLogInsert['remark_desc'] = CustomerChangeInfoLogModel::REMARK[CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES];
} }
}else{ //三日内不活跃 } else { //三日内不活跃
if($oUser->is_active == self::IS_ACTIVE_NO) continue; //已经是不活跃用户 if ($oUserExtend->is_active == self::IS_ACTIVE_NO) continue; //已经是不活跃用户
//变更用户状态 //变更用户状态
$res = $this->newQuery()->where('uid',$oUser->uid)->update(['is_active'=>self::IS_ACTIVE_NO]); $res = $this->newQuery()->where('uid', $oUserExtend->uid)->update(['is_active' => self::IS_ACTIVE_NO]);
if($res) { if ($res) {
$isChanged = true; //记录日志
$aLogInsert['value'] = self::IS_ACTIVE_NO; $oCustomerChangeInfoLogModel->addUserActiveStatusLog($oUserExtend->uid, $oUserExtend->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO);
$aLogInsert['after_value'] = self::IS_ACTIVE_NO;
$aLogInsert['remark_key'] = CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO;
$aLogInsert['remark_desc'] = CustomerChangeInfoLogModel::REMARK[CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO];
} }
} }
if($isChanged){ //有变化插入日志
$oCustomerChangeInfoLogModel->addLog($aLogInsert);
}
} }
Db::commit(); Db::commit();
}catch (\Exception $e){ } catch (\Exception $e) {
Log::error('updateUserActiveStatus error:'.$e->getMessage()); Log::error('updateUserActiveStatus error:' . $e->getMessage());
Db::rollBack(); Db::rollBack();
} }
} }
} }
//登录检测用户活跃状态
function updateUserActiveStatus($uid): void
{
try{
Db::beginTransaction();
$oCustomerWsHistoryModel = new CustomerWsHistoryModel();
$aActiveUserId = $oCustomerWsHistoryModel->findActiveUserId($uid, Carbon::yesterday()->toDateString()); //三日内活跃用户
if(empty($aActiveUserId)) return;
$oCustomerUserExtendModel = $this->newQuery()->where('uid', $uid)->first(['uid','is_active']);
if(!$oCustomerUserExtendModel) return;
$oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel();
$res = $this->newQuery()->where('uid', $uid)->update(['is_active' => self::IS_ACTIVE_YES]);
if ($res) {
//记录日志
$oCustomerChangeInfoLogModel->addUserActiveStatusLog($uid, $oCustomerUserExtendModel->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES);
$this->activeUserStatusToQueueProducer($uid); //投递到消息队列
}
Db::commit();
}catch (\Exception $e){
Log::error('updateUserActiveStatus error:' . $e->getMessage());
Db::rollBack();
}
}
//投递到消息队列,处理活跃推送信箱更新问题
function activeUserStatusToQueueProducer($uid): void
{
$params = QueueUserActiveStatusStruct::PARAMS;
$params['uid'] = $uid;
$params['queueCreatedAt'] = date('Y-m-d H:i:s');
UserActiveStatusQueue::dispatch($params)->onQueue(QueueUserActiveStatusStruct::QUEUE_NAME);
}
function activeUserStatusQueueConsumer($params): void
{
$uid = $params['uid'];
$oPostPushBoxModel = new PostPushBoxModel();
$oPostPushBoxModel->pullBigFanMasterPostConsumer($uid);
}
} }

View File

@ -1,9 +1,11 @@
<?php <?php
namespace App\Models\Post; namespace App\Models\Post;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Models\Base\BaseModel; use App\Models\Base\BaseModel;
use App\Tools\Tools; use App\Tools\Tools;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
class PostModel extends BaseModel class PostModel extends BaseModel
@ -15,7 +17,9 @@ class PostModel extends BaseModel
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $fillable = [ protected $fillable = [
'id', 'id',
'type',
'uuid', 'uuid',
'post_batch_sn',
'mid', 'mid',
'uid', 'uid',
'media', 'media',
@ -24,25 +28,65 @@ class PostModel extends BaseModel
'deleted_at', 'deleted_at',
]; ];
const TYPE_POST = PostPushBoxModel::TYPE_POST;
const TYPE_REPOST = PostPushBoxModel::TYPE_REPOST;
const TYPE = [
self::TYPE_POST => '推文',
self::TYPE_REPOST => '转发',
];
protected function media(): Attribute
{
return Attribute::make(
get: fn(string $value = '') => Tools::JonsDecode($value),
set: fn(array $value = []) => Tools::JonsEncode($value),
);
}
/** /**
* @throws ModelException * @throws ModelException
*/ */
function addPost($uid, $content = null, $media = null): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null function addPost($uid, $type = self::TYPE_POST, $content = null, $media = null, $mid = null, $sBachSn = null): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{ {
if(!$content && !$media) throw new ModelException('addPost params error'); if (!in_array($type, [self::TYPE_POST, self::TYPE_REPOST])) throw new ModelException('type params error');
$uuid = Tools::genUuid();
$bsn = 'BSN_' . ($sBachSn ?? Tools::genUuid());
if (!$content && !$media) throw new ModelException('addPost params error');
$aItem['type'] = $type;
$aItem['uid'] = $uid; $aItem['uid'] = $uid;
$aItem['uuid'] = Tools::genUuid(); $aItem['uuid'] = $uuid;
$aItem['post_batch_sn'] = $bsn;
$aItem['mid'] = $mid;
$aItem['media'] = $media; $aItem['media'] = $media;
$aItem['content'] = $content; $aItem['content'] = $content;
$sDateTime = date('Y-m-d H:i:s'); $sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime; $aItem['created_at'] = $sDateTime;
$res = $this->addItem($aItem); $res = $this->addItem($aItem);
if($res){ if ($res) {
$this->pushToQueue(self::TYPE_POST, $res->id);
} }
return $res; return $res;
} }
function addBatchPost(array $aPostList): void
{
$mid = null;
$bsn = 'BSN_' . ($sBachSn ?? Tools::genUuid());
foreach ($aPostList as $aPostItem) {
$oPost = $this->addPost($aPostItem['uid'], $aPostItem['type'], $aPostItem['content'], $aPostItem['media'], $mid, $bsn);
if ($oPost) {
$mid = $oPost->id;
}
}
}
//发送到消息队列处理新增post
function pushToQueue($type, $id): void
{
PostPushBoxModel::addPostQueueProducer(['type' => $type, 'id' => $id]);
}
/** /**
* @throws ModelException * @throws ModelException
*/ */
@ -50,9 +94,9 @@ class PostModel extends BaseModel
{ {
$oPost = $this->findItem($id); $oPost = $this->findItem($id);
$res = $this->delItem($id); $res = $this->delItem($id);
if($res){ if ($res) {
$oPostHistoryModel = new PostHistoryModel(); $oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL,$oPost->toArray()); $oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL, $oPost->toArray());
} }
return $res; return $res;
} }
@ -62,18 +106,18 @@ class PostModel extends BaseModel
*/ */
function delPostByUuid($uuid) function delPostByUuid($uuid)
{ {
$oPost = $this->findItemByWhere(['uuid'=>$uuid]); $oPost = $this->findItemByWhere(['uuid' => $uuid]);
$res = $this->newQuery()->where('uuid', $uuid)->delete(); $res = $this->newQuery()->where('uuid', $uuid)->delete();
if($res){ if ($res) {
$oPostHistoryModel = new PostHistoryModel(); $oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL,$oPost->toArray()); $oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL, $oPost->toArray());
} }
return $res; return $res;
} }
function getPostListByUid($uid): \Illuminate\Database\Eloquent\Collection|array function getPostListByUid($uid): \Illuminate\Database\Eloquent\Collection|array
{ {
return $this->getItemsByWhere(['uid'=>$uid]); return $this->getItemsByWhere(['uid' => $uid]);
} }
function getPostById($id): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null function getPostById($id): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
@ -86,13 +130,13 @@ class PostModel extends BaseModel
*/ */
function updatePostById($aItem): bool|int function updatePostById($aItem): bool|int
{ {
if(!isset($aItem['id'])) throw new ModelException('updatePostById params error'); if (!isset($aItem['id'])) throw new ModelException('updatePostById params error');
if(empty($aItem['id'])) throw new ModelException('updatePostById params error'); if (empty($aItem['id'])) throw new ModelException('updatePostById params error');
$oPost = $this->findItem($aItem['id']); $oPost = $this->findItem($aItem['id']);
$res = $this->updateItem($aItem); $res = $this->updateItem($aItem);
if($res){ if ($res) {
$oPostHistoryModel = new PostHistoryModel(); $oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT,$oPost->toArray()); $oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT, $oPost->toArray());
} }
return $res; return $res;
} }
@ -102,31 +146,32 @@ class PostModel extends BaseModel
*/ */
function updatePostByUuid($aItem): bool|int function updatePostByUuid($aItem): bool|int
{ {
if(!isset($aItem['uuid'])) throw new ModelException('updatePostByUuid params error'); if (!isset($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
if(empty($aItem['uuid'])) throw new ModelException('updatePostByUuid params error'); if (empty($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
$oPost = $this->findItemByWhere(['uuid'=>$aItem['uuid']]); $oPost = $this->findItemByWhere(['uuid' => $aItem['uuid']]);
$res = $this->updateItem($aItem,'uuid'); $res = $this->updateItem($aItem, 'uuid');
if($res){ if ($res) {
$oPostHistoryModel = new PostHistoryModel(); $oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT,$oPost->toArray()); $oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT, $oPost->toArray());
} }
return $res; return $res;
} }
function getPostListByMid($mid): \Illuminate\Database\Eloquent\Collection|array function getPostListByMid($mid): \Illuminate\Database\Eloquent\Collection|array
{ {
return $this->getItemsByWhere(['mid'=>$mid]); return $this->getItemsByWhere(['mid' => $mid]);
} }
function getPostListByUidMid($uid,$mid): \Illuminate\Database\Eloquent\Collection|array function getPostListByUidMid($uid, $mid): \Illuminate\Database\Eloquent\Collection|array
{ {
return $this->getItemsByWhere(['uid'=>$uid,'mid'=>$mid]); return $this->getItemsByWhere(['uid' => $uid, 'mid' => $mid]);
} }
function getPostListByUids($uids,$sDateLimit = null): \Illuminate\Database\Eloquent\Collection|array
function getPostListByUids($uids, $sDateLimit = null): \Illuminate\Database\Eloquent\Collection|array
{ {
if($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s',strtotime('-3 day')); if ($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s', strtotime('-3 day'));
return $this->newQuery()->where('created_at',$sDateLimit)->whereIn('uid',$uids)->get(); return $this->newQuery()->where('created_at', $sDateLimit)->whereIn('uid', $uids)->get();
} }

View File

@ -3,10 +3,16 @@
namespace App\Models\Post; namespace App\Models\Post;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Jobs\AddPostQueue;
use App\Models\Base\BaseModel; use App\Models\Base\BaseModel;
use App\Models\Comment\PostCommentModel;
use App\Models\Customer\CustomerUserExtendModel; use App\Models\Customer\CustomerUserExtendModel;
use App\Models\Follow\FollowModel; use App\Models\Follow\FollowModel;
use App\Models\Post\Structs\PostParamsStruct;
use App\Structs\QueueAddPostStruct;
use App\Tools\CollectOffsetLimit; use App\Tools\CollectOffsetLimit;
use App\Tools\Tools;
use Illuminate\Database\Eloquent\Casts\Attribute;
class PostPushBoxModel extends BaseModel class PostPushBoxModel extends BaseModel
{ {
@ -15,18 +21,29 @@ class PostPushBoxModel extends BaseModel
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $fillable = [ protected $fillable = [
'id', 'id',
'type',
'uid', 'uid',
'pid', 'pid',
'puuid', 'puuid',
'post_params',
'is_like', 'is_like',
'is_repost', 'is_repost',
'is_bookmark', 'is_bookmark',
'is_read', 'is_read',
'post_created_at',
'created_at', 'created_at',
'created_box_at',
'deleted_at', 'deleted_at',
]; ];
const TYPE_POST = 1;
const TYPE_REPOST = 2;
const TYPE_COMMENT = 3;
const TYPE = [
self::TYPE_POST => '推文',
self::TYPE_REPOST => '转发',
self::TYPE_COMMENT => '评论',
];
const IS_LIKE_DEFAULT = 1; const IS_LIKE_DEFAULT = 1;
const IS_LIKE_YES = 2; const IS_LIKE_YES = 2;
const IS_LIKE_NO = 3; const IS_LIKE_NO = 3;
@ -50,24 +67,69 @@ class PostPushBoxModel extends BaseModel
self::IS_BOOKMARK_YES => '已收藏', self::IS_BOOKMARK_YES => '已收藏',
]; ];
const IS_READ_DEFAULT = 1; const IS_READ_NO = 1;
const IS_READ_YES = 2; const IS_READ_YES = 2;
const IS_READ = [ const IS_READ = [
self::IS_READ_DEFAULT => '默认', self::IS_READ_NO => '默认',
self::IS_READ_YES => '已收藏', self::IS_READ_YES => '已收藏',
]; ];
protected function postParams(): Attribute
{
return Attribute::make(
get: fn (string $value = '') => Tools::JonsDecode($value),
set: fn (array $value = []) => Tools::JonsEncode($value),
);
}
public static function addPostQueueProducer(array $params): void
{
AddPostQueue::dispatch($params)->onQueue(QueueAddPostStruct::QUEUE_NAME);
}
/** /**
* 提交后调用事件 * 提交后调用事件,在消费队列跑推送
* @throws ModelException * @throws ModelException
*/ */
function newPostPushTask($id = null, $uuid = null) function addPostQueueConsumer(array $params)
{ {
if(empty($params)) return false;
if(isset($params['id'])) return false;
if(isset($params['type'])) return false;
$id = $params['id'];
$type = $params['type'];
if(!in_array($type,[self::TYPE_POST,self::TYPE_REPOST,self::TYPE_COMMENT])) return false;
if(empty($id)) return false;
$oPostModel = new PostModel(); $oPostModel = new PostModel();
$oPost = null; $oPost = null;
if ($id) $oPost = $oPostModel->findItem($id); $aPostParams = [];
if ($uuid) $oPost = $oPostModel->findItemByWhere(['uuid' => $uuid]);
//判断推送类型
if ($type == self::TYPE_POST) {
$postId = $id;
} elseif ($type == self::TYPE_REPOST) {
$postId = $id;
$oRePostModel = $oPostModel->findItem($id);
if(!$oRePostModel) return false;
$aPostParams[PostParamsStruct::REPOST_ORG_USER_ID] = $oRePostModel->uid;
$aPostParams[PostParamsStruct::REPOST_ORG_POST_ID] = $oRePostModel->mid;
} elseif ($type == self::TYPE_COMMENT) {
$oPostCommentModel = new PostCommentModel();
$oPostCommentModel = $oPostCommentModel->findItem($id);
if(!$oPostCommentModel) return false;
$postId = $oPostCommentModel->pid;
$aPostParams[PostParamsStruct::COMMENT_ID] = $oPostCommentModel->id;
$aPostParams[PostParamsStruct::COMMENT_USER_ID] = $oPostCommentModel->uid;
$aPostParams[PostParamsStruct::COMMENT_POST_ID] = $oPostCommentModel->pid;
$aPostParams[PostParamsStruct::COMMENT_CONTEXT] = $oPostCommentModel->content;
$aPostParams[PostParamsStruct::COMMENT_CONTEXT_CREATE_TIME] = $oPostCommentModel->created_at;
} else {
throw new ModelException('type error');
}
if ($postId) $oPost = $oPostModel->findItem($postId);
if (!$oPost) throw new ModelException('post not found'); if (!$oPost) throw new ModelException('post not found');
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000)); $iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
@ -80,11 +142,14 @@ class PostPushBoxModel extends BaseModel
$bSendMode = $CustomerUserExtend->fans_num < $iConfigFansPushLimit; $bSendMode = $CustomerUserExtend->fans_num < $iConfigFansPushLimit;
$iTotalCount = $this->countSendFans($bSendMode, $oPost->uid); //计算发送总数 $iTotalCount = $this->countSendFans($bSendMode, $oPost->uid); //计算发送总数
$aPost = $oPost->toArray();
if(empty($aPost)) return false;
$aPost['post_params'] = $aPostParams;
//分批发送 //分批发送
$oCollectOffsetLimit = new CollectOffsetLimit(); $oCollectOffsetLimit = new CollectOffsetLimit();
$oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($oPost, $bSendMode) { $oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($aPost, $bSendMode) {
$oFollowList = $this->getFansListWithPage($bSendMode, $oPost->uid, $offset, $limit); $oFollowList = $this->getFansListWithPage($bSendMode, $aPost['uid'], $offset, $limit);
$this->sendPostToBox($oPost, $oFollowList); $this->sendPostToBox($aPost, $oFollowList);
}); });
} }
@ -116,17 +181,15 @@ class PostPushBoxModel extends BaseModel
} }
//发送到推送信箱 //发送到推送信箱
function sendPostToBox($oPost, $oFollowList): void function sendPostToBox($aPost, $oFollowList): void
{ {
if (!$oFollowList) return; if (!$oFollowList) return;
$date = date('Y-m-d H:i:s');
foreach ($oFollowList as $oFollow) { foreach ($oFollowList as $oFollow) {
$aItem['uid'] = $oFollow->uid; $aItem['uid'] = $oFollow->uid;
$aItem['pid'] = $oPost->id; $aItem['pid'] = $aPost['id'];
$aItem['puuid'] = $oPost->uuid; $aItem['puuid'] = $aPost['uuid'];
$aItem['created_at'] = $oPost->created_at; $aItem['post_created_at'] = $aPost['created_at'];
$aItem['created_box_at'] = $date; $this->addItemWithCreateTime($aItem);
$this->addItem($aItem);
} }
} }
@ -138,20 +201,27 @@ class PostPushBoxModel extends BaseModel
* @param $limit * @param $limit
* @return \Illuminate\Database\Eloquent\Collection|array * @return \Illuminate\Database\Eloquent\Collection|array
*/ */
function getPushBoxList($uid, $last_id = 0, $limit = 20): \Illuminate\Database\Eloquent\Collection|array function getPushBoxList($uid, $last_id = 0, $limit = 20,$cols = ['*']): \Illuminate\Database\Eloquent\Collection|array
{ {
//活跃用户直接拉取未读消息 //活跃用户直接拉取未读消息
return $this->newQuery()->where('uid', $uid)->where('id', '>', $last_id)->where('is_read', self::IS_READ_DEFAULT)->orderBy('created_at', 'desc')->limit($limit)->get(); return $this->newQuery()
->where('uid', $uid)
// ->where('id', '>', $last_id)
->where('is_read', self::IS_READ_NO)
->orderBy('created_at', 'desc')
->limit($limit)
->get($cols);
//非活跃用户拉取大v消息在用户状态更新时已经调用过此处不用在做处理 //非活跃用户拉取大v消息在用户状态更新时已经调用过此处不用在做处理
} }
//非活跃拉取已跟随大v最新文章。 //非活跃拉取已跟随大v最新文章。
//放在用户状态更新时调用 //放在用户状态更新时调用
function pullBigFanMasterPost($uid) function pullBigFanMasterPostConsumer($uid)
{ {
//@@获取文章和转发文章和评论文章
//获取大v定义粉丝数,获取大于该粉丝数的大v文章 //获取大v定义粉丝数,获取大于该粉丝数的大v文章
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000)); $iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
//@此处需针对大量数据进行分批获取 //@@此处需针对大量数据进行分批获取
$oFollowModel = new FollowModel(); $oFollowModel = new FollowModel();
$oFollowList = $oFollowModel->getFollowListWithFansLimit($uid,$iConfigFansPushLimit,['a.follow_uid']); $oFollowList = $oFollowModel->getFollowListWithFansLimit($uid,$iConfigFansPushLimit,['a.follow_uid']);
if ($oFollowList->isEmpty()) return null; if ($oFollowList->isEmpty()) return null;
@ -161,7 +231,7 @@ class PostPushBoxModel extends BaseModel
$oPostList = $oPostModel->getPostListByUids($aFollowUid); $oPostList = $oPostModel->getPostListByUids($aFollowUid);
//将推文发送到信箱 //将推文发送到信箱
$this->sendPostToBoxByUid($oPostList,$uid); self::sendPostToBoxByUid($oPostList,$uid);
} }

View File

@ -0,0 +1,16 @@
<?php
namespace App\Models\Post\Structs;
class PostParamsStruct{
const REPOST_ORG_USER_ID = 'repostOrgUserId';
const REPOST_ORG_USERNAME = 'repostOrgUsername';
const REPOST_ORG_USER_NICKNAME = 'repostOrgUserNickname';
const REPOST_ORG_POST_ID = 'repostOrgPostId'; //原推文id
const COMMENT_ID = 'CommentId';
const COMMENT_USER_ID = 'CommentUserId';
const COMMENT_USERNAME = 'CommentUsername';
const COMMENT_POST_ID = 'CommentPostId';
const COMMENT_CONTEXT= 'CommentContext';
const COMMENT_CONTEXT_CREATE_TIME= 'CommentContextCreateTime';
}

View File

@ -46,4 +46,17 @@ class CustomerWsHistoryModel extends CustomerBaseModel
->toArray(); ->toArray();
} }
//获取判断用户是否活跃
//@需要加入缓存-缓存时间为3天
function findActiveUserId($uid, $date, $days = 3): array
{
return $this->newQuery()
->where('uid', $uid)
->where('event', self::EVENT_ON_CONNECT)
->where('status', self::STATUS_SUCCESS)
->whereBetween(DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d')"), [Carbon::parse($date)->subDays($days - 1)->toDateString(), Carbon::parse($date)->toDateString()])
->first(['uid'])
->toArray();
}
} }

View File

@ -0,0 +1,12 @@
<?php
namespace App\Structs;
class QueueAddPostStruct
{
const QUEUE_NAME = 'queue_add_post';
const PARAMS = [
'type'=>'',
'id'=>'',
];
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Structs;
class QueueUserActiveStatusStruct
{
const QUEUE_NAME = 'queue_user_active_status';
const PARAMS = [
'uid'=>'',
'queueCreatedAt'=>'',
];
}

View File

@ -51,6 +51,16 @@ class Tools
return Str::orderedUuid(); return Str::orderedUuid();
} }
static function JonsEncode(array $aData): string
{
return json_encode($aData, JSON_UNESCAPED_UNICODE);
}
static function JonsDecode(string $aData): string
{
return json_decode($aData, JSON_UNESCAPED_UNICODE);
}
} }