bilibili解析算法(单独算法)

%title插图%num

[rihide]

<?php
if(version_compare(PHP_VERSION,'5.6.0','<')){exit('请升级当前PHP环境,本版本解析需PHP5.6以上版本支持!');}
//error_reporting(0);
header('Content-type: text/json;charset=utf-8');
define('SELF', pathinfo(__file__, PATHINFO_BASENAME));
define('FCPATH', str_replace("\\", "/", str_replace(SELF, '', __file__)));

/*************************处理URL,判断参数*********************************/
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
if($_SERVER['PHP_SELF'] == '/index.php'){
	$_SERVER['PHP_SELF'] = '/';
}
$_SERVER['PHP_SELF'] = '/';
$page_url = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

$url_arr = explode('url=', $page_url);
$url = $url_arr[1];
if(count($url_arr) > 2){
	$url = $url_arr[1].'url='.$url_arr[2];
}

$Mao_param = [];
$Mao_param['url'] = $url;
$Mao_param['key'] = @$_GET['key'];

if(empty($Mao_param['url']) || empty($Mao_param['key'])){
    $Mao_echo = [];
    $Mao_echo['code'] = -100;
    $Mao_echo['msg'] = 'url和key不能为空';
    echo json_encode($Mao_echo);
    exit;
}
$Mao_param_url = urldecode($Mao_param['url']);
/*========================Cookie轮询 开始==============================*/
/*========================Cookie轮询 开始==============================*/
/*========================Cookie轮询 开始==============================*/
//cookie 为 access_key=bde4e6daa35f05913b3c6cd5242e96c1;段,官网自取
//ck数组
$list = array(
"0" => 'a30d04c7bec48a17b2dd7f61842a8ac1',
"1" => 'a30d04c7bec48a17b2dd7f61842a8ac1',
"2" => 'a30d04c7bec48a17b2dd7f61842a8ac1',
"3" => 'a30d04c7bec48a17b2dd7f61842a8ac1',
);

function cookieyokuLX($list , $polling_time , $polling_number ) {
    // 规划轮询间隔时间的参数:
    $interval = false;
    
    $arg = array(
        's'=>1 , // 秒
        'm'=>60 , // 分= 60 sec
        'h' =>3600 , // 时= 3600 sec
        'd' => 86400 , // 天= 86400 sec
    );

    // 判断间隔时间的类型,并计算间隔时间
    foreach ( $arg as $k => $v ) {
    if ( false !== stripos( $polling_time , $k ) ) {
    $interval = intval( $polling_time ) * $v;
    break;
    }
    }

    // 判断间隔时间
    if( !is_int( $interval ) ){
    return false;
}
 

// 从今年开始的秒数
$this_year_begin_second = strtotime( date( 'Y-01-01 01:00:01' , time() ) );

// 当前秒数 - 今年开始的秒数,得到今年到目前为止的秒数。
$polling_time = time() - $this_year_begin_second;

// 从今年到目前为止的秒数,计算得到当前轮数
$len = count( $list ); // 总长度
$start_index = intval( $polling_time / $interval );
$start_index = $polling_number * $start_index % $len; // 轮排数量 * 轮数 , 取余 总数量。

$res = array( );

// 将轮数 指向到数组的索引,然后从这个索引开始接着往下循环遍历。
for ( $i=0; $i < $len ; ++$i ) {
    $index = $i + $start_index; // 索引的变化是根据时间来变
    
    // 当遍历索引超过数组的最大下标时,
    if ( $index >= $len ) {
        $index = $index - $len ;
        }
        $res[] = $list[ $index ]; // 存入结果
        }
        return $res;
}
//30分切换一次
$new_list=cookieyokuLX($list,'1800 sec',1); // 秒=1 sec 分=60 sec 时=3600 sec 天=86400 sec

//print_r($new_list);


