YouTube Data API v3 Direct Form Upload - youtube

I had a system setup with the YouTube Data API v2 that would let a user upload a video directly to MY YouTube account via a form on my site (I understand the implications of this, please keep in mind that I am just giving a bare bones description of what the tool did). I have so far been unable to figure out how to setup this same system with the v3 API now that v2 is deprecated. Another quick note, I would like to be able to do this without sending the user to the OAuth page since I have no need to access their YouTube account.
Here is a slimmed down version of PHP code that made this work for v2:
<?php
if ($_GET['op'] == "yt") {
if ($_GET['status'] == "200") {
// video upload was successful, $_GET['id'] contains the YouTube video ID for the upload
} else {
// video upload failed
}
} else {
require_once("Zend/Loader.php");
Zend_Loader::loadClass("Zend_Gdata_ClientLogin");
Zend_Loader::loadClass("Zend_Gdata_YouTube");
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = "YOUTUBE_USERNAME",
$password = "YOUTUBE_PASSWORD",
$service = "youtube",
$client = null,
$source = "My Video Upload Bla Bla Bla",
$loginToken = null,
$loginCaptcha = null,
"https://www.google.com/accounts/ClientLogin"
);
$yt = new Zend_Gdata_YouTube($httpClient, "My Video Upload Bla Bla Bla", "My Video Upload Bla Bla Bla", "YOUTUBE_DEVELOPER_KEY");
$yt->setMajorProtocolVersion(2);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$myVideoEntry->setVideoTitle("Video Title");
$myVideoEntry->setVideoDescription("Video Description");
$myVideoEntry->setVideoCategory("People");
$accessControlElement = new Zend_Gdata_App_Extension_Element("yt:accessControl", "yt", "http://gdata.youtube.com/schemas/2007", "");
$accessControlElement->setExtensionAttributes(array(
array("namespaceUri" => "", "name" => "action", "value" => "list"),
array("namespaceUri" => "", "name" => "permission", "value" => "denied")
));
$myVideoEntry->setExtensionElements(array($accessControlElement));
$tokenArray = $yt->getFormUploadToken($myVideoEntry, "http://gdata.youtube.com/action/GetUploadToken");
$nextUrl = urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}?op=yt");
print "<form action=\"{$tokenArray['url']}?nexturl={$nextUrl}\" method=\"POST\" enctype=\"multipart/form-data\">\n";
print " <input name=\"file\" type=\"file\" />\n";
print " <input name=\"token\" type=\"hidden\" value=\"{$tokenArray['token']}\" />\n";
print " <input value=\"Upload Video File\" type=\"submit\" />\n";
print "</form>\n";
}
?>

I found an excellent article that helped me with this:
http://jasonwritescode.blogspot.com/2013/09/youtube-browser-based-uploading-with.html
A couple of things to point out if you use this article to help you with the same problem. The CURL call to http://gdata.youtube.com/action/GetUploadToken needs to be to HTTPS not HTTP and the form action="{{post_url}}?next={{next_url}} needs to be action="{{post_url}}?nexturl={{next_url}}.

Related

How to get the page Info.totalResults from the youtube api Search: list

Below is the code i have created so far, my goal is to use the youtube Search: list api to find streams for specific games and then publish how many streams there are for that game, I have a database for the game titles and this is my function below, my api link does work im just not able to get the Info.totalResults from it, any help would be great, Thank you for any help you can provide
function totalgamelist() {
global $wpdb;
$gamelistname = $wpdb->prefix . 'Games';
global $wpdb;
$getgames = $wpdb->get_results( 'SELECT * FROM '.$gamelistname , OBJECT );
if (empty($getgames)) {
//empty array
echo 'This is empty sorry!';
} else {
echo 'We Got Something!';
foreach ( $getgames as $getgame )
{
echo '<div class="gamename">'.$getgame->GameTitle;
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=50&q='.$getgame->GameTitle.'&key=[API KEY]");
$json_data = json_decode($JSON, true);
echo $json_data['totalResults'];
echo '</div>';
}
}
}
EDIT:
So with the help from johnh10, i was able to find out that it wasn't my ability to display the results although the echo johnh10 gave is correct :) it was also that my server was blocking access to the url i was asking to view. Below is the curl code i used to access the url, hope it helps others.
$urlgame = 'https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=1&q='.$getgame->GameTitle.'&key=[API Key]';
$ch = curl_init($urlgame);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$json_data = json_decode($data, true);
if (!empty($json_data)) {
$streamnumber = $json_data['pageInfo']['totalResults'];
echo ' Streams:'.$streamnumber;
} else {
echo ' Streams: No Streams Found';
}
echo $json_data['pageInfo']['totalResults'];

