📜 ⬆️ ⬇️

Video upload via YouTube API

Some time ago I had to study and adjust the work of the customer’s site from YouTube, after that, for my startup, as it is now customary to say, I applied almost the same knowledge and skills. In this small post I will tell you how to upload video files using youtube api.

I’ll make a reservation right away that you shouldn’t pay much attention to the code given in the post - it is written specifically for this post and bears more meaning for better understanding. All the code in this PHP dialect :)

The first step is to register you as a regular user on the youtube service. Of course, you can use the existing login-password pair, but it seems to me for convenience that it is better to register a new user, in the channel of which the downloaded video will be broadcast.

Step two begins with a visit to http://code.google.com/apis/youtube/dashboard/ , where we get our Developer Key. On this page you will need to specify the name of your application, the URL of the site from which we will send requests and a description. Having entered the necessary data, the system will generate for us our key, which is a sequence of characters like: AI39si5b05QIsObFU2_BSrPvyO6zC9Eu14BnDzKkhhIqHebS4PqE8o2AKigjP8gCaYTFblB8bpj8CkIWAUMcpc
')
It should be noted that when sending YouTube data, we will include two main parameters of X-GData-Client: <client_id>, where <client_id> is the actual name of the application, and X-GData-Key: key = <developer_key> where it is not hard to guess <developer_key> is the generated key. At this stage, we have finished preparing and begin building the application.

Step three begins with studying the developer documentation ( http://code.google.com/intl/ru/apis/youtube/developers_guide_protocol.html ), understanding the structure of the documentation is very important, because for people who are not familiar with the documentation organization system of Google This may initially seem complicated. Once you understand what is coming from, the problems will disappear.

So, we have some constants that will be used everywhere, these are:

How and where, you will store these constants - I do not know, maybe it will be some configuration files, or constants declared by DEFINE - is not the point, but it is worth noting that this data will be needed always and everywhere, therefore, constant jerking of them database, I think not the best solution.

To start working correctly, we need to get the value of another constant - the authentication token. Google provides two types of authentication: Auth Sub and ClientLogin. The latter method will be considered in the framework of this note - this will allow you to determine the user account associated with subsequent requests, which is why we will need to pass in the subsequent requests login and password.

We need to send data to the URL www.google.com/youtube/accounts/ClientLogin , which will allow us to uniquely identify and provide an authentication token. Below I will give a small piece of code, it is obvious that for those who want to use curl, this code will become more elegant, but I warned at the very beginning that the code is provided for reference only:

$eq = 'accountType=HOSTED_OR_GOOGLE&Email=YOUTUBE_EMAIL&Passwd=YOUTUBE_PASS&service=youtube&source=API_NAME;
if ($fp = fsockopen ("ssl://www.google.com", 443, $errno, $errstr, 20))
{
$request ="POST /youtube/accounts/ClientLogin HTTP/1.0\r\n";
$request.="Host: www.google.com\r\n";
$request.="Content-Type:application/x-www-form-urlencoded\r\n";
$request.="Content-Length: ".strlen($eq)."\r\n";
$request.="\r\n\r\n";
$request.=$eq;
fwrite($fp,$request,strlen($request));
while (!feof($fp))
$response.=fread($fp,8192);
fclose($fp);
}
preg_match("!(.*?)Auth=(.*?)\n!si",$response,$ok);
AUTH_TOKEN = $ok[2];


So, as we now see, we received a positive response from Google, where, among other things, an authentication token was given, which is stored in the AUTH_TOKEN constant. This marker needs to be updated from time to time - I, unfortunately, did not find how long the marker is considered valid, so I get a new crown once an hour, which is later used in work.

Now we are fully ready to work with YouTube.

Step four - download the video. A video download formally consists of two components: sending data and then retrieving the download URL, and the video loading itself. In order to get a unique download URL, where you should actually send our videos, we need to send data to the server that describes the video: name, description, tags, and category.

The main URL where you need to send data for downloading, editing, deleting, receiving the contents of channels and other things else is gdata.youtube.com . All data is transmitted by the POST method. We form a request:

$data = "<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'>
<media:group>
<media:title type='plain'>_</media:title>
<media:description type='plain'>_</media:description>
<media:category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>_</media:category>
<media:keywords>_</media:keywords>
</media:group>
";


And after that we send this request:

if ($fp = fsockopen ("gdata.youtube.com", 80, $errno, $errstr, 20))
{
$request ="POST /action/GetUploadToken HTTP/1.1\r\n";
$request.="Host: gdata.youtube.com\r\n";
$request.="Content-Type: application/atom+xml; charset=UTF-8\r\n";
$request.="Content-Length: ".strlen($data)."\r\n";
$request .="Authorization: GoogleLogin auth=AUTH_TOKEN\r\n";
$request.="X-GData-Client: API_NAME \r\n";
$request.="X-GData-Key: key=API_KEY \r\n";

$request.="\r\n";
$request.=$data."\r\n";
socket_set_timeout($fp, 10);

fputs($fp,$request,strlen($request));
$response = fread($fp,3280);
fclose($fp);


The data received from the server is stored in the $ response variable. The answer will be presented in the form of atom / xml, where we are most interested in two tags: - containing the download URL and containing the loading token. We can get the necessary data, for example:

preg_match("!(.*?)!si",$response, $url);
preg_match("!(.*?)!si",$response, $token);


After that, we may well form a form for downloading videos. It will look like this:
<form action="$url[1]?nexturl=URL_______" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="hidden" name="token" value="$token[1] " />
<input type="submit" value="go" />
</form>



After downloading, if it was successful, the YouTube server will forward the user's browser to the URL_ of our site_where_to transfer_data_after_load_ with the unique code of the YouTube video in the address bar.

Well, actually everything, this time. In this note I intentionally did not touch on the topic of error handling, all this is described in the documentation, or is learned empirically. Next time I will talk about checking uploaded videos, editing and deleting.

Source: https://habr.com/ru/post/69006/


All Articles