Here's a little action I wrote recently, to automatically populate a specific YouTube playlist as new videos are being posted to a Drupal site, using modules Trigger or Rules. The same concept can also be used retroactively on existing content, using Views Bulk Operations: select all existing video nodes and apply the action to them. The action avoids adding the same video more than once.
To run this code, you will need to put the Zend Gdata library somewhere in your PHP include_path.
<?php
function module_hook_info() {
return array(
'add_youtube_playlist' => array(
'type' => 'node',
'description' => t('Add video to YouTube "XYZ" playlist'),
'configurable' => FALSE,
),
);
}
function add_youtube_playlist($node, $context) {
if ($node->type != 'video_ad' || !isset($node->field_embed_video[0]) || $node->field_embed_video[0]['provider'] != 'youtube') return;
$video_id = $node->field_embed_video[0]['value'];
static $playlist = NULL;
require_once('Zend/Gdata/ClientLogin.php');
require_once('Zend/Gdata/YouTube.php');
$authenticationUrl = 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
YOUTUBE_USERNAME,
YOUTUBE_PASSWORD,
'youtube',
NULL,
YOUR_APPLICATION_NAME,
NULL,
NULL,
$authenticationUrl
);
$yt = new Zend_Gdata_YouTube($httpClient, YOUR_APPLICATION_NAME, YOUR_APPLICATION_NAME, YOUTUBE_DEVELOPER_KEY);
$postUrl = 'http://gdata.youtube.com/feeds/api/playlists/' . YOUTUBE_PLAYLIST_ID;
// Check in playlist
if (!is_array($playlist)) {
$playlist = array();
set_time_limit(0);
$playlistVideoFeed = $yt->getPlaylistVideoFeed($postUrl);
$playlistVideoFeed = $yt->retrieveAllEntriesForFeed($playlistVideoFeed);
foreach ($playlistVideoFeed as $playlistVideoEntry) {
$parsedUrl = parse_url($playlistVideoEntry->getVideoWatchPageUrl());
parse_str($parsedUrl['query'], $parsedQuery);
$playlist[] = $parsedQuery['v'];
}
}
if (in_array($video_id, $playlist)) return;
// Add to playlist
try {
$videoEntryToAdd = $yt->getVideoEntry($video_id);
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());
$yt->insertEntry($newPlaylistListEntry, $postUrl);
$playlist[] = $video_id;
}
catch (Exception $e) {
watchdog(YOUR_APPLICATION_NAME, 'Could not add video %vid to playlist: %error.',
array('%vid' => $video_id, '%error' => $e->getMessage()),
WATCHDOG_ERROR
);
}
}
?>Assumptions:
video_ad.field_embed_video.Exercises to the reader:
Comments
Flickr
Cool! I did something similar with Flickr's API recently. I didn't go the actions and triggers route, though it wouldn't be hard to integrate some of this with the custom module I wrote - check it! http://drupal.org/project/flickr_imagefield