Google YouTubeService playlistItems returning non-existent cancelled On Air Hangout items

I am using the standard/sample Google API code for listing the YouTube videos from a channel:
$channelsResponse = $youtube->channels->listChannels("contentDetails", array(
"mine" => "true",
));
foreach ($channelsResponse["items"] as $channel) {
$uploadsListId = $channel["contentDetails"]["relatedPlaylists"]["uploads"];
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems("snippet", array(
"playlistId" => $uploadsListId,
"maxResults" => 50
));
echo "<h3>Videos in list $uploadsListId</h3><ul>";
foreach ($playlistItemsResponse["items"] as $playlistItem) {
echo $playlistItem["snippet"]["title"] . " (" . $playlistItem["snippet"]["resourceId"]["videoId"] . ")<br>";
echo "<img src=" . $playlistItem["snippet"]["thumbnails"]["default"]["url"] . "><br>";
echo "<br><br>";
}
echo "</ul>";
}
However, the list it comes back with is filled with TONS of On Air Hangout events, which I had initiated, but never clicked the "Start Broadcast" button which would have caused them to be saved/archived into my YouTube account. It's almost like, cancelling an "On Air" Hangout before your start the broadcast creates these ghost playlistItems... How can I detect them (and filter them from the list returned by the API call that is displayed?)

how to get list of retweeters using streaming api

