<?php
/**
 * 新版采集模块
 * @copyright reginx.com
 * $Id$
 */
class ga_mod extends admin_mod {

    /**
     * 采集类型
     *
     * @var unknown_type
     */
    private $tconf = array(
        2   => '影片采集',
        1   => '资讯采集'
    );


    /**
	 * 列表
	 *
	 */
    public function listAct(){
        $ctype = intval($this->get('ctype'));
        $ctype = isset($this->tconf[$ctype]) ? $ctype : 2;
        $tab   = $ctype > 1 ? 'vod' : 'art';
        $this->assign('atitle' , $this->tconf[$ctype] . '列表');
        $this->assign('ctype'  , $ctype);
        $this->assign('list' , core::getobj('ga_tab')->where("tab = '{$tab}'")->fields('id,name,udate,adate,lasts,pn,maxpn,total')->order("id desc")->getall());
        $this->display('ga/ga.list.html');
    }

    /**
	 * 新增/修改
	 *
	 */
    public function addAct(){
        $id = intval($this->get('id'));
        $this->assign('atitle' , '新增采集');
        $ctype = intval($this->get('ctype'));
        $tab   = $ctype > 1 ? 'vod' : 'art';
        if($id > 0){
            $ga = core::getobj('ga_tab')->where("id = $id ")->get();
            $ga['conf'] = unserialize(base64_decode($ga['conf']));
            $this->assign('atitle' , "修改 [{$ga['name']}]");
            $this->assign('ga' , $ga);
            $tab = $ga['tab'];
            $ctype = $tab == 'vod' ? 2 : 1;
        }
        $this->assign('tab' , $tab);
        $this->assign('ctypes' , ga_lib::$urlctype);
        $this->assign('cats'    , OBJ('cat_tab')->getslist( 0 , $ctype , 1));
        $this->assign('fields'  , OBJ($tab . '_tab')->getfileds());
        $this->display('ga/ga.add.html');
    }

    /**
     * 剧集地址采集
     *
     */
    public function fetchresAct(){
        $hash = $this->get('hash');
        $data = $GLOBALS['_CACHE']->get('ga#player.' .$hash);
        $this->assign('ga' , ga_lib::get(intval($this->get('id'))));
        $this->assign('data' , $data);
        $this->display('ga/ga.res.html');
    }

    /**
     *  获取播放资源地址
     *
     */
    public function fetchurlAct(){
        $ga = ga_lib::get(intval($this->get('id')));
        if(empty($ga)){
            $this->ajaxout(array('code' => 2 , 'msg' => '未指定的采集'));
        }
        $this->assign('ga' , $ga);
        if(!$this->isajax){
            // list page
            $tobj = OBJ('gatask_tab')->keep()->where("gaid = {$ga['id']} and ctype = 0");
            $pobj = new page_lib($tobj->count() , 'pn' , intval($this->get('pn')) , 50);
            $task = $tobj->clear('fields')->fields('gatask_tab.* , vod_tab.name')->leftjoin('vod_tab' , 'vid' , 'id')->order('vid asc')->limit($pobj->limit)->order('extra asc')->getall();
            if(empty($task)){
                $this->showmsg('采集任务已完成!' , core::url('ga-list-ctype-2') , 1 , 2);
            }
            foreach ($task as &$v){
                list($v['url'] , $v['sname']) = explode('###' , $v['sdesc']);
            }
            $this->assign('tasks' , $task);
            $this->assign('pobj'  , $pobj->toarray());
            $this->assign('auto' , intval($this->get('auto')));
            $this->display('ga/ga.task.html');
        }else{
            $vid   = intval($this->get('vid' , 'p'));
            $extra = intval($this->get('extra' , 'p'));
            $task = OBJ('gatask_tab')->where("gaid = {$ga['id']} and vid = $vid and ctype = 0 and extra = $extra")->get();
            if(empty($task)){
                $this->ajaxout(array('code' => 1 , 'msg' => '资源url采集已经完成了'));
            }
            $vod = OBJ("vod_tab")->where("id = '{$task['vid']}'")->fields('id,name')->get();
            $ret = ga_lib::fetchurl($task , $vod , $this->conf['vsname'] , $ga);
            if((int)$ret['code'] === 0 && !empty($ret['list'])){
                $uobj = OBJ('vod_url_tab');
                if(count($ret['list']) > 1){
                    $tmplist = array();
                    foreach ($ret['list'] as $v){
                        $v[3] = vod_lib::getplayer($v[1]);
                        $tmplist[$v[3]][] = $v; 
                    }
                    // 批量入库
                    foreach ($tmplist as $k => $v){
                        foreach ($v as $sk => $sv){
                            $pkey = array();
                            preg_match('/\d+/' , $sv[0] , $pkey);
                            $pkey = intval($pkey[0]);
                            $uobj->set("vid" , $vid)->set('url' , $sv[1])->set('name' , $sv[0]);
                            $uobj->set("player" , $sv[3])->set('uid' , $pkey ? $pkey : ($k+1))->set('hash' , $sv[2]);
                            $uobj->replace();
                        }
                    }
                }else{
                    $v = $ret['list'][0];
                    $uobj->set("vid" , $vid)->set('url' , $v[1])->set('name' , $v[0]);
                    $uobj->set("player" , vod_lib::getplayer($v[1]))->set('uid' , $extra)->set('hash' , $v[2]);
                    $uobj->replace();
                }
                OBJ('gatask_tab')->where("gaid = {$ga['id']} and vid = $vid and ctype = 0 and extra = $extra")->del();
                $this->ajaxout(array('code' => 0 , 'msg' => '已完成'));
            }
            $this->ajaxout(array('code' => 1 , 'msg' => $ret['msg']));
        }

    }

