<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-02-17
// +—————————————————————————————————————————————————————————————————————
/**
 * 直播列表
 */
namespace app\admin\controller;

require CMF_ROOT . 'vendor/tencentcloud/vendor/autoload.php';

use cmf\controller\AdminBaseController;
use TencentCloud\Live\V20180801\Models\DescribeLivePullStreamTasksRequest;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamOnlineListRequest;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamPublishedListRequest;
use think\Db;

// 根据腾讯云sdk请求 创建直播拉流
use TencentCloud\Live\V20180801\Models\CreateLivePullStreamTaskRequest;
use TencentCloud\Live\V20180801\Models\DeleteLivePullStreamTaskRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Live\V20180801\LiveClient;
use think\Exception;
use think\exception\PDOException;

class LiveingController extends AdminbaseController {

    private $secretId   = 'AKID575vicM9rU6iBiWJNi09HF8xhMxOk4Od';
    private $secretKey  = 'MiDkHwgOFpMpGf2KXcZIo9MYY5qnmhU5';
    private $pushDomain = 'push.umotool.com';

    private $pushKey    = 'd79106bd037188b132bc2d4cc272aa98';
    private $pullKey    = 'JYthadi3fG4C4fbdmF6R';
    private $pullDomain = 'tintonkangdahotel.com';

    protected function getLiveClass(){

        $liveclass=Db::name("live_class")->order('list_order asc, id desc')->column('id,name');

        return $liveclass;
    }
    
    protected function getTypes($k=''){
        $type=[
            '0'=>'普通房间',
            '1'=>'密码房间',
            '2'=>'门票房间',
            '3'=>'计时房间',
        ];
        
        if($k==''){
            return $type;
        }
        return $type[$k];
    }
    
    public function index(){
        $data = $this->request->param();
        $map=[];
        $map[]=['islive','=',1];
        $start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        
        if($start_time!=""){
           $map[]=['starttime','>=',strtotime($start_time)];
        }

        if($end_time!=""){
           $map[]=['starttime','<=',strtotime($end_time) + 60*60*24];
        }
        
        $uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $lianguid=getLianguser($uid);
            if($lianguid){
                $map[]=['uid',['=',$uid],['in',$lianguid],'or'];
            }else{
                $map[]=['uid','=',$uid];
            }
        }
        
        $this->configpri=getConfigPri();
            

        $lists = Db::name("live")
                ->where($map)
                ->order("starttime DESC")
                ->paginate(20);
        
        $lists->each(function($v,$k){

             $v['userinfo']=getUserInfo($v['uid']);
             $where=[];
             $where['action']=1;
             $where['touid']=$v['uid'];
             $where['showid']=$v['showid'];
             /* 本场总收益 */
             $totalcoin=Db::name("user_coinrecord")->where($where)->sum('totalcoin');
             if(!$totalcoin){
                $totalcoin=0;
             }
             /* 送礼物总人数 */
             $total_nums=Db::name("user_coinrecord")->where($where)->group("uid")->count();
             if(!$total_nums){
                $total_nums=0;
             }
             /* 人均 */
             $total_average=0;
             if($totalcoin && $total_nums){
                $total_average=round($totalcoin/$total_nums,2);
             }
             
             /* 人数 */
            $nums=zSize('user_'.$v['stream']);
            
            $v['totalcoin']=$totalcoin;
            $v['total_nums']=$total_nums;
            $v['total_average']=$total_average;
            $v['nums']=$nums;
            
            if($v['isvideo']==0 && $this->configpri['cdn_switch']!=5){
                $v['pull']=PrivateKeyA('rtmp',$v['stream'],0);
            }
                
            return $v;           
        });
        
        $lists->appends($data);
        $page = $lists->render();

        $liveclass=$this->getLiveClass();
        $liveclass[0]='默认分类';

        $this->assign('lists', $lists);

        $this->assign("page", $page);
        
        $this->assign("liveclass", $liveclass);
        
        $this->assign("type", $this->getTypes());
        
