<?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\Model\RoomBrowseRecord;
use App\Utility\MysqlClient;
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;
}
public function test(){
$app_id=1;
$res= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($app_id){
$options =[
'group' => [
'ns' => 'ny_room_browse_record',
// '$reduce' => new MongoDB\BSON\JavaScript('function(doc, prev){prev.items.push(doc.FUserName);}'),
'$reduce' => 'function (obj, prev) {
if (prev.create_time_max < obj.create_time) {
prev.create_time_max = obj.create_time;
prev.room_name=obj.room_name;
prev.room_desc=obj.room_desc;
prev.room_pic=obj.room_pic;
prev.id=obj._id.toString().substr(10,24);
}
}',
'key' => [ 'room_id' => 1 ],
'initial' => ["room_name" =>'',"create_time_max"=> 0,'room_desc'=>'','room_pic'=>'','id'=>''],
],
];
$driver->getDb();
$driver->collection = 'ny_room_browse_record';
$ret = $driver->group($options);
return $ret;
});
$this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => $res]);
}
/**
* @api {get} /Wx/RoomBrowseRecordManage/addRecord 添加浏览记录
* @apiDescription token中需要传wechat_user_space_id
* @apiName addRecord
* @apiParam {String} room_id 直播间id
* @apiParam {String} terminal 设备号
* @apiGroup RoomBrowseRecordManage
* @apiSuccessExample success-示例:
{
"code": 200,
"msg": "success",
"data": []
}
* @apiUse ParamError
*/
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' => []]);
}
/**
* use for: 记录微信用户与直播间关系
* auth: Joql
* @param $params
* @return bool
* date:2020-11-06 11:24
*/
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;
}
/**
* @api {post} /Wx/RoomBrowseRecordManage/delRecord 删除浏览记录
* @apiDescription token中需要传wechat_user_space_id
* @apiName delRecord
* @apiGroup RoomBrowseRecordManage
* @apiSuccessExample success-示例:
{
"code": 200,
"msg": "success",
"data": []
}
* @apiUse ParamError
*/
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' => []]);
}
/**
* @api {get} /Wx/RoomBrowseRecordManage/delOneRecord 删除单条浏览记录
* @apiDescription 删除单条浏览记录
* @apiName delOneRecord
* @apiGroup RoomBrowseRecordManage
* @apiParam {Number} room_browse_record_id 直播间浏览记录id
* @apiSuccessExample success-示例:
{
"code": 200,
"msg": "success",
"data": []
}
* @apiUse ParamError
*/
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.$oid'=>$room_browse_record_id]);
$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' => []]);
}
/**
* @api {get} /Wx/RoomBrowseRecordManage/recordList 浏览记录列表
* @apiDescription token中需要传wechat_user_space_id
* @apiName recordList
* @apiGroup RoomBrowseRecordManage
* @apiParam {Number} [page=1] 分页页码
* @apiParam {Number} [page_size=6] 分页步长
* @apiSuccessExample success-示例:
{
"code": 200,
"msg": "success",
"data": {
"totalNum": 2,
"lists": [
{
"id":1,
"room_id": 65806,
"room_name": "分销统计早数据",
"room_pic": "http://console.nuoyun.tv/Public/Home/Images/cover.jpg",
"room_desc": ""
},
{
"id":1,
"room_id": 65807,
"room_name": "1",
"room_pic": "http://console.nuoyun.tv/Public/Home/Images/cover.jpg",
"room_desc": ""
}
]
}
}
* @apiUse ParamError
*/
public function recordList(){
$params = $this->request()->getRequestParam();
$params['page'] = (isset($params['page'])&&($params['page']>=1)) ? $params['page'] : 1;
$page[1] = isset($params['page_size']) ? $params['page_size'] : 15;
$page[0] = ($params['page']-1)*$page[1];
$RoomBrowseRecordModel = new RoomBrowseRecord(MysqlClient::getDb());
$record=$RoomBrowseRecordModel->recordList($this->wechat_user_space_id,$page);
$this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => $record]);
}
}
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/8/8
* Time: 9:33
*/
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 group($options) {
$command = new Command($options);
$result = $this->db->executeCommand($this->database, $command);
$res = $result->toArray();
return $res;
}
/**
* use for: 统计总数
* auth: Joql
* @param array $where
* @return int
* date:2020-05-15 17:08
*/
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;
}
/**
* use for: 查询
* auth: Joql
* @param array $where
* @param array $option
* @return string
* date:2020-05-15 17:09
*/
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);
}
}
学习案例
<?php
use MongoDB\BSON\UTCDateTime;
use MongoDB\Driver\Command;
use MongoDB\Driver\Manager;
class MongoDB
{
protected $connection = 'mongodb://username:password@hostname:hostport/?authSource=database';
protected
//mongodb连接管理
$Manager,
//数据库
$database = 'GameLog',
//集合(表)
$table = 'GameLog0';
public function __construct()
{
$this->Manager = new Manager($this->connection);
}
/**
* 获取数据
* @param string|array $pipeline 条件配置
* @param bool $isPage 是否分页
* @return mixed
* @throws \MongoDB\Driver\Exception\Exception
*/
public function getData($pipeline, $isPage = false)
{
//组装查询语句
$options = $this->getOptions($pipeline);
if ($isPage) {
$total = $this->getCount($options);
$options = $this->mongoPage($options);
}
//执行查询获取数据
$data = $this->executeCommand($options);
$return = [
'data' => $data,
'options' => $options
];
if ($isPage) $return['total'] = $total;
return $return;
}
/**
* 拼装查询options
* @param $group
* @return array
*/
protected function getOptions($pipeline)
{
$options = [
'aggregate' => $this->table,
'pipeline' => [
[
'$match' => $this->getMongoCondition()
]
],
'cursor' => new \stdClass(),
];
array_push($options['pipeline'], ...$pipeline);
return $options;
}
/**
* mongo command查询
* @param $options
* @return array
* @throws \MongoDB\Driver\Exception\Exception
*/
protected function executeCommand($options)
{
$command = new Command($options);
$result = $this->Manager->executeCommand($this->database, $command)->toArray();
return $result;
}
/**
* mongo 分页
* @param $options
* @return mixed
*/
protected function mongoPage($options)
{
$page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 10;
$page = [
[
'$limit' => $page * $limit
],
[
'$skip' => ($page - 1) * $limit
],
];
array_push($options['pipeline'], ...$page);
return $options;
}
/**
* 获取总条数
* @param $options
* @return int
* @throws \MongoDB\Driver\Exception\Exception
*/
public function getCount($options)
{
array_push($options['pipeline'], ['$group' => ['_id' => null, 'count' => ['$sum' => 1]]]);
return $this->executeCommand($options)[0]->count;
}
/**
* date范围格式化
* @param datetime $dateTimes 日期
* @param bool $isToTime 是否转时间戳
* @return mixed
*/
protected function getDateTime($dateTimes, $isToTime = false)
{
if (!is_array($dateTimes)) {
$dateTimes = explode(' - ', $dateTimes);
}
foreach ($dateTimes as &$date) {
$date = $isToTime ? (int)strtotime($date) : date('Y-m-d H:i:s', strtotime($date));
}
return $dateTimes;
}
/**
* 获取mongo条件
* @return array
*/
protected function getMongoCondition()
{
$condition = [
'ClientType' => ['$gt' => 0]
];
$get = $_GET;
if (!empty($get['Time'])) {
$range_time = $this->getDateTime($get['Time'], true);
$condition['TimeStamp'] = [
'$gte' => $range_time[0],
'$lt' => $range_time[1],
];
}
if (!empty($get['KindID'])) {
$condition['KindID'] = ['$eq' => (int)$get['KindID']];
}
if (!empty($get['ServerId'])) {
$condition['ServerID'] = ['$eq' => (int)$get['ServerId']];
}
if (!empty($get['UserID'])) {
$condition['UserID'] = ['$eq' => (int)$get['UserID']];
}
return $condition;
}
}
$Mongo = new MongoDB();
$UTCDateTime = new UTCDateTime(0);
$repair_time = 3600000 * 8;//修复时差
$pipeline = [
[
'$match' => [
'KindID' => [
'$in' => [204, 220]
],
'$or' => [
['KindID' => 204],
['KindID' => 220]
]
]
],
[
'$project' => [
'timeToDate' => [
'$dateToString' => [
'format' => "%Y-%m-%d",
'date' => [
'$add' => [
$UTCDateTime,
[
'$multiply' => ['$TimeStamp', 1000]
], $repair_time]
]
]
],
'WinGold' => '$WinGold',
'BetonGold' => '$BetonGold',
'KindID' => '$KindID'
]
],
[
'$group' => [
'_id' => ['date' => '$timeToDate', 'KindID' => '$KindID'],
//下注次数
'count' => ['$sum' => 1],
//输赢金额
'Amount' => ['$sum' => '$WinGold'],
'BetonGold' => ['$sum' => '$BetonGold'],
'KindID' => ['$last' => '$KindID'],
'date' => ['$last' => '$timeToDate']
]
],
[
'$sort' => ['_id.date' => -1]
]
];
echo '<pre>';
$data = $Mongo->getData($pipeline);
var_dump($data);