    /**
     * 拉取单条数据
     *
     */
    public function fetchAct(){
        set_time_limit(180);
        $id = intval($this->get('id'));
        if($id > 0){
            $row = OBJ("ga_tab")->where("id = $id ")->get();
            if($row && !empty($row)){
                $row['conf'] = unserialize(base64_decode($row['conf']));
            }
            $url = $this->has('url' , 'p') ? $this->get('url' , 'p') : '';
            if(substr($url , 0 , 1) == '/'){
                $url = $row['host'] . substr($url , 1);
            }
            if(($url = filter_var($url , FILTER_VALIDATE_URL)) != false){
                $ret = ga_lib::fetch($url , $row);
                if($row['tab'] == 'art' && (int)$ret['code'] === 0){
                    $ret['data']['catid'] = $row['catid'];
                    $aret = art_lib::addnew($ret['data'] , $row);
                    unset($ret['data']);
                    if($aret && (int)$aret['code'] === 0){
                        $ret['code'] = 0;
                        OBJ("ga_tab")->exec("update ga_tab set lasts = lasts + 1 , udate = " . REQUEST_TIME . " where id = $id ");
                        $ret['msg']  = '已完成';
                    }else{
                        $ret['code'] = 1;
                        $ret['msg']  = '入库失败!';
                    }
                }
                // 视频
                else if($row['tab'] == 'vod' && (int)$ret['code'] === 0){
                    $res = vod_lib::addnew($ret['data'] , $row);
                    if($res['vid'] > 0){
                        $ret['code'] = 0;
                        $ret['msg'] = $res['msg'];
                        // 单个页面含有全部资源的场景处理
                        if($row['conf']['utype'] == '3' || $row['conf']['utype'] == '4'){
                            $tmp = $ret['data']['player_url'][0];
                            $tmp[1] = '全部剧集';
                            $ret['data']['player_url'] = array($tmp);
                        }
                        // 资源站采集处理
                        if($row['conf']['utype'] == '5'){
                            $nums  = 0;
                            $ulist = vod_lib::formatjsurl($ret['data']['player_url'] , $ret['data']['name'] , $this->conf['vsname']);
                            if(!empty($ulist)){
                                $uobj = OBJ('vod_url_tab');
                                foreach ($ulist as $k => $v){
                                    foreach ($v as $sv){
                                        $uobj->set("vid" , $res['vid'])->set('url' , $sv['url'])->set('name' , $sv['sname']);
                                        $uobj->set("player" , $sv['player'])->set('uid' , $sv['uid'])->set('hash' , $sv['hash']);
                                        $uobj->replace();
                                        $nums++;
                                    }
                                }
                            }
                            $ulist = null; unset($ulist);
                            $ret['msg'] = $nums . ' 集已入库';
                        }
                        // 默认单页单播放资源
                        else{
                            ga_lib::addtask($row['id'] , $res['vid'] , 0 , $ret['data']['player_url'] , 0);
                        }
                    }else{
                        $ret['msg'] = '采集失败了';
                    }
                }
            }else{
                $ret['code'] = '1';
                $ret['msg']  = 'url错误了';
            }
            OBJ("ga_tab")->exec("update ga_tab set lasts = lasts + 1 , udate = " . REQUEST_TIME . " where id = '$id' ");
            $this->ajaxout($ret);
        }
    }

