YouTube PHP API - Getting status of previously uploaded video? - php

Just started digging into the YouTube PHP API and got the browser-based Zend upload script working. However, I can't find any documentation on how to retrieve the status of the video after it's been uploaded. The main reason I would need this is for error handling - I need to be able to know whether the video was approved by YouTube, since someone could technically upload an image or a file too large. I need to know that the vid was approved so that I know what message to display the end user when they return to the site (ie 'Your video is live' or 'Video upload failed').
The YouTube PHP browser-based upload returns a URL parameter status of 200 even if the format or size is incorrect, which is of course not helpful. Any ideas on how else to get this info from the YT object?
All in all, when a user returns to the site, I want to be able to create a YT object based on their specific video ID, and want to be able to confirm that it was not rejected. I'm using ClientLogin to initiate the YouTube obj:
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
Any thoughts?

Whew, finally found the answer to this after searching around and piecing together code for the last few days. After you create the $yt object, use the following to check the status:
$yt->setMajorProtocolVersion(2);
$youtubeEntry = $yt->getVideoEntry('YOUR_YOUTUBE_VID_ID', null, true);
if ($youtubeEntry->getControl()){
$control = $youtubeEntry->getControl();
$state = $control->getState()->getName();
}
Echoing out $state displays the string 'failed' if the video was not approved for whatever reason. Otherwise it's empty, which means it was approved and is good to go (Guessing the other state names would be: processing, rejected, failed, restricted, as Mient-jan Stelling suggested above).
Crazy how tough this answer was to put together for first-time YouTube API'ers. Solved! (Pats self on back)

Do you have a CallToken if so its pretty easy.
For this example i use Zend_Gdata_Youtube with Zend AuthSub.
WHen uploading your video you had a CallToken, With this call token you can access the status of the video.
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$youtube = new Zend_Gdata_YouTube( $httpClient, '', NULL, YOUTUBE_DEVELOPER_KEY );
$youtubeEntry = $youtube->getFullVideoEntry( 'ID_OF_YOUTUBE_MOVIE' );
// its the 11 digit id all youtube video's have
in $youtubeEntry all your data about the video is present
$state = $youtubeEntry->getVideoState();
if state is null then your video is available else make of state a string like this.
(string) $state->getName();
There are about 4 important state names. ( processing, rejected, failed, restricted)

Related

PHP: media posting on twitter?

