更换model目录

This commit is contained in:
cano
2024-03-04 04:28:48 +08:00
parent f4f61a5f4c
commit bebbee4184
29 changed files with 90 additions and 146 deletions

View File

@ -0,0 +1,9 @@
<?php
namespace App\Models\Api\Base;
use App\Models\Base\BaseModel;
class ApiBaseModel extends BaseModel {
}

View File

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

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models\Api\Customer;
use App\Models\Api\Base\ApiBaseModel;
use Illuminate\Support\Carbon;
class CustomerChangeInfoLogModel extends ApiBaseModel
{
protected $table = 'customer_change_info_log';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'uid',
'column',
'value',
'before_value',
'after_value',
'pid',
'remark_key',
'remark_desc',
'created_at',
];
const PID_SYSTEM = 0; //系统默认pid
const TYPE_CHANG_USER_ACTIVE_STATUS = 1;
const TYPE = [
self::TYPE_CHANG_USER_ACTIVE_STATUS => '修改用户活跃状态',
];
const REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES = 'dailyCheckUserActiveStatusYes';
const REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO = 'dailyCheckUserActiveStatusNo';
const REMARK = [
self::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES => '每日检查用户活跃状态-活跃',
self::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO => '每日检查用户活跃状态-不活跃',
];
function addLog($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
$sDateTime = Carbon::now()->toDateTimeString();
$aItem['created_at'] = $sDateTime;
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

@ -0,0 +1,19 @@
<?php
namespace App\Models\Api\Customer;
use App\Models\Api\Base\ApiBaseModel;
class CustomerLoginHistoryModel extends ApiBaseModel
{
protected $table = 'customer_login_history';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'status',
'uid',
'device',
'created_at',
];
}

View File