    /**
     * 执行采集
     *
     */
    public function execAct(){
        $id = intval($this->get('id'));
        $obj = OBJ('ga_tab');
        $ga = $obj->where("id = $id")->get();
        if($ga){
            $ga['conf'] = unserialize(base64_decode($ga['conf']));
            if($ga['pn'] == '0'){
                // 当前页初始化
                if($ga['sort']){
                    $ga['pn'] = $ga['pn'] ? $ga['pn'] : 1;
                }else{
                    $ga['pn'] = $ga['pn'] ? $ga['pn'] : $ga['maxpn'];
                }
            }else{
                $ga['pn'] =  $ga['pn'] + ($ga['sort'] ? 1 : -1);
            }
            // 首页
            if($ga['pn'] == 1){
                $purl = $ga['listurl'];
            }else{
                $pn = $ga['pn'];
                if(!empty($ga['conf']['pnformat'])){
                    $pn = sprintf($ga['conf']['pnformat'] , $pn);
                }
                $purl = str_replace('#数字#' , $pn , $ga['conf']['pregx']);
            }
            $this->assign('ga' , $ga);
            $data = ga_lib::getpages($purl , $ga);
            if($data['maxpn'] != $ga['maxpn']){
                $obj->set("maxpn" , (int)$data['maxpn']);
            }
            if($data['total'] != $ga['total']){
                $obj->set("total" , (int)$data['total']);
            }
            if((int)$data['maxpn'] === 0){
                $this->showmsg('采集完成' , core::url('ga-list-ctype-%d' , $ga['tab'] == 'art' ? 1 : 2) , 1 , 2);
            }
            $obj->set('pn' , $ga['pn'])->where("id = {$ga['id']}")->save();
            $this->assign('data' , $data);
            $this->assign('purl' , $purl);
            $this->assign('auto' , intval($this->get('auto')));
            $this->display('ga/ga.exec.html');
        }
    }

    /**
	 *  保存
	 *
	 */
    public function saveAct(){
        $obj = core::getobj('ga_tab');
        $ga  = $this->get('ga' , 'p');
        $ga['adate'] = $ga['adate'] ? $ga['adate'] : REQUEST_TIME;
        $ga['conf']['cmap'] = ga_lib::cmap($ga['conf']['csmap']);
        $ga['conf'] = base64_encode(serialize($ga['conf']));
        $ga['maxpn'] = intval($ga['maxpn']);
        $ctype = $ga['tab'] == 'vod' ? 2 : 1;
        if($obj->load($ga)){
            $ret = $obj->save();
            if($ret['code'] === 0){
                $this->showmsg('操作成功' , core::url('ga-list-ctype-%s' , $ctype) , 1 ,2);
            }
        }
        $this->showmsg($obj->geterr() , -1 ,1 ,2);
    }

    /**
     * 删除
     *
     */
    public function delAct(){
        $id = intval($this->get('id'));
        if($id > 0){
            $nav = core::getobj('ga_tab')->where("id = $id ")->del();
        }
        $this->showmsg('操作成功' , null , 1 , 1);
    }

    

    /**
     * 规则导出
     */
    public function exportAct(){
        $id = intval($this->get('id'));
        if($id > 0){
            $row = core::getobj('ga_tab')->where("id = $id ")->get();
            $row['id'] = 0;
            $row['pn'] = 0;
            $row['lasts'] = 0;
            $row['udate'] = 0;
            header('Content-Type: application/force-download');
            header("Content-Disposition: attachment; filename=Ga-{$id}.RGX");
            $out = base64_encode(serialize($row));
            echo (chunk_split(base64_encode(md5($out)) . $out));
        }
    }
    
    /**
     * 复制
     *
     */
    public function copyAct(){
        $id = intval($this->get('id'));
        if($id > 0){
            $ga = core::getobj('ga_tab')->where("id = $id ")->get();
            $ga['id'] = 0;
            $ga['pn'] = 0;
            $ga['lasts'] = 0;
            $ga['udate'] = 0;
            $ga['name'] = $ga['name'] . '_副本';
            OBJ('ga_tab')->load($ga);
            OBJ('ga_tab')->save();
            $this->showmsg('操作成功' , null , 1 , 1);
        }
    }

    /**
     * 重置
     *
     */
    public function setAct(){
        $id = intval($this->get('id'));
        if($id > 0){
            core::getobj('ga_tab')->where("id = $id ")->set('pn' , 0)->set('lasts' , 0)->set('udate' , 0)->save();
        }
        $this->showmsg('操作成功' , null , 1 , 1);
    }
    
    /**
     * 采集调试
     *
     */
    public function debugAct(){
        $ctype = intval($this->get('ctype'));
        $tab = $ctype == '2' ? 'vod' : 'art';
        $this->assign('ctype'  , $ctype);
        $this->assign('atitle' , '采集调试');
        $this->assign('list' , OBJ('ga_tab')->fields('id,name')->where("tab = '{$tab}'")->getall());
        $this->display('ga/ga.debug.html');
    }
}
?>