CodeIgniter: загрузить видео на YouTube

Я использую библиотеки CodeIgniter + Zend. Я хочу, чтобы пользователи могли загружать видео на мой сайт, которые я затем буду загружать на свой канал YouTube. Это мое первое знакомство с API YouTube. Может ли кто-нибудь указать мне правильное направление?

Правильно ли я смотрю на это: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html#Direct_uploading? У кого-нибудь есть фрагмент кода, который показывает, как загрузка выполняется через PHP?


person StackOverflowNewbie    schedule 16.02.2012    source источник


Ответы (3)


Я не рекомендую использовать Zend с CI из-за его размера и сложности. Я разработал библиотеку специально для CodeIgniter https://github.com/jimdoescode/CodeIgniter-YouTube-API-Library

Библиотека предоставляет несколько различных вариантов загрузки на YouTube. Вы можете сделать прямую загрузку, когда вы загружаете видео, хранящееся на вашем сервере, на YouTube. Также есть возможность использовать форму для загрузки видео с клиента на youtube. Проверьте это и дайте мне знать, если у вас есть какие-либо вопросы.

person Jim S.    schedule 18.06.2012

Попробуйте это работает

class Addvideo extends Controller {



    function Addvideo()

    {

        parent::Controller();


        $this->load->library("zend");
        $this->zend->load("Zend/Gdata/AuthSub");
        $this->zend->load("Zend/Gdata/ClientLogin");
        $authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';

        /************Authentication**************/

        $this->zend->load("Zend/Gdata/YouTube");
        $this->zend->load("Zend/Gdata/HttpClient");

        $this->zend->load("Zend/Gdata/App/MediaFileSource");
        $this->zend->load("Zend/Gdata/App/HttpException");
        $this->zend->load("Zend/Uri/Http");


        $youtube = new Zend_Gdata_YouTube();
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
        $Gdata_AuthSub=new Zend_Gdata_AuthSub();

        $this->load->helper("text");
    }

        function index(){
            $data['result']='videos';
            $this->load->view('videos/newform', $data); 

        }

    function indexed(){

        $title = 'GruppoDSE Video';
        $description = 'Description';

        $youtube = new Zend_Gdata_YouTube();    
        $authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
        $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
                $username = $this->config->item('username'),
                $password = $this->config->item('password'),
                $service = 'youtube',
                $client = null,
                $source = 'Arts Connector', // a short string identifying your application
                $loginToken = null,
                $loginCaptcha = null,
                $authenticationURL); 

        $developerKey = $this->config->item('developer_key');
        $applicationId = 'Arts Connector';
        $clientId = 'My video upload client - v1';
        $yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

        // create a new VideoEntry object
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

        $myVideoEntry->setVideoTitle($title);
        $myVideoEntry->setVideoDescription($description);
        // The category must be a valid YouTube category!
        $myVideoEntry->setVideoCategory('Autos');

        // Set keywords. Please note that this must be a comma-separated string
        // and that individual keywords cannot contain whitespace
        $myVideoEntry->SetVideoTags('cars, funny');

        $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
        $tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
        $data['tokenValue'] = $tokenArray['token'];
        $data['postUrl'] = $tokenArray['url']; 


            // place to redirect user after upload
            $data['nextUrl'] = 'http://www.avantajsoftwares.com/gruppo/uploadVideo';
            $res="Il file video aggiungere con successo, il risultato atteso verrà visualizzato dopo alcune volte";
            $this->session->set_userdata('greenFlag',$res);
            // build the form