I've been trying to post an image with a simple message onto twitter using PHP and twitteroauth.php.
However, every time I run my code, I only get the $tweetMessage published on the twitter feed without any image.
I searched and searched and read their own documentation but don't even get me started on their own documentation! its like someone who's had a sleepwalk was writing their documentation. Just a bunch of jargon..
And most of the information on STO is either outdated or pointing to a library!
I do not want to use any library as I will have to try to learn someone else's code as well and Surely twitter would allow publishing photo's using their own API without the use of any third party Library?!
Any way, This is my full code:
// Include twitteroauth
require_once('inc/twitteroauth.php');
// Set keys
$consumerKey = 'xxxxxxxxxxxxxxxxxxx';
$consumerSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessTokenSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// Create object
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
// Set status message
$tweetMessage = 'This is a tweet to my Twitter account via PHP.';
$image_path="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
$handle = fopen($image_path,'rb');
$image = fread($handle,filesize($image_path));
fclose($handle);
// Check for 140 characters
if(strlen($tweetMessage) <= 140)
{
// Post the status message
$tweet->post('statuses/update', array('media[]' => "{$image};type=image/jpeg;filename={$image_path}", 'status' => $tweetMessage));
}
Could someone please advise on this issue?
Thanks in advance.
EDIT:
I've changed my code to the following and I get this error:
{"errors":[{"code":195,"message":"Missing or invalid url parameter."}]}
But I'm sure the image is on the specified URL/directory!
This is the code:
require_once 'inc/twitteroauth.php';
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('images/sign-in-with-twitter-l.png');
$image = 'images/sign-in-with-twitter-l.png';
$status_message = 'Attaching an image to a tweet';
$status = $connection->post('statuses/update_with_media', array('status' => $status_message, 'media[]' => file_get_contents($image)));
echo json_encode($status);
Any idea why this error is being shown?
Uploading media to Twitter is slightly complicated. Essentially, it's a three stage process.
Upload the photo to Twitter.
Receive a media_id back from Twitter.
Post your status and media_id to Twitter.
This is described in great detail at https://dev.twitter.com/rest/reference/post/media/upload
Generally speaking, it is easier for use to use a library like CodeBird as they've already done the hard work of finding all the edge cases.
But, assuming you don't want to do that...
POST the image to /1.1/media/upload.json
Receive back some JSON like
{
"media_id": 553656900508606464,
"media_id_string": "553656900508606464",
"size": 998865,
"image": {
"w": 2234,
"h": 1873,
"image_type": "image/jpeg"
}
}
* Use that media_id_string when you post the status. e.g.
tweet->post('statuses/update', array('media_ids' => $media_id_string, 'status' => $tweetMessage));
Hopefully that gives you enough to understand what's going on.
I solved it like this:
$tweet_img = 'Path/to/image';
$handle = fopen($tweet_img,'rb');
$image = fread($handle,filesize($tweet_img));
fclose($handle);
$parameters = array('media[]' => "{$image};type=image/jpeg;filename={$tweet_img}",'status' => 'Picture time');
$returnT = $connection->post('statuses/update_with_media', $parameters, true);
Horrible twitter API documentation needs improving!! it needs to be written by humans as opposed to a bunch of sleepwalking zombies!!!
This is a very frustrating situation that they put us in when we try to use their API...
They either need stop their API support and remove it all from the public or simply improve their documentation and write it for the public and not just for their own use using jargon words.
Any way, the above code works just fine using the latest twitteroauth
I hope this helps others in my situation.
I feel like i wasted 5 hours for something that should be clear and mentioned in plain English on their site!!!
Rant and Answer over & good luck.. :)

How can auto post to google plus in PHP?

I find article about Post on Google Plus on
https://developers.google.com/+/api/latest/moments/insert
From that we find example shows how to create moment.
$moment_body = new Google_Moment();
$moment_body->setType("http://schemas.google.com/AddActivity");
$item_scope = new Google_ItemScope();
$item_scope->setId("target-id-1");
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The Google+ Platform");
$item_scope->setDescription("A page that describes just how awesome Google+ is!");
$item_scope->setImage("https://developers.google.com/+/plugins/snippet/examples/thing.png");
$moment_body->setTarget($item_scope);
$momentResult = $plus->moments->insert('me', 'vault', $moment_body);
From Google APIs Client Library for PHP i'm not find api about Google_ItemScope, and Google_Moment is Google_PlusMomentsService.php. So can not try this example.
Anybody know about this? Or have solution can me try auto post on google plus using PHP?
Thanks
i also found same problem, in new google + api they change class name try below code
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId('12345');
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("yout site/api name");
$item_scope->setDescription("A page that describes just how html work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);

upgrading twitter api 1 to current version

I am not a hardcore coder but i have small knowledge i have attempted to fix this error we are getting regarding the Twitter api
there is a line of code that checks that a twitter name is currect which is sent via a form
$url = get_data("http://api.twitter.com/1/users/lookup.json?screen_name=".$name);
$xml = json_decode($url, true);
$id = $xml[0]['id'];
$av = $xml[0]['profile_image_url'];
if ($id != "")
What i understand
I understand that this version of twitter is no longer available and i need to update it to 1.1
What searching and research i have done
I have Searched the net for a quick answer for this but was not able to find any....
I have found this code https://github.com/abraham/twitteroauth/tree/master/twitteroauth
My question
How do i adapt the files to work within this file? i didnt post the whole code within the page as im not sure all of it is relevant.
Just use the 1.1 in the URL. That will do
http://api.twitter.com/1.1/users/lookup.json
-------^
Do like this...
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN,OAUTH_SECRET);
$account = $connection->get('account/verify_credentials');
$status = $connection->post('statuses/update', array('status' => 'Text of status here', 'in_reply_to_status_id' => 123456));
$status = $connection->delete('statuses/destroy/12345');
Documentation

