YouTuBe 解析API

技术文章 无标签
<?php
/**
 *
 * YouTuBe API
 *
 * @author     DanMo <https://www.pohaier.com/>
 * @date       2018-08-18 19:42:30
 * @version    0.26
 *
 *
 */
error_reporting(0);
header('Content-type: text/json;charset=utf-8');

$ui = array();
foreach($_GET as $key => $value){
    $ui[$key] = trim($value);
}

if( empty($ui['vid']) ){
    die('Please attach relevant parameters!');
}

define('VID',$ui['vid'] );
define('VIDEO_URL',"https://www.youtube.com/watch?v=");
define('YouTuBe_Api',"https://y2mate.com/zh-cn/analyze/ajax");
define('TEST_API_KEY', 'AIzaSyCOz5Yml_mICULfhM0s_u87l4MRvcL7_p0' );
define('API_KEY', 'AIzaSyBiMxVlkwUqqHbxVU3HJV3KcPFQPikfZwE' );

function https_curl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}

function api_curl($url,$data){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    curl_setopt($curl, CURLOPT_HEADER,0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'ERROR '.curl_error($curl);
    }
    curl_close($curl);
    return $response ;
}

$APIs = [
    'categories.list'    => 'https://www.googleapis.com/youtube/v3/videoCategories',
    'videos.list'        => 'https://www.googleapis.com/youtube/v3/videos',
    'search.list'        => 'https://www.googleapis.com/youtube/v3/search',
    'channels.list'      => 'https://www.googleapis.com/youtube/v3/channels',
    'playlists.list'     => 'https://www.googleapis.com/youtube/v3/playlists',
    'playlistItems.list' => 'https://www.googleapis.com/youtube/v3/playlistItems',
    'activities'         => 'https://www.googleapis.com/youtube/v3/activities',
];

function getApi($name){
    global $APIs;
    return $APIs[$name]."?";
}

function _parse_url_path($url){
    $array = parse_url($url);
    return $array['path'];
}

function _parse_url_query($url){
    $array = parse_url($url);
    $query = $array['query'];
    $queryParts = explode('&', $query);
    $params = [];
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = empty($item[1]) ? '' : $item[1];
    }
    return $params;
}

function getVideoInfo($vId, $part = ['id', 'snippet', 'contentDetails', 'player', 'statistics', 'status']){
    $API_URL = getApi('videos.list');
    $params = [
        'id' => is_array($vId) ? implode(',', $vId) : $vId,
        'key' => API_KEY,
        'part' => implode(', ', $part),
    ];
    return https_curl($API_URL,$params,0);
}

function getPageContent($id){
    $page = 'http://www.youtube.com/watch?v='.$id;
    $arr = array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false,
        ),
    );  
    $content = file_get_contents($page, false, stream_context_create($arr));
    return $content;
}

function getDownloadLinks($id){
    $videoMap = array(
        "13" => array("3GP", "Low Quality - 176x144"),
        "17" => array("3GP", "Medium Quality - 176x144"),
        "36" => array("3GP", "High Quality - 320x240"),
        "5" => array("FLV", "Low Quality - 400x226"),
        "6" => array("FLV", "Medium Quality - 640x360"),
        "34" => array("FLV", "Medium Quality - 640x360"),
        "35" => array("FLV", "High Quality - 854x480"),
        "43" => array("WEBM", "Low Quality - 640x360"),
        "44" => array("WEBM", "Medium Quality - 854x480"),
        "45" => array("WEBM", "High Quality - 1280x720"),
        "18" => array("MP4", "Medium Quality - 480x360"),
        "22" => array("MP4", "High Quality - 1280x720"),
        "37" => array("MP4", "High Quality - 1920x1080"),
        "38" => array("MP4", "High Quality - 4096x230")
    );

    $content = getPageContent($id);
    $videos = array('MP4' => array(), 'FLV' => array(), '3GP' => array(), 'WEBM' => array());

    if(preg_match("'\"url_encoded_fmt_stream_map\":\"(.*?)\"'si", $content, $r)){
        $data = $r[1];
        $data = explode(',', $data);

        foreach($data As $cdata){
            $cdata = str_replace('\u0026', '&', $cdata);
            $cdata = explode('&', $cdata);

            foreach($cdata As $xdata){
                if(preg_match('/^sig/', $xdata)){
                    $sig = substr($xdata, 4);
                }

                if(preg_match('/^url/', $xdata)){
                    $url = substr($xdata, 4);
                }

                if(preg_match('/^itag/', $xdata)){
                    $type = substr($xdata, 5);
                }
            }
            $url = urldecode($url);
            $videos[$videoMap[$type][0]][$videoMap[$type][1]] = $url;
        }
    }
    return $videos;
}
function format_bytes($size){
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for($i = 0; $size >= 1024 && $i < 4; $i++){
        $size /= 1024;
    }
    return round($size, 2).$units[$i];
}
function itag($itag){
    $stream_itag = array(
        "38" =>"3072p",
        "85" =>"1080p",
        "46" =>"1080p",
        "37" =>"1080p",
        "102" =>"720p",
        "45" =>"720p",
        "84" =>"720p",
        "22" =>"720p",
        "120" =>"720p",
        "44" =>"480p",
        "35" =>"480p",
        "101" =>"360p",
        "100" =>"360p",
        "43" =>"360p",
        "34" =>"360p",
        "82" =>"360p",
        "18" =>"270p/360p",
        "6" =>"270p",
        "83" =>"240p",
        "13" =>"144p",
        "5" =>"240p",
        "36" =>"240p",
        "17" =>"144p"
    );
    //return $stream_itag[$itag];
    parse_str($itag,$info);

    return array(
        'iTag' => $stream_itag[$info['itag']],//清晰度
        //'Duration' => $info['dur'],//时间
        'mt' => $info['expire'],//文件大小
        'type' => $info['mime'] //文件形式
    );
}

