api - Youtube api 上传视频不起作用 "Error : NoLinkedYouTubeAccount "

标签 api codeigniter video upload youtube

我正在使用 youtube api 从我的网站上传视频,这是我第一次使用我的 google 帐户。我给了 youtube 帐户用户名、密码和开发人员 key ,我收到错误“NoLinkedYouTubeAccount”。

有人帮我解决这个问题。

    /**
    *  developerKey
    */
    public $developerKey;

    /**
    *  accessToken - authorization access taken 
    */
    public $accessToken;


    /**
    *  next_index - used to track short results
    */
    public $next_index;

    /**
    *  authType - authentication type GoogleLogin or  AuthSub
    */
    public $authType;

    /**
     *  initializes the token and API key information for API methods which requires authentication information
     *  @param developerKey - String 
     *  @param accessToken - array
     *  @return void
     *  @access public
     *  Modified: Sandip
    */

    public function __construct($params){
        $this->accessToken = $params['accessToken'];
        $this->authType = $params['authType']; 
        $this->developerKey=$params['developerKey'];
    }

    /**
     *  client login authentication
     *  @param username - String 
     *  @param pass - String
     *  @return array
     *  @access public
     *  Modified: Sandip
    */

    public function clientLoginAuth($username,$pass){
        $this->authType = 'GoogleLogin'; 
        $url = 'https://www.google.com/youtube/accounts/ClientLogin';
        $data = 'Email='.urlencode($username).'&Passwd='.urlencode($pass).'&service=youtube&source=Test';
        $result = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $curlheader[0] = "Content-Type:application/x-www-form-urlencoded";
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    
        curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
        $result['output'] = curl_exec($ch);
        $result['err'] = curl_errno( $ch );
        $result['errmsg']  = curl_error( $ch );
        $result['header']  = curl_getinfo( $ch );
        $temp = explode("YouTubeUser=",$result['output']);
        $result['username'] = trim($temp[1]);
        $temp2 = explode("=",trim($temp[0]));
        $result['token'] = trim($temp2[1]);
        $this->accessToken = $result['token'];
        curl_close($ch);
        return $result;
    }



    public function uploadVideo($filename,$fullFilePath,$title,$description,$tags)
    {

        $fdata = file_get_contents($fullFilePath);  
        $tmpdata = '<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<media:title type="plain">'.$title.'</media:title>
<media:description type="plain">'.$description.'</media:description> 
<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category>    <media:keywords>'.$tags.'</media:keywords>
</media:group>
</entry> 
';
        $url = 'http://gdata.youtube.com/feeds/api/users/default/uploads';
        $data = '--f93dcbA3

内容类型:application/atom+xml;字符集=UTF-8

'.$tmpdata.'
--f93dcbA3
内容类型:视频/快速时间
内容传输编码:二进制

'.$fdata.'
--f93dcbA3--';
        $token = $this->accessToken;
        $developerKey = $this->developerKey;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $curlheader[0] = "Host: uploads.gdata.youtube.com";
        if($this->authType == 'GoogleLogin')
            $curlheader[1] = "Authorization: ".$this->authType." auth=\"$token\"";
        else
            $curlheader[1] = "Authorization: ".$this->authType." token=\"$token\"";
        $curlheader[2] = "GData-Version: 2";
        $curlheader[3] = "X-GData-Key: key=\"$developerKey\"";
        $curlheader[4] = "Slug: ".$filename;    
        $curlheader[5] = "Content-Type: multipart/related; boundary=\"f93dcbA3\"";
        $curlheader[6] = "Content-Length: ".strlen($data);
        $curlheader[7] = "Connection: close";


        curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        //print_r($info);

        curl_close($ch);

        unset($fdata);
        $validresult = $this->checkErrors($output);


        if($validresult['is_error'] == 'No')
        {

            $xml = $validresult['xml'];

            $webSite = 'http://www.youtube.com/';
            $criteria = 'uploads';
            $mediaInfo = array();
            $gdMedia = $xml->children('http://schemas.google.com/g/2005');
            $media = $xml->children('http://search.yahoo.com/mrss/');
            $ytMedia = $xml->children('http://gdata.youtube.com/schemas/2007');
            $georssMedia = $xml->children('http://www.georss.org/georss');

            if($media->group->title){
                $mediaInfo['title'] = sprintf("%s",$media->group->title[0]);
            }else{
                $mediaInfo['title'] = '';
            }
            if($media->group->description){
                $mediaInfo['description'] = sprintf("%s",$media->group->description[0]);
            }else{
                $mediaInfo['description'] = '';
            }
            if($media->group->player){

                $video = $media->group->player[0]->attributes()->url;
                $vLink = preg_replace('/=/', "/", $video);
                $videoLink = preg_replace('/\?/', "/", $vLink);
                $mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
                $test_str = preg_split('/\/v\//', $videoLink, 2);
                $video_id_array = preg_split('/&/', $test_str[1],2);
                $mediaInfo['videoId'] = $video_id_array[0];
            }else{
                if($entry->link[0]->attributes()->href){
                    $video = $entry->link[0]->attributes()->href;
                    $vLink = preg_replace('/=/', "/", $video);
                    $videoLink = preg_replace('/\?/', "/", $vLink);
                    $mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
                    $test_str = preg_split('/\/v\//', $videoLink, 2);
                    $video_id_array = preg_split('/&/', $test_str[1],2);
                    $mediaInfo['videoId'] = $video_id_array[0];


                }else{
                    return "video not found.";

                }
            }
                $mediaInfo['path_url'] = $mediaInfo['contentUrl'];
                $mediaInfo['webSite'] = $webSite;
                $mediaInfo['genre'] = sprintf("%s",@$media->group->category[0]);
                $mediaInfo['criteria'] = $criteria;

                unset($xml);
                unset($gdMedia);
                unset($media);
                unset($ytMedia);
                unset($georssMedia);

                return $mediaInfo;
        }
        else
        {
            $result = array();
            $result['is_error'] = $validresult['is_error'];
            $result['error'] = $validresult['error'];
            unset($validresult);
            return $result;

        }           

    }


    public function getUploadedVideos($username='default',$startIndex=1,$limit=10,$location='',$location_radius='',$safeSearch='strict',$strict='true'){



        $url = 'http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?start-index='.$startIndex.'&max-results='.$limit.'&strict='.$strict;
        if($location !='')
        {
            $url .= '&location='.$location;
            $url .= '&location-radius='.$location_radius;
        }
        //echo "<br>".$url;
        $criteria = 'uploads';
        if($username == 'default')
            $output = $this->make_api_call($url);
        else
        {
            $response = $this->make_get_call($url);
            $output = $response['output'];
        }

        $result = array();

        $validresult = $this->checkErrors($output);

        if($validresult['is_error'] == 'No')
        {
            $xml = $validresult['xml'];

            $tmp = $xml->xpath("openSearch:totalResults");
            $tmp_totalresults = (string)$tmp[0];

            $tmp = $xml->xpath("openSearch:startIndex");
            $result['startindex'] = (string)$tmp[0];

            //$tmp = $xml->xpath("openSearch:itemsPerPage");
            //$result['itemsPerPage'] = (string)$tmp[0];

            $res = $this->getFormatedVideoresult($xml,$criteria);

            //Pagination logic
            $shortCnt = $this->getShortCount();
            //


            if($shortCnt > 0 && $tmp_totalresults > $limit)
            {
                $newStartIndex = $startIndex + $limit;
                $newmaxresults = $shortCnt;

                $iteration = 1;
                while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){            
                    if($iteration !=1){
                        $newStartIndex = $newStartIndex + $newmaxresults;
                        $newmaxresults = $shortCnt;
                    }
                        $iteration++;

                    $url = 'http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
                    if($location !='')
                    {
                        $url .= '&location='.$location;
                        $url .= '&location-radius='.$location_radius;
                    }

                    $shortResult = $this->getShortResult($url,$criteria);

                    if(@$shortResult['is_error']=='No'){
                        if(!empty($shortResult['result']))
                        {
                            ////echo "<br>INSIDE";  
                            foreach($shortResult['result'] as $shortkey => $shortItem)
                                $res[] = $shortItem;        
                                $shortCnt = $this->getShortCount();
                        }
                        else
                        {
                            continue;
                        }                           
                    }
                    else
                    {
                        break;
                    }                       
                }//while

                $result['nextPageIndex'] = @(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
            }
            else
            {
                $result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
            }
            if($tmp_totalresults < $result['nextPageIndex'])    
            {
                $result['nextPageIndex'] = 0;
            }


            //pagination logic


            $result['itemsPerPage'] = $limit;               
            $result['totalresults'] = count($res);

            $result['result'] = $res;

            unset($res);
            unset($xml);
        }
        else
        {
            $result['is_error'] = $validresult['is_error'];
            $result['error'] = $validresult['error'];

        }
        unset($validresult);

        return $result;
    }
    public function checkErrors($response){

        $result = array();
        $result['is_error'] = 'No';
        $reg_ex = '/<H1>Bad Request<\/H1>/';
        $res = preg_match_all($reg_ex,$response,$matches);          

        if(!empty($matches[0])) {
            $result['is_error'] = 'Yes';
            $result['error'] = "Bad Request";
        } 
        else {

            $xml = @simplexml_load_string($response);
            if($xml === FALSE && $response !=''){
                $result['error'] = $response;
                $result['is_error'] = 'Yes';
            }
            else{

                if(@$xml->error){

                    $msg = @(string)$xml->error->code.':'.@(string)$xml->error->internalReason;
                    unset($xml);
                    $result['error'] = $msg;
                    $result['is_error'] = 'Yes';
                }
                else{
                     $result['xml'] = $xml;
                }
            }
        }
        unset($xml);
        unset($response);
        return $result;
    }
    public function getContentURL($url){
        $output = $this->make_api_call($url);
        $result = array();
        $validresult = $this->checkErrors($output);
        if($validresult['is_error'] == 'No')
        {
            $xml = $validresult['xml'];
            $ytMedia = $xml->children('http://gdata.youtube.com/schemas/2007');
            $result['term'] = $xml->category[1]->attributes()->term;
            $result['title'] = (string)$xml->title;
            $result['username'] = (string)$ytMedia->username;
            $result['contentURL'] = (string)$xml->content->attributes()->src;
            if(stristr($result['title'],'Activity of'))
            {
                $result['contentURL'] = 'http://gdata.youtube.com/feeds/api/users/'.$result['username'].'/uploads?v=2';

            }           
        }
        else
        {
            $result['is_error'] = $validresult['is_error'];
            $result['error'] = $validresult['error'];
        }
        unset($validresult);
        return $result;
    }