@ -0,0 +1,180 @@
<?php
namespace App\Models\Api\Customer;
use App\Exceptions\ModelException;
use App\Jobs\UserActiveStatusQueue;
use App\Models\Api\Post\PostPushBoxModel;
use App\Models\Api\WebSocket\ApiWsHistoryModel;
use App\Models\Api\Base\ApiBaseModel;
use App\Structs\QueueUserActiveStatusStruct;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class CustomerUserExtendModel extends ApiBaseModel
{
protected $table = 'customer_user_extend';
protected $primaryKey = 'uid';
protected $fillable = [
'uid',
'is_active',
'fans_num',
'follow_num',
'updated_at',
];
const COL_IS_ACTIVE = 'is_active';
//是否活跃用户
const IS_ACTIVE_YES = 1;
const IS_ACTIVE_NO = 2;
const IS_ACTIVE = [
self::IS_ACTIVE_YES => '活跃',
self::IS_ACTIVE_NO => '不活跃',
];
//增加用户扩展信息
function addExtend($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if (empty($aItem['uid'])) throw new ModelException('uid error');
if ($this->findItem($aItem['uid'], ['uid'])) return null; //已存在
$sDateTime = date('Y-m-d H:i:s');
$aItem['updated_at'] = $sDateTime;
return $this->addItem($aItem);
}
//增加当前粉丝总数
function incrFansNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->increment('fans_num');
}
//减去当前追随者总数
function decrFansNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->decrement('fans_num');
}
//增加当前订阅总数
function incrFollowNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->increment('follow_num');
}
//减去当前订阅总数
function decrFollowNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->decrement('follow_num');
}
//获取用户活跃信息
function getUserActiveListLimit($nowUid, $limit = 500): \Illuminate\Database\Eloquent\Collection|array
{
return $this->newQuery()
->where('id', '>=', $nowUid)
->limit($limit)
->orderBy('id')
->get(['uid', 'is_active']);
}
//检测所有用户活跃状态
function updateAllUserActiveStatus($date = null): void
{
if (empty($date)) $date = Carbon::yesterday()->toDateString();
$oCustomerWsHistoryModel = new ApiWsHistoryModel();
$aActiveUserIdList = $oCustomerWsHistoryModel->getActiveUserIdList($date); //三日内活跃用户
if (empty($aActiveUserIdList)) return;
$oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel();
$nowUid = 0;
while (true) {
try {
Db::beginTransaction();
$aUserExtendList = $this->getUserActiveListLimit($nowUid, 500);
if (empty($aUserExtendList)) break;
$nowUid = max($aUserExtendList->pluck('uid')->toArray());
foreach ($aUserExtendList as $oUserExtend) {
if (in_array($oUserExtend->uid, $aActiveUserIdList)) { //在活跃列表中
if ($oUserExtend->is_active == self::IS_ACTIVE_YES) continue; //已经是活跃用户
//变更用户状态
$res = $this->newQuery()->where('uid', $oUserExtend->uid)->update(['is_active' => self::IS_ACTIVE_YES]);
if ($res) {
//记录日志
$oCustomerChangeInfoLogModel->addUserActiveStatusLog($oUserExtend->uid, $oUserExtend->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES);
$this->activeUserStatusToQueueProducer($oUserExtend->uid); //投递到消息队列
}
} else { //三日内不活跃
if ($oUserExtend->is_active == self::IS_ACTIVE_NO) continue; //已经是不活跃用户
//变更用户状态
$res = $this->newQuery()->where('uid', $oUserExtend->uid)->update(['is_active' => self::IS_ACTIVE_NO]);
if ($res) {
//记录日志
$oCustomerChangeInfoLogModel->addUserActiveStatusLog($oUserExtend->uid, $oUserExtend->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO);
}
}
}
Db::commit();
} catch (\Exception $e) {
Log::error('updateUserActiveStatus error:' . $e->getMessage());
Db::rollBack();
}
}
}
//登录检测用户活跃状态
function updateUserActiveStatus($uid): void
{
try{
Db::beginTransaction();
$oCustomerWsHistoryModel = new ApiWsHistoryModel();
$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

@ -0,0 +1,143 @@
<?php
namespace App\Models\Api\Customer;
use App\Cache\Table\TableCustomerUserCache;
use App\Models\Api\Base\ApiBaseModel;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
class CustomerUserModel extends ApiBaseModel
{
protected $table = 'customer_users';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'status',
'im_user_id',
'country_name',
'username',
'password',
'nickname',
'email',
'phone_area',
'phone',
'is_google_auth',
'google_auth_secret',
'created_at',
'updated_at',
];
protected $hidden = [
'password',
'google_auth_secret',
];
//插入密码hash加密
protected function password(): Attribute
{
return Attribute::make(
set: fn(string $value) => Hash::make($value),
);
}
//对比密码是否正确
function checkPasswd($iUid, $sPasswd): bool
{
$oUser = $this->where('id', $iUid)->first();
if (empty($oUser)) return false;
return Hash::check($sPasswd, $oUser->password);
}
//添加用户
function addUser($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
$sDateTime = Carbon::now()->toDateTimeString();
$aItem['created_at'] = $sDateTime;
$aItem['updated_at'] = $sDateTime;
return $this->addItem($aItem);
}
//查找账户-所有方式
function findItemByAccount($aData, $col = ['*']): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
$oQuery = $this->newQuery();
if (!empty($aData['username'])) {
$oQuery->orWhere('username', $aData['username']);
} elseif (!empty($aData['email'])) {
$oQuery->orWhere('email', $aData['email']);
} elseif (!empty($aData['phone']) && !empty($aData['phone_area'])) {
$oQuery->orWhere([
'phone' => $aData['phone'],
'phone_area' => $aData['phone_area'],
]);
} else {
throw new \Exception('findItemByAccount params error');
}
return $oQuery->first($col);
}
//查找账户-用户名
function findItemByUsername($sUsername, $col = ['*']): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->newQuery()->where('username', $sUsername)->first($col);
}
//查找账户-手机
function findItemByPhone($sPhoneArea, $sPhone, $col = ['*']): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->newQuery()->where('phone_area', $sPhoneArea)->where('phone', $sPhone)->first($col);
}
//查找账户-邮箱
function findItemByEmail($sEmail, $col = ['*']): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->newQuery()->where('email', $sEmail)->first($col);
}
//根据uid从缓存中查询用户信息不存在则从数据库中查询
/**
* @throws \Exception
*/
function findUserByUidWithCache($iUid): array|null
{
$oTableCustomerUserCache = new TableCustomerUserCache();
$oTableCustomerUserCache->setPrimaryKey($iUid);
return $oTableCustomerUserCache->getCacheData();
// return Cache::remember($this->getCacheKey($iUid), RedisConst::ORM_FIND_CACHE_SECOND, function () use ($iUid) {
// return $this->findItem($iUid);
// });
}
// function delItemFromCache($iUid): bool
// {
// return Cache::delete($this->getCacheKey($iUid));
// }
// //生成user缓存key
// function getCacheKey($iUid): string
// {
// if(empty($iUid)) throw new \Exception('getCacheKey params error');
// return RedisConst::ORM_CACHE_USER . $iUid;
// }
// function setUserInfo($iUid,$sNickname): bool|int
// {
// return $this->updateItem([
// 'id' => $iUid,
// 'nickname' => $sNickname,
// 'email' => $sNickname,
// 'phone_area' => $sNickname,
// ]);
// }
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Models\Api\Follow;
use App\Exceptions\ModelException;
use App\Models\Api\Base\ApiBaseModel;
class FollowHistoryModel extends ApiBaseModel
{
protected $table = 'customer_follow_history';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'method',
'uid',
'follow_uid',
'created_at',
];
const METHOD_FOLLOW = 1;
const METHOD_UNFOLLOW = 2;
const METHOD = [
self::METHOD_FOLLOW => '关注',
self::METHOD_UNFOLLOW => '取关',
];
/**
* @throws ModelException
*/
function addFollowHistory($method, $uid, $follow_uid): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if(!in_array($method,self::METHOD)) throw new ModelException('method error');
$aItem['method'] = $method;
$aItem['uid'] = $uid;
$aItem['follow_uid'] = $follow_uid;
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
return $this->addItem($aItem);
}
}