function compress_html_main($buffer){
    $initial=strlen($buffer);
    $buffer=explode("<!--html-->", $buffer);
    $count=count ($buffer);
    for ($i = 0; $i <= $count; $i++){
        if (stristr($buffer[$i], '<!--html no compression-->')){
            $buffer[$i]=(str_replace("<!--html no compression-->", " ", $buffer[$i]));
        }else{
            $buffer[$i]=(str_replace("\t", " ", $buffer[$i]));
            $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));
            $buffer[$i]=(str_replace("\n", "", $buffer[$i]));
            $buffer[$i]=(str_replace("\r", "", $buffer[$i]));
            while (stristr($buffer[$i], '  '))
            {
            $buffer[$i]=(str_replace("  ", " ", $buffer[$i]));
            }
        }
        $buffer_out.=$buffer[$i];
    }
        return $buffer_out;
    }

    function returns($data){
        global $ui;
        return $ui['callback'] ? $ui['callback']."({$data})" : "Jquery_".bin2hex(base64_encode('sbtencentsbtencent'))."({$data})";
    }

    $params = [
        'url' => VIDEO_URL.VID,
        'ajax' => 1,
    ];

    //$_loc1_ = json_decode(api_curl(YouTuBe_Api,$params),true);
    $_loc1_ = json_decode(https_curl(YouTuBe_Api,$params,1),true);

    preg_match('|<div class="tab-pane fade active in" id="mp4">(.*?)</div> <div class="tab-pane fade" id="mp3">|',compress_html_main($_loc1_['result']),$_loc2_);

    preg_match("#data-vlink=\"(.*?)\" .*class=\"video-thumbnail\".* >#",compress_html_main($_loc1_['result']),$_loc3_);//默认播放
    preg_match_all("#data-vlink=\"(.*?)\" >#",$_loc2_[1],$_loc4_);//视频链接

    //preg_match_all("#</td> <td>(.*?)</td> <td class=\"txt-center\">#",$_loc2_[1],$_loc5_);//视频大小

    foreach( $_loc4_[1] as $row ){
        $vinfo = itag($row);
        $video[] = array(
            'url'  => $row,
            'itag' => $vinfo['iTag'],//清晰度
            'mt'   => $vinfo['mt'],//文件大小
            'type' => $vinfo['type'] //文件形式
        );
    }
    $_loc6_ = itag($_loc3_[1]);
    $data = array(
        'date' => gmdate("D M d Y h:i:s ")."GMT+0800 (中国标准时间)",
        'api' => 'mtop.api.video.url.youtube.get',
        'version' => '0.26',
        'tip' => 'More than 1080 definition films and audio segmentation are not provided', 
        'result' => array(
            'default' => array(
                'url'  => $_loc3_[1],
                'itag' => $_loc6_['iTag'],//清晰度
                'mt'   => $_loc6_['mt'],//文件大小
                'type' => $_loc6_['type'] //文件形式
            ),
            'video'   => $video,
        )
    );

    //print_r( $_loc4_[1] );
    //print_r( compress_html_main($_loc1_['result']) );
    print_r( returns(json_encode($data)) );

Comments (14)

    Generic placeholder image
    UEETEK Nail Grinder Reviews 回复

    Nice post. I was checking constantly this blog and
    I'm impressed! Extremely useful info specially the last part :) I care for such info a lot.
    I was seeking this certain information for a very long time.
    Thank you and good luck.

    Generic placeholder image
    SELF-CUT SYSTEM PRO Kit Price 回复

    Aw, this was a very good post. Taking the time and actual effort to create a really good article… but what can I say… I hesitate a lot and never manage to get nearly anything done.

      Generic placeholder image
      admin 回复
      @SELF-CUT SYSTEM PRO Kit Price

      Thank you. I will continue to try to write more articles about them.

    Generic placeholder image
    Andis SuperLiner Blade Replacement 回复

    Thank you for sharing your thoughts. I truly appreciate your efforts and I am waiting for your next post thank you once again.

    Generic placeholder image
    Barber Supplies Online Cheap 回复

    Wonderful web site. Plenty of useful info here.
    I am sending it to a few pals ans additionally sharing in delicious.

    And certainly, thanks for your sweat!

    Generic placeholder image
    SELF-CUT SYSTEM 2.0 Review 回复

    Hi, Neat post. There is an issue together with your web site in internet explorer, might test this?

    IE nonetheless is the market chief and a good portion of
    other folks will miss your wonderful writing due to this problem.

      Generic placeholder image
      admin 回复
      @SELF-CUT SYSTEM 2.0 Review

      In China, they use mainstream browsers.

      Generic placeholder image
      admin 回复
      @SELF-CUT SYSTEM 2.0 Review

      ......................................

    Generic placeholder image
    Barber Supplies Online Store 回复

    It is appropriate time to make a few plans for the long run and it is time
    to be happy. I have read this put up and if I
    may I want to counsel you some fascinating issues
    or tips. Perhaps you could write subsequent articles relating to this article.
    I wish to read even more issues approximately it!

      Generic placeholder image
      admin 回复
      @Barber Supplies Online Store

      Thank you for reading this article, you can ask questions, you can talk and discuss together.

    Generic placeholder image
    回复

    这个怎么用?

      Generic placeholder image
      admin 回复
      @宣

      不会用?你逗我嘛?