Can you set a YouTube video's license to CreativeCommons via the PHP 3.0 API?

You're supposed to be able to do this, through something like this:
$snippet = new Google_VideoSnippet();
$snippet->setTitle("some title");
$snippet->setDescription("some description);
...
$status = new Google_VideoStatus();
$status->setPrivacyStatus("public");
$status->setLicense("creativeCommon");
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
and so on. Yes, you'd think that the value for setLicense would be "creativeCommons", but it's not (https://developers.google.com/youtube/v3/docs/videos#resource). Using "creativeCommons" or anything other than "youtube" and "creativeCommon" results in a "(500) Bad Request" response.
But the real problem is that, for me anyway, once the video gets up to YouTube (which it is doing), I get a YouTube license regardless of whether I've specified "youtube" or "creativeCommon". So: is this supposed to work / am I doing it wrong / are there any ideas out there?
Not sure if this helps anyone but (a few years later) it seems to work to set the licencetype to creativeCommon using the javascript-version of the api (v3).
UploadVideo.prototype.uploadFile = function(file) {
var metadata = {
status: {
privacyStatus: $('#privacy-status option:selected').text(),
license: "creativeCommon"
}
};

How to get the id of the latest uploaded video in a youtube channel

In youtube
How do i get the id of the latest uploaded video (the one that comes in the url like v=....) of a channel to which Im subscribed, for embeded
im using php in my server side
As of April 20, 2015, it looks like the answer mentioned above may no longer work. Here's an example using a YouTube Channel ID (can be found in the source of a Channel page.)
<?php
$id = NULL;
$channel_id = 'someChannelID';
$xml = simplexml_load_file(sprintf('https://www.youtube.com/feeds/videos.xml?channel_id=%s', $channel_id));
if (!empty($xml->entry[0]->children('yt', true)->videoId[0])){
$id = $xml->entry[0]->children('yt', true)->videoId[0];
}
echo $id; // Outputs the video ID.
Here's a example using the YouTube RSS feeds, simplexml_load_file, parse_url, and parse_str.
<?php
$id = NULL;
$username = 'YouTube';
$xml = simplexml_load_file(sprintf('http://gdata.youtube.com/feeds/base/users/%s/uploads?alt=rss&v=2&orderby=published', $username));
if ( ! empty($xml->channel->item[0]->link) )
{
parse_str(parse_url($xml->channel->item[0]->link, PHP_URL_QUERY), $url_query);
if ( ! empty($url_query['v']) )
$id = $url_query['v'];
}
echo $id; // Outputs the video ID.
Here's how to do it via the YouTube API once you set up your API Key.
<?php
$channel_id = 'someChannelId';
$api_key = 'yourAPIKey';
$json_url="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=".$channel_id."&key=".$api_key;
$json = file_get_contents($json_url);
$listFromYouTube=json_decode($json);
$id = $listFromYouTube->items[0]->snippet->resourceId->videoId;
echo $id; // Outputs the video ID.
Generating your API Key:
Goto - https://console.developers.google.com
Create a new project
Select "APIs & auth"
Select "APIs"
Select "Youtube Data API v3" and enable it
Select "Credentials"
Create new Key, select browser and then press create (don't enter
anything in the text box)
Same here as with Greg Brendel. YT did make some changes: "As we upgrade the YouTube Data API to bring more features, we’ll begin shutting down the old version on April 20, 2015. This will result in the current YouTube app not working on certain device models from 2012 and older."
https://support.google.com/youtube/answer/6098135?p=yt_devicesupport&hl=en&rd=1

Categories