<?php
namespace App\HttpController\Wx;
use App\Common\StatusCode;
use App\HttpController\Base;
use App\Logic\Common\CodeException;
use App\Logic\Common\RoomInfo;
use App\Logic\Common\Tools;
use App\Logic\Common\WechatUser;
use App\Utility\Driver\MongoClientDriver;
use App\Utility\MongoClient;
use App\Utility\RedisClient;
class RoomBrowseRecordManage extends Base
{
public $wechat_user_space_id;
private $userinfo;
public function onRequest(?string $action): bool
{
if (!parent::onRequest($action)) {
return false;
}
try {
$this->jwtInit();
}catch (CodeException $exception)
{
return $this->responseJson($exception->getErrorCode(), $exception->getErrorMessage());
}
$this->wechat_user_space_id = $this->jwtInfo()->crypted_info['userinfo']['wechat_user_space_id'];
$this->userinfo = $this->jwtInfo()->crypted_userinfo;
return true;
}
private function _getPipeline($wechat_user_space_id,$curentPage,$pageNum){
$skip=intval(($curentPage-1)*$pageNum);
$pipeline = [
[
'$match' => [
'wechat_user_space_id' => intval($wechat_user_space_id)
]
],
[
'$project' => [
'room_id' => '$room_id',
'room_name' => '$room_name',
'room_desc' => '$room_desc',
'room_pic' => '$room_pic',
'create_time' => '$create_time',
]
],
[
'$group' => [
'_id' => ['room_id' => '$room_id'],
'create_time' => ['$max' => '$create_time'],
'count' => ['$sum' => 1],
'room_name' => ['$last' => '$room_name'],
'room_desc' => ['$last' => '$room_desc'],
'room_pic' => ['$last' => '$room_pic'],
'room_id' => ['$last' => '$room_id'],
'id' => ['$last' => '$_id'],
]
],
[
'$sort' => ['create_time' => -1]
],
[
'$skip' =>$skip
],
[
'$limit' =>intval($pageNum)
]
];
return $pipeline;
}
private function _getOptions($wechat_user_space_id,$curentPage,$pageNum){
$options = [
'aggregate' =>'ny_room_browse_record',
'pipeline' => $this->_getPipeline($wechat_user_space_id,$curentPage,$pageNum),
'cursor' => new \stdClass(),
];
return $options;
}
public function recordList(){
$params = $this->request()->getRequestParam();
$curentPage=$params['curentPage']??1;
$pageNum=$params['pageNum']??10;
$options=$this->_getOptions($this->wechat_user_space_id,$curentPage,$pageNum);
$key = 'es3_room_browse_record_'.$this->wechat_user_space_id."_".$curentPage."_".$pageNum;
$result= RedisClient::getWxDataWithLock($key,15,function ()use($options){
return $this->_getRecordListFromMongo($options);
});
$this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => $result]);
}
private function _getRecordListFromMongo($options){
$result= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($options){
$driver->getDb();
$driver->collection = 'ny_room_browse_record';
$list = $driver->executeCommandMongo($options);
$listNew=[];
foreach ($list as $k=>$v){
$listNew[$k]['room_name']=$v->room_name;
$listNew[$k]['room_desc']=$v->room_desc;
$listNew[$k]['room_pic']=$v->room_pic;
$listNew[$k]['id']=json_decode(json_encode($v->id),true)['$oid'];
}
return $listNew;
});
return $result??[];
}
public function addRecord(){
$rules = ['room_id'=>'require','terminal'=>'require'];
$params = $this->checkRequestParam($rules);
if($params === false)
{
$this->writeJsonSelf(['code' =>StatusCode::param_error,'msg' => 'param error','data'=>array()]);
return false;
}
$this->_addUserRoomRelation($params);
$redis_boj = RedisClient::getInstance();
$app_row = RoomInfo::appRow($params['room_id']);
$res = $redis_boj->lpush('k8s_queue',serialize([
'type' => 'func_job',
'func' => 'roomBrowseRecordAdd',
'data' => [
'room_id'=>$params['room_id'],
'wechat_user_space_id' => $this->wechat_user_space_id,
'terminal' => $params['terminal'],
'room_name' =>$app_row['push_app_nick'],
'room_pic' => $app_row['app_cover'] ? spliceImageUrl($app_row['app_cover']) : RoomInfo::getThemeCover($app_row['theme_type']),
'room_desc' =>$app_row['desc'],
'is_delete' =>2,
'create_time' =>time(),
]
]));
if (!$res){
$this->writeJsonSelf(['code' =>StatusCode::fail,'msg' => '操作失败','data'=>array()]);
return false;
}
$this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => []]);
}
protected function _addUserRoomRelation($params)
{
$save['app_id'] = $params['room_id'];
$save['ip']= getRealIP($this->request());
$save['device'] = Tools::deviceType($this->request()->getHeaderLine('user-agent'));
$logic = new WechatUser();
$logic->addUserRoomRelation($this->userinfo['wechat_user_space_id'], $save);
return true;
}
public function delRecord(){
if (!$this->wechat_user_space_id){
$this->writeJsonSelf(['code' =>StatusCode::param_error,'msg' => '您不能删除浏览记录','data'=>array()]);
return false;
}
$wechat_user_space_id=$this->wechat_user_space_id;
$res= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($wechat_user_space_id){
$driver->getDb();
$driver->collection = 'ny_room_browse_record';
$ret = $driver->delete(['wechat_user_space_id'=>$wechat_user_space_id]);
return $ret;
});
if (!$res){
$this->writeJsonSelf(['code' =>StatusCode::fail,'msg' => '操作失败','data'=>array()]);
return false;
}
$this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => []]);
}
public function delOneRecord(){
$rules = ['room_browse_record_id'=>'require'];
$params = $this->checkRequestParam($rules);
if($params === false)
{
$this->writeJsonSelf(['code' =>StatusCode::param_error,'msg' => 'param error','data'=>array()]);
return false;
}
$room_browse_record_id=$params['room_browse_record_id'];
$res= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($room_browse_record_id){
$driver->getDb();
$driver->collection = 'ny_room_browse_record';
$ret = $driver->delete(['_id'=>new \MongoDB\BSON\ObjectID($room_browse_record_id)]);
return $ret;
});
if (!$res){
$this->writeJsonSelf(['code' =>StatusCode::fail,'msg' => '操作失败','data'=>array()]);
return false;
}
$this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => []]);
}
}
<?php
namespace App\Utility\Driver;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\SyncInvoker\AbstractInvoker;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query;
use MongoDB\Driver\WriteConcern;
class MongoClientDriver extends AbstractInvoker
{
protected $db;
protected $database;
public $collection;
protected $bulk;
protected $writeConcern;
protected $defaultConfig;
function getDb($config = []):Manager
{
if($this->db == null){
$this->defaultConfig = Config::getInstance()->getConf('MONGO');
$config = array_merge($this->defaultConfig, $config);
$mongoServer = "mongodb://";
if ($config['username']) {
$mongoServer .= $config['username'] . ':' . $config['password'] . '@';
}
$mongoServer .= $config['hostname'];
if ($config['port']) {
$mongoServer .= ':' . $config['port'];
}
$mongoServer .= '/' . $config['database'];
if(isset($config['uri'])){
$mongoServer = $config['uri'];
}
$this->db = new Manager($mongoServer);
$this->database = $config['database'];
isset($config['collection']) && $this->collection = $config['collection'];
}
$this->bulk = new BulkWrite();
$this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
return $this->db;
}
protected function onException(\Throwable $throwable)
{
Trigger::getInstance()->throwable($throwable);
return null;
}
public function executeCommandMongo($options) {
$command = new Command($options);
$result = $this->db->executeCommand($this->database, $command);
$res = $result->toArray();
return $res;
}
public function count($where = []) {
$command = new Command(['count' => $this->collection, 'query' => $where]);
$result = $this->db->executeCommand($this->database, $command);
$res = $result->toArray();
$count = 0;
if ($res) {
$count = $res[0]->n;
}
return $count;
}
public function query($where = [], $option = []) {
$query = new Query($where, $option);
$result = $this->db->executeQuery("$this->database.$this->collection", $query);
$ret = [];
foreach ($result as $document) {
$ret[] = (array)$document;
}
return $ret;
}
public function update($where = [], $update = [], $multi = false, $upsert = false) {
$this->bulk->update($where, ['$set' => $update], ['multi' => $multi, 'upsert' => $upsert]);
$result = $this->db->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
return $result->getModifiedCount();
}
public function insert($data = []) {
$this->bulk->insert($data);
$result = $this->db->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
return $result->getInsertedCount();
}
public function delete($where = [], $limit = 1) {
$this->bulk->delete($where, ['limit' => $limit]);
$result = $this->db->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
return $result->getDeletedCount();
}
public function mongoId($id){
return new \MongoId($id);
}
}