            $this->load->view('videos/form', $data);

        }

    function AddVideoAjax(){

             $title=$_POST['title'];
             $description=$_POST['description'];

        $youtube = new Zend_Gdata_YouTube();    
        $authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
        $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
                $username = $this->config->item('username'),
                $password = $this->config->item('password'),
                $service = 'youtube',
                $client = null,
                $source = 'Arts Connector', // a short string identifying your application
                $loginToken = null,
                $loginCaptcha = null,
                $authenticationURL); 

        $developerKey = $this->config->item('developer_key');
        $applicationId = 'Arts Connector';
        $clientId = 'My video upload client - v1';
        try {
        $yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

        // create a new VideoEntry object
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

        $myVideoEntry->setVideoTitle($title);
        $myVideoEntry->setVideoDescription($description);
        // The category must be a valid YouTube category!
        $myVideoEntry->setVideoCategory('Education');

        // Set keywords. Please note that this must be a comma-separated string
        // and that individual keywords cannot contain whitespace
        $myVideoEntry->SetVideoTags('Seminar, Events');

        $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
        $tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
        $tokenValue = $tokenArray['token'];
        $postUrl = $tokenArray['url']; 


            // place to redirect user after upload
            $nextUrl = 'http://www.avantajsoftwares.com/gruppo/Addvideo';
            $res="Il file video aggiungere con successo, il risultato atteso verrà visualizzato dopo alcune volte";
            $this->session->set_userdata('greenFlag',$res);
            // build the form

            echo  $form = '<form action="'. $postUrl .'?nexturl='. $nextUrl .
                    '" method="post" enctype="multipart/form-data" onsubmit="return valid()">'. 
                    '<div style="float:left;"><input name="file" type="file" id="file"/></div><div class="preloader"></div>'. 
                    '<input name="token" type="hidden" value="'.  $tokenValue .'"/>'.
                    '<div style="clear:both"></div>'.
                    '<div class="login-footer" id="prog_bar style="cursor:pointer"><input value="Carica video" type="submit" id="validate" class="button" onclick="progress_bar()"/></div>'. 
                    '</form>';



            } catch (Zend_Gdata_App_Exception $e) {

                echo $return="<div class='login-footer' style='width:130px;'><a style='height:16px; padding-top:7px;' class='button' href=".site_url()."Addvideo>Riprova di nuovo</a></div>";
            }
            // Assuming that $videoEntry is the object that was returned during the upload
             //$state = $myVideoEntry->getVideoState();




        }

    function getAuthSubRequestUrl()
        {
            $gdata_AuthSub = new Zend_Gdata_AuthSub();
            $next = 'http://www.avantajsoftwares.com/gruppo/videos';
            $scope = 'http://gdata.youtube.com';
            $secure = false;
            $session = true;
            return $data=$gdata_AuthSub->getAuthSubTokenUri($next, $scope, $secure, $session);
        }

    function getAuthSubHttpClient()
        {
            echo $_SESSION['sessionToken'];

            if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
                echo '<a href="' . $this->getAuthSubRequestUrl() . '">Login!</a>';
                return;
            } else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
              $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
            }

            $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
            return $httpClient;
        }


    /*************************** Class end ***********************************/
}
person Sajeev Krishnan    schedule 14.09.2012

В документации этот и другие методы описаны для Zend Gdata: Загрузка видео

person Martti Laine    schedule 16.02.2012
comment
Martti — похоже, в демо-версии объясняется, как загрузить видео в аккаунт пользователя на YouTube. Я хочу, чтобы пользователь загружал видео в мою учетную запись YouTube. - person StackOverflowNewbie; 16.02.2012
comment
Вы можете аутентифицировать только одну учетную запись, внедрив данные для входа в источник с помощью Логин клиента. - person Martti Laine; 16.02.2012
comment
@MarttiLaine, я думаю, ты прав. Я думал, что нечто подобное должно быть возможно. - person Mischa; 16.02.2012
comment
@StackOverflowNewbie Я не вижу причин не делать этого: он реализован в Zend Gdata, и это единственный способ аутентификации одной учетной записи. Документы рекомендуют этого не делать, потому что в наши дни рекомендуется обрабатывать аутентификацию с помощью чего-то другого, кроме прямого имени пользователя/пароля, но в вашем случае это единственный шанс. - person Martti Laine; 16.02.2012