View File

@ -0,0 +1,173 @@
<?php
namespace App\Models\Api\Follow;
use App\Exceptions\ModelException;
use App\Models\Api\Base\ApiBaseModel;
use App\Models\Api\Customer\CustomerUserExtendModel;
use Illuminate\Support\Facades\DB;
class FollowModel extends ApiBaseModel
{
protected $table = 'customer_follow';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'uid',
'follow_uid',
'created_at',
];
/**
* 添加订阅 订阅别人
* @throws ModelException
*/
function addFollow($uid, $follow_uid): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
$aItem['uid'] = $uid;
$aItem['follow_uid'] = $follow_uid;
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
$res = $this->addItem($aItem);
if ($res) {
//增加到历史记录里
$oFollowHistoryModel = new FollowHistoryModel();
$oFollowHistoryModel->addFollowHistory(FollowHistoryModel::METHOD_FOLLOW, $uid, $follow_uid);
try {
DB::beginTransaction();
//增加到user_extends中
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oCustomerUserExtendModel->incrFollowNum($uid);
$oCustomerUserExtendModel->incrFansNum($follow_uid);
DB::commit();
}catch (\Exception $e){
DB::rollBack();
throw new ModelException($e->getMessage());
}
}
return $res;
}
/**
* 取消订阅
* @throws ModelException
*/
function unFollow($uid, $follow_uid)
{
$res = $this->newQuery()->where('uid', $uid)->where('follow_uid', $follow_uid)->delete();
if ($res) {
//增加到历史记录里
$oFollowHistoryModel = new FollowHistoryModel();
$oFollowHistoryModel->addFollowHistory(FollowHistoryModel::METHOD_UNFOLLOW, $uid, $follow_uid);
try {
DB::beginTransaction();
//增加到user_extends中
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oCustomerUserExtendModel->decrFollowNum($uid);
$oCustomerUserExtendModel->decrFansNum($follow_uid);
DB::commit();
}catch (\Exception $e){
DB::rollBack();
throw new ModelException($e->getMessage());
}
}
return $res;
}
//获取user following(订阅)列表
function getFollowList($uid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->newQuery()->where('uid', $uid)->get();
}
//获取关注列表中大v用户
function getFollowListWithFansLimit($uid,$iFansLimit = 2000,$col = ['a.follow_uid']): \Illuminate\Support\Collection
{
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oFollowModel = new FollowModel();
$oModel = DB::table($oFollowModel->getTable() . ' as a');
return $oModel->where('a.uid', $uid)
->leftjoin($oCustomerUserExtendModel->getTable() . ' as b', 'a.follow_uid', '=', 'b.uid')
->where('b.fans_num','>=', $iFansLimit)
->get($col);
}
//检测是否双向关注
function isEachOtherFollow($uid, $follow_uid): bool
{
$aFollow = $this->isFollow($uid, $follow_uid);
$aFollow2 = $this->isFollow($follow_uid, $uid);
if ($aFollow && $aFollow2) {
return true;
}
return false;
}
function isFollow($uid, $follow_uid): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
return $this->newQuery()->where('uid', $uid)->where('follow_uid', $follow_uid)->first(['id']);
}
//获取关注数
function getFollowCount($uid): int
{
return $this->newQuery()->where('uid', $uid)->count();
}
//获取被关注列表
function getFansList($uid, $col = ['*'], $offset = null, $limit = null): \Illuminate\Database\Eloquent\Collection|array
{
$oModel = $this->newQuery();
if ($offset) $oModel->offset($offset);
if ($limit) $oModel->limit($offset);
return $oModel->where('follow_uid', $uid)->get($col);
}
//检测是否被关注
function isFollowed($uid, $follow_uid): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
return $this->newQuery()->where('uid', $follow_uid)->where('follow_uid', $uid)->first(['id']);
}
//获取粉丝数(被关注数)
function getFansCount($uid): int
{
return $this->newQuery()->where('follow_uid', $uid)->count(['id']);
}
//获取活跃粉丝列表
function getActiveFansUidList($uid, $col = ['a.*'], $offset = null, $limit = null): \Illuminate\Support\Collection
{
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oFollowModel = new FollowModel();
$oModel = DB::table($oFollowModel->getTable() . ' as a');
if ($offset) $oModel->offset($offset);
if ($limit) $oModel->limit($offset);
return $oModel->where('a.follow_uid', $uid)
->leftjoin($oCustomerUserExtendModel->getTable() . ' as b', 'a.uid', '=', 'b.uid')
->where('b.is_active', CustomerUserExtendModel::IS_ACTIVE_YES)
->get($col);
}
//获取活跃粉丝计数
function getActiveFansUidListCount($uid, $col = ['a.id']): int
{
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oFollowModel = new FollowModel();
return DB::table($oFollowModel->getTable() . ' as a')->where('a.follow_uid', $uid)
->leftjoin($oCustomerUserExtendModel->getTable() . ' as b', 'a.uid', '=', 'b.uid')
->where('b.is_active', CustomerUserExtendModel::IS_ACTIVE_YES)
->count($col);
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Models\Api\Post;
use App\Exceptions\ModelException;
use App\Models\Api\Base\ApiBaseModel;
class PostHistoryModel extends ApiBaseModel
{
protected $table = 'customer_post_history';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'method',
'oid',
'uuid',
'mid',
'uid',
'media',
'content',
'created_at',
];
const METHOD_ADD = 1;
const METHOD_DEL = 2;
const METHOD_EDIT = 4;
const METHOD = [
self::METHOD_ADD => '新增',
self::METHOD_DEL => '删除',
self::METHOD_EDIT => '编辑',
];
/**
* @throws ModelException
*/
function addPostHistory($method, $aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if(!in_array($method,self::METHOD)) throw new ModelException('addPostHistory method error');
if(!isset($aItem['uuid'])) throw new ModelException('addPostHistory params error');
$aItem['oid'] = $aItem['id'];
unset($aItem['id']);
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
$aItem['method'] = $method;
return $this->addItem($aItem);
}
}

