LivingController.php 16.9 KB
<?php
namespace soa\controllers\v1;

use Yii;
use soa\controllers\BaseController;
use backend\widgets\YHGImage\Common\Images as CommonImages;
use common\models\Room;
use common\models\Video;
use common\models\LiveComment;
use common\models\RoomNums;

class LivingController extends BaseController
{
    
    public function beforeAction($action) {
        
        return parent::beforeAction($action);
    }
    
    /**
     * 精选房间
     */
    public function actionBest()
    {
        $key = __CLASS__.__FUNCTION__.'app'.$this->app;
        if (!$ret = $this->cache->get($key)){
            $ret = Room::find()->with(['master'])->where(['and',['!=','best','0'],"find_in_set({$this->app},app)"])->limit(2)->orderBy(['best'=>SORT_ASC])->all();

            foreach ($ret as $k=>$model){
                $row = [
                    'room_id'=>(int)$model->room_id,
                    'master_pic'=>CommonImages::getTemplateComplex($model->master->pic, 2),
                    'master_name'=>$model->master->name,
                    'master_meta'=>$model->master->meta,
                    'title'=>$model->title,
                    'pic'=>CommonImages::getTemplateComplex($model->pic, 2),
                    'living'=>$model->living,
                    'starting_time'=>$model->starting_time,
                ];
                $ret[$k] = $row;
            }
        
            $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                ->createCommand('SELECT MAX(update_time),count(*) FROM {{%room}} WHERE best!="0" AND find_in_set(:app,app)')
                ->bindValue(':app', $this->app)
                ->getRawSql()]);
            $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
        }

        $ret = array_values(array_filter($ret,function($row){
            return !$row['starting_time'] ? true : ($row['starting_time'] > time());
        }));
        $this->renderJson(Yii::$app->params['success_code'],'',$ret);
    }
    
    /**
     * 直播中的所有视频
     */
    public function actionListing()
    {
        $key = __CLASS__.__FUNCTION__.'app'.$this->app;
        if (!$ret = $this->cache->get($key)){
            
            $ret = Room::find()->with(['master','roomNums'])->where(['and',['living'=>1],"find_in_set({$this->app},app)"])->joinWith('roomNums rn')->orderBy(['rn.online_num'=>SORT_DESC])->all();

            foreach ($ret as $k=>$model){
                $row = [
                    'room_id'=>(int)$model->room_id,
                    'master_pic'=>'',
                    'master_name'=>'',
                    'master_meta'=>'',
                    'title'=>$model->title,
                    'pic'=>CommonImages::getTemplateComplex($model->pic, 2),
                    'audience_num'=>$model->roomNums ? (int)$model->roomNums->online_num : 0,//在线人数
                ];
                if ($model->master){
                    $row = array_merge($row,[
                        'master_pic'=>CommonImages::getTemplateComplex($model->master->pic, 2),
                        'master_name'=>$model->master->name,
                        'master_meta'=>$model->master->meta,
                    ]);
                }
                $ret[$k] = $row;
            }
            
            $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                ->createCommand('SELECT MAX(update_time),count(*) FROM {{%room}} WHERE living=1 AND find_in_set(:app,app)')
                ->bindValue(':app', $this->app)
                ->getRawSql()]);
            $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
        }else{
            $keys = [];
            foreach ($ret as $k=>$row){
                $keys[] = sprintf("%sonline_nums_room_%s",Yii::$app->params['cache_prefix'],$row['room_id']);
            }

            $values = $keys ? call_user_func_array(array(Yii::$app->redisIm,'mget'), $keys) : [];
            foreach ($values as $k=>$value){
                $ret[$k]['audience_num'] = (int)($value ? : $ret[$k]['audience_num']);
            }
        }
        
        
        $this->renderJson(Yii::$app->params['success_code'],'',$ret);
    }
    
    /**
     * 所有直播预告
     */
    public function actionStarting()
    {
        $key = __CLASS__.__FUNCTION__.'app'.$this->app;
        if (!$ret = $this->cache->get($key)){
            
            $ret = Room::find()->with(['master'])->where(['and',['living'=>0],['!=','starting_time',0],"find_in_set({$this->app},app)"])->orderBy(['starting_time'=>SORT_ASC])->all();

            foreach ($ret as $k=>$model){
                $row = [
                    'room_id'=>(int)$model->room_id,
                    'master_pic'=>CommonImages::getTemplateComplex($model->master->pic, 2),
                    'master_name'=>$model->master->name,
                    'master_meta'=>$model->master->meta,
                    'title'=>$model->title,
                    'pic'=>CommonImages::getTemplateComplex($model->pic, 2),
                    'starting_time'=>$model->starting_time,
                ];
                $ret[$k] = $row;
            }

            $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                ->createCommand('SELECT MAX(update_time),count(*) FROM {{%room}} WHERE living=0 AND starting_time!=0 AND find_in_set(:app,app)')
                ->bindValue(':app', $this->app)
                ->getRawSql()]);
            $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
        }
        
        
        $this->renderJson(Yii::$app->params['success_code'],'',$ret);
    }
    
    /**
     * 所有精彩回放
     */
    public function actionReplaying()
    {
        $key = __CLASS__.__FUNCTION__.'app'.$this->app;
        if (!$ret = $this->cache->get($key)){
            
            $ret = Video::find()->with(['master'])->where(['and',['status' => 1],['not', ['url' => null]],['not', ['url' => '']],"find_in_set({$this->app},app)"])->orderBy(['create_time'=>SORT_DESC])->all();

            foreach ($ret as $k=>$model){
                $row = [
                    'video_id'=>(int)$model->id,
                    'master_pic'=>CommonImages::getTemplateComplex($model->master->pic, 2),
                    'master_name'=>$model->master->name,
                    'master_meta'=>$model->master->meta,
                    'title'=>$model->title,
                    'pic'=>CommonImages::getTemplateComplex($model->pic, 2),
                    'url'=>$model->url,
                    'live_title'=>$model->live_title,
                    'live_room_id'=>(int)$model->room_id,
                    'audience_num'=>(int)($model->audience_num+$model->replay_num),
                    'create_time'=>(int)$model->create_time,
                ];
                $ret[$k] = $row;
            }

            $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                ->createCommand('SELECT MAX(update_time),count(*) FROM {{%video}} WHERE status=1 AND NOT (url IS NULL) AND NOT (url="") AND find_in_set(:app,app)')
                ->bindValue(':app', $this->app)
                ->getRawSql()]);
            $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
        }else{
            $keys = [];
            foreach ($ret as $k=>$row){
                $keys[] = sprintf("%svideo_id_%s_audience_num",Yii::$app->params['cache_prefix'],$row['video_id']);
            }
            $values = $keys ? call_user_func_array(array(Yii::$app->redis,'mget'), $keys) : [];
            foreach ($values as $k=>$value){
                $ret[$k]['audience_num'] = (int)($value ? : $ret[$k]['audience_num']);
            }
        }
        
        $this->renderJson(Yii::$app->params['success_code'],'',$ret);
    }
    
    /**
     * 直播详情
     */
    public function actionDetail()
    {
        if ($room_id = $this->requests('room_id'))
        {//直播视频详情
            
            //观看人数+1
            //RoomNums::updateAllCounters(['audience_num' => 1],['room_id'=>$room_id]);
            
            $key = __CLASS__.__FUNCTION__.'room_id'.$room_id;
            if (!$ret = $this->cache->get($key)){
                if (!$model = Room::findOne(['room_id'=>$room_id])){
                    $this->renderJson(Yii::$app->params['failed_code'],'找不到该房间');
                }

                $ret = [
                    'master_pic'=>'',
                    'master_name'=>'',
                    'master_meta'=>'',
                    'title'=>$model->title,
                    'pic'=>CommonImages::getTemplateComplex($model->pic, 2),
                    'watermark'=>$model->watermark,
                    'living'=>$model->living,
                    'like_num'=>0,
                    'audience_num'=>0,//在线人数
                    'live_start_time'=>0,
                    'starting_time'=>$model->starting_time,//预告时间
                    'rtmp_downstream_address'=>'',
                    'flv_downstream_address'=>'',
                    'hls_downstream_address'=>'',
                    'live_last_time'=>0,
                ];

                //直播时长(秒)
                if ($model->living == 2){
                    if ($model->videoLast){
                        $ret['live_last_time'] = max($model->videoLast->live_end_time-$model->videoLast->live_start_time,0);
                        $ret['like_num'] = $model->videoLast->like_num;
                        $ret['audience_num'] = $model->videoLast->audience_num;
                    }
                }

                /*if ($model->roomNums){
                    $ret = array_merge($ret,[
                        'like_num'=>(int)$model->roomNums->like_num,
                        'audience_num'=>(int)$model->roomNums->online_num,
                    ]);
                }*/

                if ($model->master){
                    $ret = array_merge($ret,[
                        'master_pic'=>CommonImages::getTemplateComplex($model->master->pic, 2),
                        'master_name'=>$model->master->name,
                        'master_meta'=>$model->master->meta,
                    ]);
                }

                if ($model->videoRecording){
                    $ret = array_merge($ret,[
                        'live_start_time'=>(int)$model->videoRecording->live_start_time,
                    ]);
                }

                if ($model->roomQchannel){
                    if (is_array($downstream_address = json_decode($model->roomQchannel->downstream_address)) && !empty($downstream_address[0])){
                        $ret = array_merge($ret,[
                            'rtmp_downstream_address'=>$downstream_address[0]->rtmp_downstream_address,
                            'flv_downstream_address'=>$downstream_address[0]->flv_downstream_address,
                            'hls_downstream_address'=>$downstream_address[0]->hls_downstream_address,
                        ]);
                    }
                }

                $ret['background_pic'] = 'http://img11.static.yhbimg.com/global/2016/08/17/18/01f17a9cd44149052482e4ee58e590cf1b.png';
                $ret['share_url'] = 'http://m.yohobuy.com/activity/live/'.$room_id;
                $ret['share_title'] = '有货潮流新品节直播开始啦,快来看!';
                $ret['share_content'] = 'YO\'HOOD嘉年华现场火热直播中,明星潮牌等你来!';
                
                $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                    ->createCommand('SELECT update_time FROM {{%room}} WHERE room_id=:room_id')
                    ->bindValue(':room_id', $room_id)
                    ->getRawSql()]);
                $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
            }
            
            $this->renderJson(Yii::$app->params['success_code'],'',$ret);
        }elseif ($video_id = $this->requests('video_id'))
        {//重播视频详情
            
            $key = __CLASS__.__FUNCTION__.'video_id'.$video_id;
            if (!$ret = $this->cache->get($key)){
                if (!$model = Video::findOne(['id'=>$video_id])){
                    $this->renderJson(Yii::$app->params['failed_code'],'找不到该回放');
                }

                $ret = [
                    'video_id'=>$model->id,
                    'master_pic'=>'',
                    'master_name'=>'',
                    'master_meta'=>'',
                    'title'=>$model->title,
                    'pic'=>CommonImages::getTemplateComplex($model->pic, 2),
                    'watermark'=>'',
                    'url'=>$model->url,
                    'like_num'=>(int)$model->like_num,
                    'audience_num'=>(int)($model->audience_num+$model->replay_num),
                    'live_title'=>$model->live_title,
                    'live_start_time'=>(int)$model->live_start_time,
                    'live_end_time'=>(int)$model->live_end_time,

                ];

                if ($model->room){
                    $ret = array_merge($ret,[
                        'watermark'=>$model->room->watermark,
                    ]);
                }

                if ($model->master){
                    $ret = array_merge($ret,[
                        'master_pic'=>CommonImages::getTemplateComplex($model->master->pic, 2),
                        'master_name'=>$model->master->name,
                        'master_meta'=>$model->master->meta,
                    ]);
                }

                $ret['background_pic'] = 'http://img11.static.yhbimg.com/global/2016/08/17/18/01f17a9cd44149052482e4ee58e590cf1b.png';
                $ret['share_url'] = 'http://m.yohobuy.com/activity/live/replay/'.$video_id;
                $ret['share_title'] = '有货潮流新品节直播开始啦,快来看!';
                $ret['share_content'] = 'YO\'HOOD嘉年华现场火热直播中,明星潮牌等你来!';

                $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                    ->createCommand('SELECT update_time FROM {{%video}} WHERE id=:video_id')
                    ->bindValue(':video_id', $video_id)
                    ->getRawSql()]);
                $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
            }
            
            //缓存回放观看人数
            $key = sprintf("%svideo_id_%s_audience_num",Yii::$app->params['cache_prefix'],$video_id);
            if (!$audience_num = Yii::$app->redis->get($key)){
                $audience_num = (int)$ret['audience_num'];
                Yii::$app->redis->setex($key, Yii::$app->params['defaultCacheExpire']*2, $audience_num);
            }
            $ret['audience_num'] = $audience_num;

            //观看回放人数+1
            if (Video::updateAllCounters(['replay_num' => 1],['id'=>$video_id]) && Yii::$app->redis->incr($key)){
                $ret['audience_num'] += 1;
            }
            
            $this->renderJson(Yii::$app->params['success_code'],'',$ret);
        }else
        {
            $this->renderJson(Yii::$app->params['failed_code'],'缺少id');
        }
        
    }
    
    /**
     * 获取回放弹幕
     */
    public function actionGetreplaybarrage()
    {
        if (!$video_id = $this->requests('video_id'))
        {
            $this->renderJson(Yii::$app->params['failed_code'],'缺少id');
        }
        
        Yii::$app->db->cache(function() use ($video_id,&$model){
            $model = Video::findOne($video_id);
        }, Yii::$app->params['defaultCacheExpire']);
        if (empty($model)){
            $this->renderJson(Yii::$app->params['failed_code'],'找不到该回放');
        }
        
        $startTime = (int)$this->requests('startTime',0);
        $timeInterval = $this->requests('timeInterval',300);
        $endTime = $startTime + $timeInterval;
        $room_id = $model->room_id;
        
        $key = __CLASS__.__FUNCTION__."{$room_id}_{$startTime}_{$endTime}";
        if (!$ret = $this->cache->get($key)){
            
            $ret = LiveComment::findByRoomid($room_id)->where(['and',['room_id'=>$room_id],['>=','create_time',$startTime],['<=','create_time',$endTime]])->all();

            foreach ($ret as $k=>$row){
                $_row = [
                    'create_time'=>(int)$row->create_time - $model->live_start_time,
                    'avatar'=>$row->avatar,
                    'name'=>$row->name,
                    'msg'=>$row->comment,
                    'cmd'=>(int)$row->cmd,
                ];
                $ret[$k] = $_row;
            }
            $dependency = new \yii\caching\DbDependency(['sql' => 'SELECT COUNT(*) FROM '.LiveComment::tableName($room_id)." WHERE room_id={$room_id} AND create_time>={$startTime} AND create_time<={$endTime}"]);
            $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
        }
        
        $this->renderJson(Yii::$app->params['success_code'],'',$ret);
    }
}