YouTuBe 解析API

  • 内容
  • 相关
<?php
/**
 *
 * YouTuBe API
 *
 * @author     DanMo <https://blog.52xiee.com/>
 * @date       2018-08-21
 * @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 = 'https://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)) );
如果你觉得雨滴资源网对你有帮助的话,可以小小的打赏一下小站,用于维持本站的运营!

本文标签:

版权声明:雨滴资源网内容来源于互联网,如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!

本文链接:YouTuBe 解析API - https://www.yudzy.com/91.html

失效提示:此文更新于2018-8-21,如果文章内容或图片资源失效,请留言反馈,客服会及时处理,谢谢!