Is there a way to get the list of retweeters ids using streaming api
REST api has "GET statuses/:id/retweeted_by/ids" for getting the list of retweeters
Streaming api has a "statuses/retweet", but is not a generally available resources.
So the idea is to use "statuses/filter" and filter based on tweet ids.
Thank you
In the results returned by the streaming API, retweeters (if any) are listed here:
$retweeters = $tweet->{'retweeted_status'}->{'activities'}->{'retweeters'};
Here's a page which shows the ids of retweeters for a stream filtered with a search for the word 'love' — make sure to use your Twitter username and password. Note that the APIs only return the first 100 retweeters.
<html><body>
<?php
echo(str_pad("START<br>",2048));
#ob_flush();
flush();
$opts = array(
'http'=>array(
'method' => "POST",
'content' => 'track=love',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create($opts);
$username = 'your_twitter_username';
$password = 'your_twitter_password';
while (1){
$instream = fopen('http://'.$username.':'.$password.'#stream.twitter.com/1/statuses/filter.json','r' ,false, $context);
while(! feof($instream)) {
if(! ($line = stream_get_line($instream, 20000, "\n"))) {
continue;
}else{
$tweet = json_decode($line);
$retweeters = array();
$retweeters = $tweet->{'retweeted_status'}->{'activities'}->{'retweeters'};
//We store the new post in the database, to be able to read it later
if (sizeof($retweeters) > 0) {
echo("<br><br>");
print_r($retweeters);
}
#ob_flush();
flush();
}
}
}
?>
</html></body>

Retain Access Token in Epi Twitter Oauth

I'm setting up a website using the EPI Twitter Oauth method. I'm able to get a user to login and retrieve their information. However when I refresh the page that has their info, the info is lost. I'm guessing this is to do with the Access Token, and am hoping someone can suggest the easiest way to fix this.
<?php
include 'lib/EpiCurl.php';
include 'lib/EpiOAuth.php';
include 'lib/EpiTwitter.php';
include 'lib/secret.php';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$oauth_token = $_GET['oauth_token'];
if($oauth_token == '')
{
$url = $twitterObj->getAuthorizationUrl();
echo "<div id=\"container\">";
echo "<div id=\"content\">";
echo "<div id=\"holder\">";
echo "</div>";
echo "<div id=\"nav\">";
echo "<a href='$url'><img src=\"signup.jpg\" class=\"linkimage\" /></a>";
echo "</div>";
echo "</div>";
echo "</div>";
}
else
{
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['ot'] = $token->oauth_token;
$_SESSION['ots'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
$username = $twitterInfo->screen_name;
$profilepic = $twitterInfo->profile_image_url;
include 'home.php';
}
if(isset($_POST['submit']))
{
$msg = $_REQUEST['tweet'];
$twitterObj->setToken($_SESSION['ot'], $_SESSION['ots']);
$update_status = $twitterObj->post_statusesUpdate(array('status' => $msg));
$temp = $update_status->response;
echo "<br /><div align='center'>Updated your Timeline Successfully .</div>";
}
?>
It looks to me that you are only checking $_GET for the oauth token. I believe that this may be causing this "lost info" issue because by the time you refresh the page the oauth token has been stored in a session variable and may no longer be stored in the URL. I think you may want to replace the following:
$oauth_token = $_GET['oauth_token'];
with
$oauth_token = empty($_SESSION['ot']) ? $_SESSION['ot'] : $_GET['oauth_token'];

Using basic oauth to send a tweet

I was using basic auth to send tweets from a server every time a song changed. Now they have blocked basic auth and I am not sure how to incorporate it. I have a server at home that updates an html file on the webserver and then calls the following script to tweet out from that file. Any ideas on how to accomplish this simply?
<?php
//====================================================
// CONFIGURATION
//====================================================
// YOUR TWITTER USERNAME AND PASSWORD
$username = '#####';
$password = '#####';
DEFINE(htmlfile, '/homec/public_html/site.com/twitter.html');
$stationURL = "http://www.site.com";
$maxLimit = "139";
$da="";
$f=#fopen(htmlfile, "r");
if ($f!=0)
{
$da=#fread($f, 4096);
fclose($f);
}
else
{
exit;
}
$da=str_replace("\r", "\n", $da);
$da=str_replace("\n\n", "\n", $da);
$d=explode("\n", $da);
$d[0]=trim($d[0], "|"); // title
$d[1]=trim($d[1], "|"); // artist
//====================================================
if ($d[0]=="" || $d[1]=="")
{
// IF WE COULD NOT GRAB THE ARTIST AND
// SONG TITLE FROM THE SAM-GENERATED HTML FILE,
// WE'LL BAIL OUT NOW WITHOUT SUBMITTING ANY TEXT
// TO TWITTER.
exit;
}
else
{
// SUCCESS IN GETTING ARTIST AND TITLE!
// WE'LL PROCEED WITH BUILDING A TEXT STRING TO SUBMIT TO TWITTER.
$message = urlencode('' . $d[1] . ' - ' . $d[0] . ' #bandradio #nowplaying ');
$stationURL = urlencode(' ' . $stationURL);
if ((strlen($message) + strlen($stationURL)) > $maxLimit)
{
// We have to truncate the artist-title string to make room for the station URL string.
$message = substr($message, 0, (($maxLimit - 2) - strlen($stationURL)));
$message .= ".." . $stationURL;
}
else
{
// No need to truncate, it all fits.
$message = $message . $stationURL;
}
} // if ($d[0]=="" || $d[1]=="")
//====================================================
// The twitter API address
$url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
//curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
//curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
$resultArray = curl_getinfo($curl_handle);
curl_close($curl_handle);
Download the latest version of TwitterOAuth from http://github.com/abraham/twitteroauth/downloads Unpack the download and place the twitteroauth.php and OAuth.php files in the same directory as a file with the following code. Register an application at http://dev.twitter.com/apps and from your new apps details page click on "my access token" to get your access token. Fill the four required variables into the script below and you can then run it to post new tweets.
<?php
require_once('twitteroauth.php');
$connection = new TwitterOAuth('app consumer key', 'app consumer secret', 'my access token', 'my access token secret');
$connection->post('statuses/update', array('status' => 'text to be tweeted'));

Resources