Jump to content

Youtube Authentication


zkagenotora

Recommended Posts

The application that I want to build is quite simple. Here is a bit of the background of the work flow:

 

In my company, we create video for our client profile. After the video is done, we upload the video to our website and to youtube. It is done automatically.

 

After a period of time, the client can delete the video. Of course, it will delete the video in our system as well as the video in youtube. For now, the video in our system is deleted automatically. However, youtube video is deleted manually.

 

Our company has grown to have quite a lot of clients. It's hard for us to keep track clients that requested to delete their videos. We want to be able to have an application that will delete youtube video automatically.

 

I already tried to play around with youtube authentication in http://code.google.com/apis/youtube/2.0/developers_guide_php.html#Authentication but I have no luck with the authentication.

 

I want the application to be able to delete the video under my youtube account without having me to login to youtube. In my case right now, every time the application wants to delete the video, I have to send the request to youtube and ask for verification (i.e. I have to do application verification every time).

 

Here is what I have done so far:

 

ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);


require_once('db_class.php');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_App_Exception');

session_start();
setLogging('on');
$_SESSION['developerKey'] = 'AI39si5H3hL9tcKOMl80IqzoC6nb87ka1QLgHxLp9nFi1l44dLa987_Gi0rbofLePQdFEWf1lrSB8KGs4lXIrcF8TR6PhUcO3Q';

function getAuthSubRequestUrl()
{
    $next = 'http://example.com/youtube_delete_video.php';
    $scope = 'http://gdata.youtube.com';
    $secure = false;
    $session = true;
    return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}

function updateAuthSubToken($singleUseToken)
{
    try {
        $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($singleUseToken);
    } catch (Zend_Gdata_App_Exception $e) {
        print 'ERROR - Token upgrade for ' . $singleUseToken
            . ' failed : ' . $e->getMessage();
        return;
    }

    $_SESSION['sessionToken'] = $sessionToken;
        
    generateUrlInformation();
    
    header('Location: ' . $_SESSION['homeUrl']);
}

function getAuthSubHttpClient()
{
    try {
        $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
    } catch (Zend_Gdata_App_Exception $e) {
        print 'ERROR - Could not obtain authenticated Http client object. '
            . $e->getMessage();
        return;
    }
    $httpClient->setHeaders('X-GData-Key', 'key='. $_SESSION['developerKey']);
    return $httpClient;
}

function generateUrlInformation()
{
    if (!isset($_SESSION['operationsUrl']) || !isset($_SESSION['homeUrl'])) {
        $_SESSION['operationsUrl'] = 'http://'. $_SERVER['HTTP_HOST']
                                   . $_SERVER['PHP_SELF'];
        $path = explode('/', $_SERVER['PHP_SELF']);
        $path[count($path)-1] = 'index.php';
        $_SESSION['homeUrl'] = 'http://'. $_SERVER['HTTP_HOST']
                             . implode('/', $path);
    }
}

function loggingEnabled()
{
    if ($_SESSION['logging'] == 'on') {
        return true;
    }
}

function setLogging($loggingOption, $maxLogItems = 10)
{
    switch ($loggingOption) {
        case 'on' :
            $_SESSION['logging'] = 'on';
            $_SESSION['log_currentCounter'] = 0;
            $_SESSION['log_maxLogEntries'] = $maxLogItems;
            break;

        case 'off':
            $_SESSION['logging'] = 'off';
            break;
    }
}

function logMessage($message, $messageType)
{
    if (!isset($_SESSION['log_maxLogEntries'])) {
        $_SESSION['log_maxLogEntries'] = 20;
    }

    if (!isset($_SESSION['log_currentCounter'])) {
        $_SESSION['log_currentCounter'] = 0;
    }

    $currentCounter = $_SESSION['log_currentCounter'];
    $currentCounter++;

    if ($currentCounter > $_SESSION['log_maxLogEntries']) {
        $_SESSION['log_currentCounter'] = 0;
    }

    $logLocation = 'log_entry_'. $currentCounter . '_' . $messageType;
    $_SESSION[$logLocation] = $message;
    $_SESSION['log_currentCounter'] = $currentCounter;
}

function printCacheWarning()
{
    return '<p class="note">'
         . 'Please note that the change may not be reflected in the API '
         . 'immediately due to caching.<br/>'
         . 'Please refer to the API documentation for more details.</p>';
}


function editVideoData($videoId)
{	
    $httpClient = getAuthSubHttpClient();
    $youTubeService = new Zend_Gdata_YouTube($httpClient);	
   $videoEntryToUpdate = $youTubeService->getFullVideoEntry($videoId);

    if (!$videoEntryToUpdate instanceof Zend_Gdata_YouTube_VideoEntry) {
        print 'ERROR - Could not find a video entry with id ' . $videoId
            . '<br />' . printCacheWarning();
        return;
    }

    try {
        $putUrl = $videoEntryToUpdate->getEditLink()->getHref();
    } catch (Zend_Gdata_App_Exception $e) {
        print 'ERROR - Could not obtain video entry\'s edit link: '
            . $e->getMessage() . '<br />';
        return;
    }

    $videoEntryToUpdate->setVideoTitle("My Test Movie - Private 10000012");
    $videoEntryToUpdate->setVideoDescription("My Test Movie - Private 10000012");
    $videoEntryToUpdate->setVideoPrivate();

    try {
        $updatedEntry = $youTubeService->updateEntry($videoEntryToUpdate, $putUrl);
        if (loggingEnabled()) {
            logMessage($httpClient->getLastRequest(), 'request');
            logMessage($httpClient->getLastResponse()->getBody(), 'response');
        }
    } catch (Zend_Gdata_App_HttpException $httpException) {
        print 'ERROR ' . $httpException->getMessage()
            . ' HTTP details<br /><textarea cols="100" rows="20">'
            . $httpException->getRawResponseBody()
            . '</textarea><br />'
            . '<a href="session_details.php">'
            . 'click here to view details of last request</a><br />';
        return;
    } catch (Zend_Gdata_App_Exception $e) {
        print 'ERROR - Could not post video meta-data: ' . $e->getMessage();
        return;
    }
        print 'Entry updated successfully.<br /><a href="#" onclick="'
            . 'ytVideoApp.presentFeed(\'search_owner\', 5, 0, \'none\'); '
            . 'ytVideoApp.refreshSearchResults();" >'
            . '(refresh your video listing)</a><br />'
            . printCacheWarning();
}


if (!isset($_GET['token'])) {

$returnURL	=	getAuthSubRequestUrl();
echo "<a href=".$returnURL.">Link To Google</a>";

} else {
$singleUseToken = $_GET['token'];
updateAuthSubToken($singleUseToken);

/* editVideoData('mJDRXXaFVGw'); */
}

 

This is how I call the function: http://example.com/youtube_delete_video.php

 

So, what I need basically is to know

1. how can I store the authentication after I verify it from youtube?

2. What function to populate after I store the authentication? <- I couldn't figure where this part is in the documentation.

 

PS: example.com is not a real url. It's just for the sake of writing the post here:)

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.