$Mao_vinfo['accesskey'] = $new_list[0];
//cookie 为 P_pck_rm= xxxxxxxxxxxxxc ;段,官网自取
$Mao_vinfo['cookie'] = 'SESSDATA=c985c0ca%2C1634384886%2C8a825%2A41;';
$id = inter($Mao_param_url,'/');
if(strpos($id,'?')){
    $id=substr($id, 0, strpos($id,'?'));
}
if(!$id) {
    $Mao_echo = [];
    $Mao_echo['code'] = -100;
    $Mao_echo['msg'] = 'url格式错误';
    echo json_encode($Mao_echo);
    exit;
}elseif(strpos($id,'ep') === 0){
    $id = preg_replace('/\D/s', '', $id);//取出id
    //量大会被拦截
    $content =get_curl_contents($url,'https://www.bilibili.com',0,0,0);
    // $src= preg_match('cid":281130492,"cover', $content);
    $a = '/"cid":(\d+),"cover":".*?","dimension":{"height":\d+,"rotate":\d+,"width":\d+},"duration":\d+,"from":"bangumi","id":'.$id.'/';
    // $a = '/\/upgcxcode\/\d+\/\d+\/(\d+)/';
    preg_match($a, $content, $src);

    if (empty($src[1])){
        $api = "https://api.bilibili.com/pgc/player/web/playurl?qn=112&fourk=1&ep_id=".$id;
        $content = get_curl_contents($api,'https://www.bilibili.com',0,0,$Mao_vinfo['cookie']);
        $a = '/\/upgcxcode\/\d+\/\d+\/(\d+)/';
        preg_match($a, $content, $src);
        // print_r("cid为".$content);
    }
    $cid= $src[1];
    $eid = $id;
    //缓存
    $h2_eq_file1='https://'.$_SERVER['HTTP_HOST'].'/bzcache/'.$id.'.json';
    $h2m3u8_fle1 = FCPATH . 'bzcache/'.$id.'.json';
    $h2m3u8_fles = 'bzcache/';
    $h2m3u8_def = 4*3600; //缓存时间 4小时

    if (is_file($h2m3u8_fle1)){//判断m3u8缓存文件是否存在
        if((time() - filemtime($h2m3u8_fle1) < $h2m3u8_def) && (filesize($h2m3u8_fle1) > 100)){//判断缓存时间
            $Mao_jxre =file_get_contents($h2m3u8_fle1);
            // $data = json_decode($Mao_jxre, 1);
            echo $Mao_jxre;
            exit;
        }
    };
    $time = time();
    $key = $Mao_param['key'];
    $secret = "560c52ccd288fed045859ed18bffd973";
    $data['sign'] = getSign($secret, $key, $cid, $eid, $time);
    $contents = get_url("https://api.bilibili.com/pgc/player/api/playurlproj?access_key=".$Mao_param['key']."&appkey=1d8b6e7d45233436&build=5580400&buvid=XY5FE2C514FA5B4CEF4AC6A80B5EA98CA470E&cid=".$cid."&device=android&ep_id=".$eid."&fnval=16&fnver=0&force_host=0&fourk=1&mobi_app=android&platform=android&qn=32&track_path=0&ts=".$time."&sign=".$data['sign']);
    $json = json_decode($contents,true);
    $epurl = $json["durl"][0]['url'];
    // var_dump($json );
    //     exit;
    if($json["code"] == 6002000 or $json["code"] == -400 or $json["code"] == 10005){
        $key = $Mao_vinfo['accesskey'];
        // var_dump($key);
        $secret = "560c52ccd288fed045859ed18bffd973";
        $data['sign'] = getSign($secret, $key, $cid, $eid, $time);
        $contents = get_url("https://api.bilibili.com/pgc/player/api/playurlproj?access_key=".$key."&appkey=1d8b6e7d45233436&build=5580400&buvid=XY5FE2C514FA5B4CEF4AC6A80B5EA98CA470E&cid=".$cid."&device=android&ep_id=".$eid."&fnval=16&fnver=0&force_host=0&fourk=1&mobi_app=android&platform=android&qn=32&track_path=0&ts=".$time."&sign=".$data['sign']);
        $json = json_decode($contents,true);
        $epurl = $json["durl"][0]['url'];   
        // var_dump($json["code"]);
        //如果还是失效则返回小电视接口
        if($json["code"] == 6002000 or $json["code"] == -400 or $json["code"] == 10005){
            $contents = get_url("https://api.snm0516.aisee.tv/x/tv/playurl?mobi_app=android_tv_yst&appkey=4409e2ce8ffd12b8&fnval=120&object_id=450011&qn=1&cid=".$cid."&access_key=3496a9d39d20fdfa84d7e9e88c661411&fourk=1&platform=android&ts=".$time."&build=104400&brand=Xiaomi&sys_ver=32&device_name=android&fnver=208&buvid=XY5FE2C514FA5B4CEF4AC6A80B5EA98CA470E&playurl_type=1");
            $json = json_decode($contents,true);
            $epurl = str_replace('222.134.1.67','upos-sz-mirrorhwb.bilivideo.com',$json["data"]["durl"][0]["url"]);
            $epurl = str_replace('222.134.1.66','upos-sz-mirrorhw.bilivideo.com',$json["data"]["durl"][0]["url"]);
            $epurl = str_replace('222.134.1.68','upos-sz-mirrorhw.bilivideo.com',$json["data"]["durl"][0]["url"]);
            $epurl = str_replace('222.134.1.71','upos-sz-mirrorhw.bilivideo.com',$json["data"]["durl"][0]["url"]);
            // var_dump($json);
            // var_dump($json["code"]);
            $Mao_jxre_data['code'] = 200;
            $Mao_jxre_data['ptype'] = 'html5';
            $Mao_jxre_data['url'] = $epurl;
            $Mao_jxre_data['ip'] = $_SERVER["REMOTE_ADDR"];
            $Mao_jxre_data['msg'] = '备用线路';
            $Mao_jxre_json = json_encode($Mao_jxre_data,1);
            echo $Mao_jxre_json;
            exit;
        
        }
    }
    $epurl = $json['durl'][0]['url'];
    $Mao_jxre_data['code'] = 200;
    $Mao_jxre_data['ptype'] = 'html5';
    $Mao_jxre_data['url'] = $epurl;
    $Mao_jxre_data['ip'] = $_SERVER["REMOTE_ADDR"];
    $Mao_jxre_data['msg'] = 'access_key错误';
    $Mao_jxre_json = json_encode($Mao_jxre_data,JSON_UNESCAPED_SLASHES);
    xmlsc1('youku',$Mao_jxre_json,$h2m3u8_fle1,$h2m3u8_fles);
    echo $Mao_jxre_json;
    exit;
}elseif(strpos($id,'BV') === 0){
    $cid =get_url('https://api.bilibili.com/x/player/pagelist?bvid='.$id);
    $json = json_decode($cid,true);
    $cid = $json["data"][0]["cid"];
    $api = 'https://api.bilibili.com/x/player/playurl?cid='.$cid.'&bvid='.$id.'&platform=html5&high_quality=1';
    $content = get_url($api);
    $json = json_decode($content,true);
    $epurl = $json["data"]["durl"][0]["url"];
    $Mao_jxre_data['code'] = 200;
    $Mao_jxre_data['ptype'] = 'html5';
    $Mao_jxre_data['url'] = $epurl;
    $Mao_jxre_data['ip'] = $_SERVER["REMOTE_ADDR"];
    $Mao_jxre_data['msg'] = 'Mao';
    $Mao_jxre_json = json_encode($Mao_jxre_data,JSON_UNESCAPED_SLASHES);
    echo $Mao_jxre_json;
    exit;
}elseif(strpos($id,'ss') === 0){
    $id = preg_replace('/\D/s', '', $id);//取出id
    $content = get_url("https://api.bilibili.com/pgc/web/season/section?season_id=".$id);
    $json = json_decode($content,true);
    $cid = $json["result"]["main_section"]["episodes"][0]["cid"];
    $eid = $json["result"]["main_section"]["episodes"][0]["id"];
    if ($json["result"]["main_section"]["episodes"][0]["badge"] =='会员'){
        
        $key = $Mao_vinfo['accesskey'];
    }else{
        $key = $Mao_param['key'];
    };
    $h2_eq_file1='https://'.$_SERVER['HTTP_HOST'].'/bzcache/'.$eid.'.json';
    $h2m3u8_fle1 = FCPATH . 'bzcache/'.$eid.'.json';
    $h2m3u8_fles = 'bzcache/';
    $h2m3u8_def = 3*3600; //缓存时间

    if (is_file($h2m3u8_fle1)){//判断m3u8缓存文件是否存在
        if((time() - filemtime($h2m3u8_fle1) < $h2m3u8_def) && (filesize($h2m3u8_fle1) > 100)){//判断缓存时间
            $Mao_jxre =file_get_contents($h2m3u8_fle1);
            // $data = json_decode($Mao_jxre, 1);
            echo $Mao_jxre;
            exit;
        }
    };
    
    $time = time();
    $secret = "560c52ccd288fed045859ed18bffd973";
    $data['sign'] = getSign($secret, $key, $cid, $eid, $time);
    $content = get_url("https://api.bilibili.com/pgc/player/api/playurlproj?access_key=".$key."&appkey=1d8b6e7d45233436&build=5580400&buvid=XY5FE2C514FA5B4CEF4AC6A80B5EA98CA470E&cid=".$cid."&device=android&ep_id=".$eid."&fnval=16&fnver=0&force_host=0&fourk=1&mobi_app=android&platform=android&qn=32&track_path=0&ts=".$time."&sign=".$data['sign']);
    // var_dump($content);
    // var_dump($eid);
    // exit;
    $json = json_decode($content,JSON_UNESCAPED_SLASHES);
    // var_dump($json);
    if($json["code"] == 6002000){
        $Mao_jxre_data['code'] = 6002000;
        $Mao_jxre_data['ptype'] = 'html5';
        $Mao_jxre_data['url'] = $epurl;
        $Mao_jxre_data['ip'] = $_SERVER["REMOTE_ADDR"];
        $Mao_jxre_data['msg'] = 'access_key错误';
        $Mao_jxre_json = json_encode($Mao_jxre_data,1);
        echo $Mao_jxre_json;
        exit;
    }
    $epurl = $json["durl"][0]["url"];
    $Mao_jxre_data['code'] = 200;
    $Mao_jxre_data['ptype'] = 'html5';
    $Mao_jxre_data['url'] = $epurl;
    $Mao_jxre_data['ip'] = $_SERVER["REMOTE_ADDR"];
    $Mao_jxre_data['msg'] = 'Mao';
    $Mao_jxre_json = json_encode($Mao_jxre_data,1);
    xmlsc1('youku',$Mao_jxre_json,$h2m3u8_fle1,$h2m3u8_fles);
    echo $Mao_jxre_json;
    exit;
}else{
    $Mao_echo = [];
    $Mao_echo['code'] = 404;
    $Mao_echo['msg'] = '解析失败';
    echo json_encode($Mao_echo);
    exit;
}
//带cookie访问
function get_curl_contents($url,$referer=0,$header=0,$nobody=0,$cookie=0){
		if(!function_exists('curl_init')) die('php.ini未开启php_curl.dll');
		$c = curl_init();
		curl_setopt($c, CURLOPT_URL, $url);
		curl_setopt($c, CURLOPT_HEADER, $header);
		curl_setopt($c, CURLOPT_NOBODY, $nobody);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($c, CURLOPT_SSL_VERIFYHOST, FALSE);
        if($cookie){
			curl_setopt($c, CURLOPT_COOKIE, $cookie);
		}
		curl_setopt($c, CURLOPT_ACCEPT_ENCODING, "gzip,deflate");
		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($c, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($c, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.$_SERVER["REMOTE_ADDR"], 'CLIENT-IP:'.$_SERVER["REMOTE_ADDR"]));
		if($referer){
			curl_setopt($c, CURLOPT_REFERER, $referer);
		}else{
			curl_setopt($c, CURLOPT_REFERER, '');
		}
		$content = curl_exec($c);
		curl_close($c);
	return $content;	
}
function inter($str, $start)
{
    if ($str && $start) {
        $arr = explode($start, $str);
          foreach ($arr as $value) {
                if(strpos($value,'BV')=== 0 || strpos($value,'ss')=== 0 || strpos($value,'ep')=== 0 ){
                    return $value;
                }
        }
    }
}
function getSign($secret, $key, $cid, $eid, $time) {
    $data = array(
            "access_key"=> $key,
            "appkey"=> "1d8b6e7d45233436",
            "build"=> "5580400",
            "buvid"=> "XY5FE2C514FA5B4CEF4AC6A80B5EA98CA470E",
            "cid"=> $cid,
            "device"=> "android",
            "ep_id"=> $eid,
            "fnval"=> "16",
            "fnver"=> "0",
            "force_host"=> "0",
            "fourk"=> "1",
            "mobi_app"=> "android",
            "platform"=> "android",
            "qn"=> "32",
            "track_path"=> "0",
            "ts"=> $time,
    );    
  // 对数组的值按key排序
  ksort($data);
  // 生成url的形式
  $params = http_build_query($data);
  // 生成sign
  $sign = md5($params . $secret);
  return $sign;
}
function get_url($url)
{

  //$ip = '154.13.31.22';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url); //设置访问的url地址
//  curl_setopt($ch, CURLOPT_PROXY, $ip);  // 使用代理ip
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//不输出内容
  $result = curl_exec($ch);
  curl_close ($ch);
  return $result;
}



function xmlsc1($id,$msg1,$fle1,$fles=''){
if(!is_readable($fles)){is_file($fles) or mkdir($fles,0755,true);}
$fpp=fopen($fle1,"w+");
fputs($fpp,$msg1);
fclose($fpp);
}
?>

[/rihide]

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 共6条

请登录后发表评论

      • btjson的头像-站长资源网btjson徽章-表示赞同-站长资源网等级-LV9-站长资源网作者0