View File

@ -0,0 +1,209 @@
<?php
namespace App\Models\Api\Post;
use App\Exceptions\ModelException;
use App\Models\Api\Base\ApiBaseModel;
use App\Models\Api\Post\Structs\PostParamsStruct;
use App\Tools\Tools;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\SoftDeletes;
class PostModel extends ApiBaseModel
{
//软删除
use SoftDeletes;
protected $table = 'customer_post';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'uuid',
'post_batch_sn',
'mid',
'uid',
'media',
'content',
'post_params',
'created_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),
);
}
protected function postParams(): Attribute
{
return Attribute::make(
get: fn(string $value = '') => Tools::JonsDecode($value),
set: fn(array $value = []) => Tools::JonsEncode($value),
);
}
/**
* @throws ModelException
*/
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 (!in_array($type, [self::TYPE_POST, self::TYPE_REPOST])) throw new ModelException('type params error');
$aPostParams = [];
if($type == self::TYPE_REPOST){
$oRePostModel = $this->findItem($mid);
$aPostParams[PostParamsStruct::REPOST_ORG_USER_ID] = $oRePostModel->uid;
$aPostParams[PostParamsStruct::REPOST_ORG_POST_ID] = $oRePostModel->mid;
}
$uuid = Tools::genUuid();
$bsn = 'BSN_' . ($sBachSn ?? Tools::genUuid());
if (!$content && !$media) throw new ModelException('addPost params error');
$aItem['type'] = $type;
$aItem['uid'] = $uid;
$aItem['uuid'] = $uuid;
$aItem['post_batch_sn'] = $bsn;
$aItem['mid'] = $mid;
$aItem['media'] = $media;
$aItem['content'] = $content;
$aItem['post_params'] = $aPostParams;
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
$res = $this->addItem($aItem);
if ($res) {
$this->pushToQueue(self::TYPE_POST, $res->id);
}
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
*/
function delPostById($id)
{
$oPost = $this->findItem($id);
$res = $this->delItem($id);
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL, $oPost->toArray());
}
return $res;
}
/**
* @throws ModelException
*/
function delPostByUuid($uuid)
{
$oPost = $this->findItemByWhere(['uuid' => $uuid]);
$res = $this->newQuery()->where('uuid', $uuid)->delete();
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL, $oPost->toArray());
}
return $res;
}
function getPostListByUid($uid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['uid' => $uid]);
}
function getPostById($id): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->findItem($id);
}
/**
* @throws ModelException
*/
function updatePostById($aItem): bool|int
{
if (!isset($aItem['id'])) throw new ModelException('updatePostById params error');
if (empty($aItem['id'])) throw new ModelException('updatePostById params error');
$oPost = $this->findItem($aItem['id']);
$res = $this->updateItem($aItem);
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT, $oPost->toArray());
}
return $res;
}
/**
* @throws ModelException
*/
function updatePostByUuid($aItem): bool|int
{
if (!isset($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
if (empty($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
$oPost = $this->findItemByWhere(['uuid' => $aItem['uuid']]);
$res = $this->updateItem($aItem, 'uuid');
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT, $oPost->toArray());
}
return $res;
}
function getPostListByMid($mid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['mid' => $mid]);
}
function getPostListByUidMid($uid, $mid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['uid' => $uid, 'mid' => $mid]);
}
function getPostListByUids($uids, $sDateLimit = null,$cols = ['*'],$offset = null, $limit = null): \Illuminate\Database\Eloquent\Collection|array
{
$oModel = $this->newQuery();
if ($offset) $oModel->offset($offset);
if ($limit) $oModel->limit($offset);
if ($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s', strtotime('-3 day'));
return $oModel
->where('created_at', $sDateLimit)
->whereIn('uid', $uids)
->orderBy('created_at')
->get($cols);
}
function CountPostListByUids($uids, $sDateLimit = null): int
{
if ($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s', strtotime('-3 day'));
return $this->newQuery()->where('created_at', $sDateLimit)->whereIn('uid', $uids)->orderBy('created_at')->count();
}
}

View File

@ -0,0 +1,256 @@
<?php
namespace App\Models\Api\Post;
use App\Exceptions\ModelException;
use App\Jobs\AddPostQueue;
use App\Models\Api\Base\ApiBaseModel;
use App\Models\Api\Comment\PostCommentModel;
use App\Models\Api\Customer\CustomerUserExtendModel;
use App\Models\Api\Follow\FollowModel;
use App\Models\Api\Post\Structs\PostParamsStruct;
use App\Structs\QueueAddPostStruct;
use App\Tools\CollectOffsetLimit;
use App\Tools\Tools;
use Illuminate\Database\Eloquent\Casts\Attribute;
class PostPushBoxModel extends ApiBaseModel
{
protected $table = 'customer_post_push_box';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'uid',
'pid',
'puuid',
'post_params',
'is_like',
'is_repost',
'is_bookmark',
'is_read',
'post_created_at',
'created_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_YES = 2;
const IS_LIKE_NO = 3;
const IS_LIKE = [
self::IS_LIKE_DEFAULT => '默认',
self::IS_LIKE_YES => '喜欢',
self::IS_LIKE_NO => '不喜欢',
];
const IS_REPOST_DEFAULT = 1;
const IS_REPOST_YES = 2;
const IS_REPOST = [
self::IS_REPOST_DEFAULT => '默认',
self::IS_REPOST_YES => '已转发',
];
const IS_BOOKMARK_DEFAULT = 1;
const IS_BOOKMARK_YES = 2;
const IS_BOOKMARK = [
self::IS_BOOKMARK_DEFAULT => '默认',
self::IS_BOOKMARK_YES => '已收藏',
];
const IS_READ_NO = 1;
const IS_READ_YES = 2;
const IS_READ = [
self::IS_READ_NO => '默认',
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
*/
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();
$oPost = null;
$aPostParams = [];
//判断推送类型
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');
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
//查询粉丝数
$CustomerUserExtendModel = new CustomerUserExtendModel();
$CustomerUserExtend = $CustomerUserExtendModel->findItem($oPost->uid);
if (!$CustomerUserExtend) throw new ModelException('user extend not found');
//粉丝数少于$iConfigFansPushLimit的用户走写扩散流程所有粉丝信箱插入一条
$bSendMode = $CustomerUserExtend->fans_num < $iConfigFansPushLimit;
$iTotalCount = $this->countSendFans($bSendMode, $oPost->uid); //计算发送总数
$aPost = $oPost->toArray();
if (empty($aPost)) return false;
$aPost['post_params'] = $aPostParams;
//分批发送
$oCollectOffsetLimit = new CollectOffsetLimit();
$oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($aPost, $bSendMode) {
$oFollowList = $this->getFansListWithPage($bSendMode, $aPost['uid'], $offset, $limit);
if(empty($oFollowList)) return;
$this->sendPostToBox($aPost, $oFollowList);
});
}
function getFansListWithPage($bAllFans, $uid, $offset = 0, $limit = 2000): \Illuminate\Database\Eloquent\Collection|array|\Illuminate\Support\Collection
{
$oFollowModel = new FollowModel();
//粉丝数少于$iConfigFansPushLimit的用户走写扩散流程所有粉丝信箱插入一条
if ($bAllFans) {
$oFollowList = $oFollowModel->getFansList($uid, ['uid'], $offset, $limit); //获取所有粉丝列表
} else { //读扩散流程(只针对活跃粉丝信箱插入一条)
//获取活跃粉丝列表
//@活跃粉丝数量过大需要分批处理
$oFollowList = $oFollowModel->getActiveFansUidList($uid, ['a.uid'], $offset, $limit);
}
return $oFollowList;
}
function countSendFans($bAllFans, $uid): int
{
$oFollowModel = new FollowModel();
if ($bAllFans) {
$iCount = $oFollowModel->getFansCount($uid); //获取所有粉丝列表
} else { //读扩散流程(只针对活跃粉丝信箱插入一条)
//获取活跃粉丝列表
$iCount = $oFollowModel->getActiveFansUidListCount($uid);
}
return $iCount;
}
//发送到推送信箱
function sendPostToBox($aPost, $oFollowList): void
{
if (!$oFollowList) return;
foreach ($oFollowList as $oFollow) {
$aItem['uid'] = $oFollow->uid;
$aItem['pid'] = $aPost['id'];
$aItem['puuid'] = $aPost['uuid'];
$aItem['post_created_at'] = $aPost['created_at'];
$this->addItemWithCreateTime($aItem);
}
}
/**
* 拉取推送信箱列表
* @param $uid
* @param $last_id //上次最后一条id
* @param $limit
* @return \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_NO)
->orderBy('created_at', 'desc')
->limit($limit)
->get($cols);
//非活跃用户拉取大v消息在用户状态更新时已经调用过此处不用在做处理
}
//非活跃拉取已跟随大v最新文章。
//放在用户状态更新时调用
function pullBigFanMasterPostConsumer($uid)
{
//获取文章和转发文章
//获取大v定义粉丝数,获取大于该粉丝数的大v文章
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
$oFollowModel = new FollowModel();
$oFollowList = $oFollowModel->getFollowListWithFansLimit($uid, $iConfigFansPushLimit, ['a.follow_uid']);
if ($oFollowList->isEmpty()) return null;
$aFollowList = $oFollowList->toArray();
$aFollowUid = array_column($aFollowList, 'follow_uid');
$oPostModel = new PostModel();
//分批发送到信箱
//@@大v评论拉取到自己信箱
$iTotalCount = $oPostModel->CountPostListByUids($aFollowUid);
$oCollectOffsetLimit = new CollectOffsetLimit();
$oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($oPostModel,$aFollowUid,$uid) {
$oPostList = $oPostModel->getPostListByUids($aFollowUid,null,['*'],$offset, $limit);
if(empty($oPostList)) return;
$this->sendPostToBoxByUid($oPostList->toArray(), $uid);
});
}
function sendPostToBoxByUid(array $oPostList, $uid): void
{
foreach ($oPostList as $oPost) {
$aItem['type'] = $oPost->type;
$aItem['uid'] = $uid;
$aItem['pid'] = $oPost->id;
$aItem['puuid'] = $oPost->uuid;
$aItem['post_params'] = $oPost->post_params;
$aItem['post_created_at'] = $oPost->created_at;
$this->addItemWithCreateTime($aItem);
}
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Models\Api\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

@ -0,0 +1,59 @@
<?php
namespace App\Models\Api\WebSocket;
use App\Models\Api\Base\ApiBaseModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class ApiWsHistoryModel extends ApiBaseModel
{
protected $table = 'customer_ws_history';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'event',
'status',
'uid',
'device',
'created_at',
];
const EVENT_ON_CONNECT = 1;
const EVENT = [
self::EVENT_ON_CONNECT => 'onConnect',
];
const STATUS_SUCCESS = 1;
const STATUS_FAIL = 2;
const STATUS = [
self::STATUS_SUCCESS => '成功',
self::STATUS_FAIL => '失败',
];
function getActiveUserIdList($date, $days = 3): array
{
return $this->newQuery()
->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()])
->distinct(['uid'])
->get()
->pluck('uid')
->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();
}
}