        return $this->fetch();

    }

    public function getLivePushUrl(){

        $uid = $_POST['uid'] ?? ''; // 从 POST 请求中获取 uid 值

        if (empty($uid)) {
            echo "请输入UID";
        } elseif (!is_numeric($uid)) {
            echo "UID必须是数字";
        } else {

            $tx_push = cmf_get_option('configpri')['tx_push'];
            $push_url = 'rtmp://' . $tx_push.'/live/'.$uid;

            $pull_key = cmf_get_option('configpri')['tx_play_key'];



            try {
                // 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中。
                // 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。
                // $cred = new Credential("SecretId", "SecretKey");
                $cred = new Credential("AKID575vicM9rU6iBiWJNi09HF8xhMxOk4Od",
                    "MiDkHwgOFpMpGf2KXcZIo9MYY5qnmhU5");

                // 实例化一个http选项,可选的,没有特殊需求可以跳过
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile( $httpProfile );
                // 实例化要请求产品的client对象,clientProfile是可选的
                $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

                // 实例化一个请求对象,每个接口都会对应一个request对象
                $req = new CreateLivePullStreamTaskRequest();
                $timestamp = time();
                //播放链接限制10分钟 60*10  一天 60*60*24
                $end_timestamp     = time() + 60*60*24;
                $txTime = strtoupper(base_convert($end_timestamp, 10, 16));
                $txSecret   = md5( $pull_key . $uid . $txTime );
                $params = array(
                    "SourceType" => "PullLivePushLive",
                    "SourceUrls" => [
                        'https://tintonkangdahotel.com/live/'.$uid.'.flv',
                    ],
                    "DomainName" => 'push.umotool.com',
                    "PushArgs"   => 'txSecret='.$txSecret.'&txTime='.$txTime,
                    "AppName"    => 'live',
                    "StreamName" => $uid,
                    "StartTime"  => gmdate("Y-m-d\TH:i:s\Z", $timestamp),
                    "EndTime"    => gmdate("Y-m-d\TH:i:s\Z", $end_timestamp),
                    "Operator"   => 'tom001',
                );
                $req->fromJsonString( json_encode( $params ) );
                // 返回的resp是一个CreateLivePullStreamTaskResponse的实例,与请求对象对应
                $resp   = $client->CreateLivePullStreamTask( $req );

                // 推流地址、播流地址、taskId
                $data['push'] = 'rtmp://push.umotool.com/live/'. $uid . '?' .$params['PushArgs'];

                $pull_urls = $this->getPullUrl( 'live', $uid, $end_timestamp );
                $data['pull'] = $pull_urls[1];
                $data['TaskId'] = $resp->TaskId;

                echo json_encode( $data , JSON_UNESCAPED_UNICODE );

            }
            catch(TencentCloudSDKException $e) {
                echo $e;
            }

        }
    }



    public function xiabo()
    {
        $uid = $_POST['uid'];
        $TaskId = $_POST['TaskId'];
        if (empty($uid) || empty($TaskId)) {
            echo "请输入 TaskId";
        } elseif (!is_numeric($uid) || !is_numeric($TaskId)) {
            echo "TaskId 必须是数字";
        } else {

            require CMF_ROOT . 'vendor/tencentcloud/vendor/autoload.php';

            try {
                // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
                // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。密钥可前往官网控制台 https://console.tencentcloud.com/capi 进行获取
                $cred = new Credential("AKID575vicM9rU6iBiWJNi09HF8xhMxOk4Od",
                    "MiDkHwgOFpMpGf2KXcZIo9MYY5qnmhU5");
                // 实例化一个http选项,可选的,没有特殊需求可以跳过
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile( $httpProfile );
                // 实例化要请求产品的client对象,clientProfile是可选的
                $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

                // 实例化一个请求对象,每个接口都会对应一个request对象
                $req = new DeleteLivePullStreamTaskRequest();

                $params = array(
                    "TaskId"   => $TaskId,
                    "Operator" => "tom001"
                );
                $req->fromJsonString( json_encode( $params ) );
                // 返回的resp是一个DeleteLivePullStreamTaskResponse的实例,与请求对象对应
                $resp = $client->DeleteLivePullStreamTask( $req );
                // 输出json格式的字符串回包
                $json = $resp->toJsonString();


                $data['uid'] = $uid;
                $data['TaskId'] = '已下播-'.$TaskId;
                $rs = DB::name('live')->update($data);


//                return $json;
                return json_decode( $json, 1 );

            } catch ( TencentCloudSDKException $e ) {
                return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
            } catch ( PDOException  $e ) {
                return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
            }catch ( Exception   $e ) {
                return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
            }
        }
    }


    public function del(){
        
        $uid = $this->request->param('uid', 0, 'intval');
        
        $rs = DB::name('live')->where("uid={$uid}")->delete();
        if(!$rs){
            $this->error("删除失败!");
        }
		
	
        
        $this->success("删除成功!",url("liveing/index"));
            
    }
    
    public function add(){
        
        $this->assign("liveclass", $this->getLiveClass());
        
        $this->assign("type", $this->getTypes());
        
        return $this->fetch();
    }
    
    public function addPost(){
        if ($this->request->isPost()) {
            
            $data = $this->request->param();
            
            $nowtime=time();
            $uid=$data['uid'];
            
            $userinfo=DB::name('user')->field("ishot")->where(["id"=>$uid,"user_type"=>2])->find();
            if(!$userinfo){
                $this->error('用户不存在');
            }
            
            $liveinfo=DB::name('live')->field('uid,islive')->where(["uid"=>$uid])->find();
            if($liveinfo['islive']==1){
                $this->error('该用户正在直播');
            }
            
            $TaskId=$data['TaskId'];
//            $pull=urldecode($data['pull']);
//            $push=urldecode($data['push']);
            $pull=$data['pull'];
            $push=$data['push'];
            $type=$data['type'];
            $type_val=$data['type_val'];
            $anyway=$data['anyway'];
            $liveclassid=$data['liveclassid'];
            $stream=$uid.'_'.$nowtime;
            $title='';


            
            $data2=array(
                "uid"=>$uid,
                "showid"=>$nowtime,
                "starttime"=>$nowtime,
                "title"=>$title,
                "province"=>'',
                "city"=>'好像在火星',
                "stream"=>$stream,
                "thumb"=>'',
                "TaskId"=>$TaskId,
                "pull"=>$pull,
                "push"=>$push,
                "lng"=>'',
                "lat"=>'',
                "type"=>$type,
                "type_val"=>$type_val,
                "isvideo"=>1,
                "islive"=>1,
                "anyway"=>$anyway,
                "liveclassid"=>$liveclassid,

            );
            
            if($liveinfo){
                $rs = DB::name('live')->update($data2);
            }else{
                $rs = DB::name('live')->insertGetId($data2);
            }

            if($rs===false){
                $this->error("添加失败!");
            }
			
	
            
            $this->success("添加成功!");
            
        }           
    }
    
    public function edit(){
        $uid   = $this->request->param('uid', 0, 'intval');
        
        $data=Db::name('live')
            ->where("uid={$uid}")
            ->find();
        if(!$data){
            $this->error("信息错误");
        }
        
        $this->assign('data', $data);
        
        $this->assign("liveclass", $this->getLiveClass());
        
        $this->assign("type", $this->getTypes());
        
        return $this->fetch();


    }
    
    public function editPost(){
        if ($this->request->isPost()) {
            
            $data = $this->request->param();
            
//            $data['pull']=urldecode($data['pull']);
//            $data['push']=urldecode($data['push']);


            
            $rs = DB::name('live')->update($data);
            if($rs===false){
                $this->error("修改失败!");
            }
		
            
            $this->success("修改成功!");
        }
    }




    /**
     * 获取推流地址
     * 如果不传key和过期时间,将返回不含防盗链的url
     * @param domain 您用来推流的域名
     *        streamName 您用来区别不同推流地址的唯一流名称
     *        key 安全密钥
     *        time 过期时间 sample 2016-11-12 12:00:00
     * @return String url
     */
    public function getPushUrl( $appName, $streamName, $time ): string
    {
        $domain = $this->pushDomain;
        $key    = $this->pushKey;

        $txTime = strtoupper( base_convert( $time, 10, 16 ) );
        //txSecret = MD5( KEY + streamName + txTime )
        $txSecret = md5( $key . $streamName . $txTime );
        return "?" . http_build_query( array(
                "txSecret" => $txSecret,
                "txTime"   => $txTime
            ) );
//        return $domain . ( $ext_str ?? "" );
    }


    public function getPullUrl( $appName, $streamName, $time ): array
    {
        $domain = $this->pullDomain;
        $key    = $this->pullKey;

        $txTime = strtoupper( base_convert( $time , 10, 16 ) );
        //txSecret = MD5( KEY + streamName + txTime )
        $txSecret   = md5( $key . $streamName . $txTime );
        $build_data = [
            "txSecret" => $txSecret,
            "txTime"   => $txTime
        ];
        $ext_str    = "?" . http_build_query( $build_data );
        return [
            "rtmp://" . $domain . "/" . $appName . "/" . $streamName . $ext_str,
            "https://" . $domain . "/" . $appName . "/" . $streamName . ".m3u8" . $ext_str,
            "https://" . $domain . "/" . $appName . "/" . $streamName . ".flv" . $ext_str
        ];

    }

    public function getPullUrl2( $appName, $streamName, $time )
    {
        $domain = $this->pullDomain;
        $key    = $this->pullKey;

        $txTime = strtoupper( base_convert( strtotime( $time ), 10, 16 ) );
        //txSecret = MD5( KEY + streamName + txTime )
        $txSecret   = md5( $key . $streamName . $txTime );
        $build_data = [
            "txSecret" => $txSecret,
            "txTime"   => $txTime
        ];
        $ext_str    = "?" . http_build_query( $build_data );

        return [
            "rtmp://" . $domain . "/" . $appName . "/" . $streamName,
            "https://" . $domain . "/" . $appName . "/" . $streamName . ".m3u8",
            "https://" . $domain . "/" . $appName . "/" . $streamName . ".flv"
        ];

    }


    /**
     * @param $sport_id
     * @param $live_data
     * @return false|void
     * 拉流转推
     */
    public function setRtmpGetHttp( $sport_id, $live_data ,$play_urls_count=2)
    {

        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            $cred = new Credential( $this->secretId, $this->secretKey );
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile( $httpProfile );
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new CreateLivePullStreamTaskRequest();

            $SourceUrls = [];
            if(count($live_data[ 'urls' ]) == 1)
            {
                $SourceUrls[] = $live_data[ 'urls' ][0]['m3u8'];
            }else{
                if(!empty($live_data[ 'urls' ][$play_urls_count]['flv']))
                {
                    $SourceUrls[] = $live_data[ 'urls' ][$play_urls_count]['flv'];
                }else{
                    foreach ( $live_data[ 'urls' ] as $item ) {
                        if ( !empty( $item[ 'flv' ] && empty( $SourceUrls ) ) ) {
                            $SourceUrls[] = $item[ 'flv' ];
                        }
                    }
                }
            }

            if ( empty( $SourceUrls ) ) {
                return false;
            }


            $AppName    = 'sport_test_live';
            $StreamName = 'sport_test_live_' . $sport_id;
            $now        = time();

            $_now       = $this->getNow( $live_data );

            $time      = date( 'Y-m-d H:i:s', $_now );
            $StartTime = date( 'Y-m-d\TH:i:s\Z', ( $now - 28800 ) );
            $EndTime   = date( 'Y-m-d\TH:i:s\Z', ( $_now - 28800 ) );
            $push_url  = $this->getPushUrl( $AppName, $StreamName, $time );

            //播放链接限制10分钟
            $_time     = date( 'Y-m-d H:i:s', time() + 600 );
            $pull_urls = $this->getPullUrl( $AppName, $StreamName, $_time );

            $params = array(
                "SourceType" => "PullLivePushLive",
                "SourceUrls" => $SourceUrls,
                "DomainName" => $this->pushDomain,
                "PushArgs"   => $push_url,
                "AppName"    => $AppName,
                "StreamName" => $StreamName,
                "StartTime"  => $StartTime,
                "EndTime"    => $EndTime,
                "Operator"   => 'tom001',
            );
            $req->fromJsonString( json_encode( $params ) );
            // 返回的resp是一个CreateLivePullStreamTaskResponse的实例,与请求对象对应
            $resp   = $client->CreateLivePullStreamTask( $req );
            $v_data = [
                'tencent_res' => json_decode( json_encode( $resp ), 1 ),
                'play_urls'   => $pull_urls
            ];
            return $v_data;
        } catch ( TencentCloudSDKException $e ) {
            return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
        }

    }


    public function getNow( $live_data )
    {

        $start_time = $live_data[ 'kickoffTS' ] + ( 12 * 60 * 60 );

        if ( $start_time >= time() ) {
            return ( $start_time + 10800 );
        }

        $sy_time = time() - $start_time;

        $zy = 10800 - $sy_time;

        if ( $sy_time > 9500 ) {
            $add_time = time() + 1800;
        } else {
            $add_time = time() + $zy;
        }
        return $add_time;
    }


    public function upRtmpGetHttp( $sport_id, $live_data, $taskId )
    {
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。密钥可前往官网控制台 https://console.tencentcloud.com/capi 进行获取
            $cred = new Credential( $this->secretId, $this->secretKey );
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile( $httpProfile );
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req        = new ModifyLivePullStreamTaskRequest();
            $SourceUrls = [];

            foreach ( $live_data as $item ) {
                if ( !empty( $item[ 'm3u8' ] && empty( $SourceUrls ) ) ) {
                    $SourceUrls[] = $item[ 'm3u8' ];
                }
            }
            if ( empty( $SourceUrls ) ) {
                return false;
            }
            $AppName    = 'sport_test_live';
            $StreamName = 'sport_test_live_' . $sport_id;
            $now        = time();
            $_now       = time() + 600;
            $time       = date( 'Y-m-d H:i:s', $_now );
            $StartTime  = date( 'Y-m-d\TH:i:s\Z', ( $now - 28800 ) );
            $EndTime    = date( 'Y-m-d\TH:i:s\Z', ( $_now - 28800 ) );

            $pull_urls = $this->getPullUrl( $AppName, $StreamName, $time );
            $params    = array(
                "TaskId"     => $taskId,
                "SourceUrls" => $SourceUrls,
                "StartTime"  => $StartTime,
                "EndTime"    => $EndTime,
                "Operator"   => 'tom001',

            );
            $req->fromJsonString( json_encode( $params ) );

            // 返回的resp是一个ModifyLivePullStreamTaskResponse的实例,与请求对象对应
            $resp = $client->ModifyLivePullStreamTask( $req );

            $v_data = [
                'tencent_res' => json_decode( json_encode( $resp ), 1 ),
                'play_urls'   => $pull_urls
            ];
            // 输出json格式的字符串回包
            return $v_data;

            // 输出json格式的字符串回包
//            print_r( $resp->toJsonString() );
        } catch ( TencentCloudSDKException $e ) {
            return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
        }
    }


    public function upRtmpGetHttpUrl( $sport_id )
    {
        $AppName    = 'sport_test_live';
        $StreamName = 'sport_test_live_' . $sport_id;
        $_now       = time() + 600;
        $time       = date( 'Y-m-d H:i:s', $_now );
        $pull_urls  = $this->getPullUrl( $AppName, $StreamName, $time );
        return $pull_urls;
    }


    public function delSportExpired( $taskId )
    {
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。密钥可前往官网控制台 https://console.tencentcloud.com/capi 进行获取
            $cred = new Credential( $this->secretId, $this->secretKey );
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile( $httpProfile );
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new DeleteLivePullStreamTaskRequest();

            $params = array(
                "TaskId"   => $taskId,
                "Operator" => "tom001"
            );
            $req->fromJsonString( json_encode( $params ) );
            // 返回的resp是一个DeleteLivePullStreamTaskResponse的实例,与请求对象对应
            $resp = $client->DeleteLivePullStreamTask( $req );
            // 输出json格式的字符串回包
            $json = $resp->toJsonString();
            return json_decode( $json, 1 );

        } catch ( TencentCloudSDKException $e ) {
            return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
        }
    }


    public function getLiveAll( $page = 1, $limit = 20, $liveid = '' )
    {
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。密钥可前往官网控制台 https://console.tencentcloud.com/capi 进行获取
            $cred = new Credential( $this->secretId, $this->secretKey );
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile( $httpProfile );
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient( $cred, "ap-bangkok", $clientProfile );

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new DescribeLivePullStreamTasksRequest();


            $params = [
                'PageNum'  => $page,
                'PageSize' => $limit
            ];
            if ( $liveid ) {
                $params[ 'TaskId' ] = $liveid;
            }

            $req->fromJsonString( json_encode( $params ) );

            // 返回的resp是一个DescribeLivePullStreamTasksResponse的实例,与请求对象对应
            $resp = $client->DescribeLivePullStreamTasks( $req );

            // 输出json格式的字符串回包
            return json_decode( $resp->toJsonString(), 1 );
        } catch ( TencentCloudSDKException $e ) {
            return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
        }
    }


    public function getLiveOnlineList( $page = 1, $limit = 100, $AppName = 'A-live' )
    {
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            $cred = new Credential( $this->secretId, $this->secretKey );
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile( $httpProfile );
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient( $cred, "", $clientProfile );

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new DescribeLiveStreamOnlineListRequest();

            $params = array(
                "AppName"  => $AppName,
                "PageNum"  => $page,
                "PageSize" => $limit
            );
            $req->fromJsonString( json_encode( $params ) );

            // 返回的resp是一个DescribeLiveStreamOnlineListResponse的实例,与请求对象对应
            $resp = $client->DescribeLiveStreamOnlineList( $req );

            return json_decode( $resp->toJsonString(), 1 );
        } catch ( TencentCloudSDKException $e ) {
            return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
        }
    }


    public function getLiveStreamPublishedList( $AppName = 'A-live', $StreamName = '' )
    {
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            $cred = new Credential( $this->secretId, $this->secretKey );
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint( "live.tencentcloudapi.com" );

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile( $httpProfile );
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient( $cred, "", $clientProfile );

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req       = new DescribeLiveStreamPublishedListRequest();
            $now       = time();
            $StartTime = date( 'Y-m-d\TH:i:s\Z', ( $now - 86400 ) );
            $EndTime   = date( 'Y-m-d\TH:i:s\Z', $now );

            $params = array(
                'DomainName' => $this->pushDomain,
                "StartTime"  => $StartTime,
                "EndTime"    => $EndTime,
                "AppName"    => $AppName
            );

            if ( !empty( $StreamName ) ) {
                $params[ 'StreamName' ] = $StreamName;
            }

            $req->fromJsonString( json_encode( $params ) );

            // 返回的resp是一个DescribeLiveStreamPublishedListResponse的实例,与请求对象对应
            $resp = $client->DescribeLiveStreamPublishedList( $req );

            return json_decode( $resp->toJsonString(), 1 );
        } catch ( TencentCloudSDKException $e ) {
            return [ 'ode' => $e->getCode(), 'msg' => $e->getMessage() ];
        }
    }


    public function startAnchorRtmp( $roomid, $sportId )
    {


        $AppName    = 'A-live';
        $StreamName = 'A-live-' . $roomid . '-' . $sportId;
        $now        = time();

        //推球时间 过期时间是 12个小时
        $start_time = date( 'Y-m-d H:i:s', $now + ( 12 * 60 * 60 ) );
        //播放链接 有效时间是10分钟,每5分钟更新一次
        $end_time = date( 'Y-m-d H:i:s', $now + 600 );

        $ext_str = $this->getPushUrl( $AppName, $StreamName, $start_time );

        $rtmpPushUrl    = "rtmp://" . $this->pushDomain . "/" . $AppName . "/" . $StreamName . $ext_str;
        $rtmp_push_url  = "rtmp://" . $this->pushDomain . "/" . $AppName . "/";
        $rtmp_push_code = $StreamName . $ext_str;

        $pull_urls = $this->getPullUrl2( $AppName, $StreamName, $end_time );

        $urls = [
            'rtmp_push_url'  => $rtmp_push_url,
            'rtmp_push_code' => $rtmp_push_code,
            'rtmp_push'      => $rtmpPushUrl,
            'hls_pull'       => $pull_urls[ 1 ],
            'http_pull'      => $pull_urls[ 2 ],
            'rtmp_pull'      => $pull_urls[ 0 ],
        ];


        return [
            'code' => 0,
            'data' => $urls
        ];

    }


}