public function getRecentUploadedVideos($xml){
        $i = 0;
        $res = array();         
        foreach($xml->entry as $fentry){
            $i++;
            $term = $fentry->category[1]->attributes()->term;               
            if($term == 'video_uploaded')
            {       
                    $mediaInfo = array();
                    $entry = $fentry->link[1]->entry;                       
                    $gdMedia = $entry->children('http://schemas.google.com/g/2005');
                    $media = $entry->children('http://search.yahoo.com/mrss/');
                    $ytMedia = $entry->children('http://gdata.youtube.com/schemas/2007');
                    $georssMedia = $entry->children('http://www.georss.org/georss');
                    if($gdMedia->rating){
                        $rating = (string)$gdMedia->rating->attributes();
                        $mediaInfo['rating'] = $rating['average'];
                    }else{
                        $mediaInfo['rating'] = 0;
                    }
                    if($media->group->thumbnail){
                        $mediaInfo['iconImage'] = sprintf("%s",$media->group->thumbnail[0]->attributes()->url);
                    }else{
                        $mediaInfo['iconImage'] = '';
                    }
                    if($media->group->title){
                        $mediaInfo['title'] = sprintf("%s",$media->group->title[0]);
                    }else{
                        $mediaInfo['title'] = '';
                    }
                    if($media->group->description){
                        $mediaInfo['description'] = sprintf("%s",$media->group->description[0]);
                    }else{
                        $mediaInfo['description'] = '';
                    }
                    if($media->group->player){
                        $video = $media->group->player[0]->attributes()->url;
                        $vLink = preg_replace('/=/', "/", $video);
                        $videoLink = preg_replace('/\?/', "/", $vLink);
                        $mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
                        $test_str = preg_split('/\/v\//', $videoLink, 2);
                        $video_id_array = preg_split('/&/', @$test_str[1],2);
                        $mediaInfo['videoId'] = $video_id_array[0];
                    }                       
                    else{
                         $tmp = @$entry->xpath("app:control");
                         $tmp2 = @$tmp[0]->xpath("yt:state");

                        if(@$tmp2[0]->attributes()->name == 'restricted')
                        {
                            //echo "<br>INSIDE ".$mediaInfo['title'];
                            $this->next_index[$i] = 'n';
                            continue;
                        }
                        if(isset($entry->link) && $entry->link[0]->attributes()->href !=''){
                            $video = $entry->link[0]->attributes()->href;
                            $vLink = preg_replace('/=/', "/", $video);
                            $videoLink = preg_replace('/\?/', "/", $vLink);
                            $mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
                            $test_str = preg_split('/\/v\//', $videoLink, 2);
                            $video_id_array = preg_split('/&/', $test_str[1],2);
                            $mediaInfo['videoId'] = $video_id_array[0];
                            if(!$mediaInfo['videoId'])
                            {
                                $this->next_index[$i] = 'n';
                                //echo "video Skipped.";
                                continue;
                            }
                        }
                        else{

                            $this->next_index[$i] = 'n';
                            continue;
                        }
                    }   
                    $this->next_index[$i] = 'y';
                    $res[] = $mediaInfo;    
            }
            else
            {
                $this->next_index[$i] = 'n';
            }
        }   // foreach
    return $res;
}


     public function getRecentShortResult($url){
            $token = $this->accessToken;
            $developerKey = $this->developerKey;
            if($token !='' && $developerKey !='')
                $output = $this->make_api_call($url);
            else
            {
                $response = $this->make_get_call($url);
                $output = $response['output'];
            }
            $result = array();
            $validresult = $this->checkErrors($output);
            if($validresult['is_error'] == 'No')
            {
                $xml = $validresult['xml'];
                $tmp = $xml->xpath("openSearch:totalResults");
                $tmp_totalresults = (string)$tmp[0];
                $tmp = $xml->xpath("openSearch:startIndex");
                $result['startindex'] = (string)$tmp[0];
                $tmp = $xml->xpath("openSearch:itemsPerPage");
                $result['itemsPerPage'] = (string)$tmp[0];
                //$result['itemsPerPage'] = $maxresults;
                if($tmp_totalresults > $result['startindex']){
                    $res = $this->getRecentUploadedVideos($xml);
                    $result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
                }
                else
                    $result['nextPageIndex'] = 0;
                $result['result'] = @$res;
            }
            else
            {
                $result['error'] = $validresult['error'];
            }
            $result['is_error'] = $validresult['is_error'];
            unset($validresult);
            unset($output);
            unset($response);
            return $result;
    }
    public function getVideosBysubscriptionID($subscriptionID,$startIndex=1,$limit=10,$safeSearch='strict',$strict='true'){
        $url = 'http://gdata.youtube.com/feeds/api/users/default/subscriptions/'.$subscriptionID.'?v=2';
        $feedResponse = $this->getContentURL($url);
        $contentURL = @$feedResponse['contentURL'];
        $tempcontentURL = $contentURL;
        $contentURL .= '&start-index='.$startIndex.'&max-results='.$limit.'&strict='.$strict;
        $result = array();
        if($contentURL !=''){
        $output = $this->make_api_call($contentURL);
        $validresult = $this->checkErrors($output);
        if($validresult['is_error'] == 'No'){
                    $xml = $validresult['xml'];
                    $tmp = $xml->xpath("openSearch:totalResults");
                    $tmp_totalresults = (string)$tmp[0];
                    $tmp = $xml->xpath("openSearch:startIndex");
                    $result['startindex'] = (string)$tmp[0];
        if(@$feedResponse['recentUpload'] == 1){
                    $res = $this->getRecentUploadedVideos($validresult['xml']);                     

                    $shortCnt = $this->getShortCount();
                    if($shortCnt > 0 && $tmp_totalresults > $limit)
                    {
                        $newStartIndex = $startIndex + $limit;
                        $newmaxresults = $shortCnt;
                        $iteration = 1;
                        while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){            
                            if($iteration !=1){
                                $newStartIndex = $newStartIndex + $newmaxresults;
                                $newmaxresults = $shortCnt;                                 
                            }
                            $iteration++;
                            $url = $tempcontentURL.'&start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
                            $shortResult = $this->getRecentShortResult($url);
                            if(@$shortResult['is_error']=='No'){
                                if(!empty($shortResult['result']) && count($res) <= $limit)
                                {
                                    foreach($shortResult['result'] as $shortkey => $shortItem)
                                        $res[] = $shortItem;    
                                    $shortCnt = $this->getShortCount();
                                }
                                else
                                {
                                    continue;
                                }                           
                            }
                            else
                            {
                                break;
                            }                                   
                        }//WHILE
                        $result['nextPageIndex'] = @(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
                    }
                    else
                    {
                        $result['nextPageIndex'] = @$result['startindex'] + count($this->next_index);
                    }
                    if($tmp_totalresults < $result['nextPageIndex'])    
                    {
                        $result['nextPageIndex'] = 0;
                    }
                    $result['itemsPerPage'] = $limit;               
                    $result['totalresults'] = count($res);
                    $result['result'] = $res;
                    unset($res);
                    unset($xml);
            }
        else
        {
        $criteria = $feedResponse['title'];

            $xml = $validresult['xml'];
            $res = $this->getFormatedVideoresult($xml,$criteria);
            //Pagination logic
            $shortCnt = $this->getShortCount();
            if($shortCnt > 0 && $tmp_totalresults > $limit)
            {
                $newStartIndex = $startIndex + $limit;
                $newmaxresults = $shortCnt;
                $iteration = 1;
                while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){            
                    if($iteration !=1){
                        $newStartIndex = $newStartIndex + $newmaxresults;
                        $newmaxresults = $shortCnt;                         
                    }
                    $iteration++;
                    $url = $tempcontentURL.'&start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
                    $shortResult = $this->getShortResult($url,$criteria);
                    if(@$shortResult['is_error']=='No'){
                        if(!empty($shortResult['result']))
                        {

                            foreach($shortResult['result'] as $shortkey => $shortItem)
                                $res[] = $shortItem;        
                                $shortCnt = $this->getShortCount();
                        }
                        else
                        {
                            continue;
                        }                           
                    }
                    else
                    {
                        break;
                    }                       
                }//while
                $result['nextPageIndex'] = @(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
            }
            else
            {
                $result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
            }
            if($tmp_totalresults < $result['nextPageIndex'])    
            {
                $result['nextPageIndex'] = 0;
            }
            //pagination logic
            $result['itemsPerPage'] = $limit;               
            $result['totalresults'] = count($res);
            $result['result'] = $res;
            unset($res);
            unset($xml);

        }
        }// NO
        else
            {
                $result['is_error'] = $validresult['is_error'];
                $result['error'] = $validresult['error'];
            }
    }
    else
    {
        $result['is_error'] = $feedResponse['is_error'];
        $result['error'] = $feedResponse['error'];
    }
        unset($validresult);
        unset($feedResponse);
        return $result;
    }

}
/* 文件结束 Someclass.php */

谢谢。

最佳答案

对于遇到此问题的任何人,我都遇到了此错误,并通过以主要用户身份登录 YouTube,转到右上角并单击“YouTube 设置”来修复它。然后我点击“创建 channel ”。错误消失了!

关于api - Youtube api 上传视频不起作用 "Error : NoLinkedYouTubeAccount ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14833393/

相关文章:

php - 从 json api 到 mysql

swift - 如何使用alamofire在ios中传递访问 token

php - ci : google indexing address with index. php 但站点中没有与 index.php 的链接

php - 如何使用 CodeIgniter DBForge 在 MySQL 中创建 DATETIME 字段?

c# - 从 C# 中的一系列图像生成视频

json - 如何使用 Axios 通过 React 发出循环请求?

php - 对于具有 Cocoa 和 JS 客户端的 Web 服务来说,最简单的数据交换格式是什么?

python - 使用python为视频添加字幕

python - 如何在Python中使用h.264引用软件提取运动向量

api - 如何构建自动完成 API?