YouTube API 3 video fileDetails creationTime - youtube-api

I am trying to get the creation time of a YouTube video in my account using the YouTube API 3. From the API docs (https://developers.google.com/youtube/v3/docs/videos), calling videos->list with the part "fileDetails" should return an element "creationTime":
The date and time when the uploaded video file was created. The value is specified in ISO 8601 format.
I have uploaded a file to YouTube that I know from ffprobe has a "creation_time" tag:
"format": {
"filename": "test.mp4",
"nb_streams": 2,
"format_name": "mov,mp4,m4a,3gp,3g2,mj2",
"format_long_name": "QuickTime / MOV",
"start_time": "0.000000",
"duration": "1.920000",
"size": "1126058",
"bit_rate": "4691908",
"tags": {
"major_brand": "isom",
"minor_version": "0",
"compatible_brands": "isom3gp4",
"creation_time": "2013-06-12 11:08:34"
}
}
which is presumably where YouTube would calculate their "creationTime" value...
However, the YouTube API fileDetails for this file shows:
fileDetails: {
fileSize: "1126058",
fileType: "video",
container: "mov",
videoStreams: [
{
widthPixels: 1280,
heightPixels: 720,
frameRateFps: 29.9167,
aspectRatio: 1.7777777777778,
codec: "h264",
bitrateBps: "5946814",
rotation: "clockwise"
}
],
audioStreams: [
{
channelCount: 2,
codec: "aac",
bitrateBps: "129487"
}
],
durationMs: "1438",
bitrateBps: "6076301",
}
Should the creationTime element not be in the fileDetails part for this video? Do all videos not get this element?
FYI: I am using the php implementation of YouTube API 3 and I have authorized my page to access my account.

It's not 100% guaranteed that file creation time will be available for all videos.
There is also a chance that you may be using older version of the PHP client library.
Try with API explorer to see, if the API returns creation time for your videos.

Related

What is the difference between ContentDetails.RegionRestriction and ContentDetails.CountryRestriction in the Youtube API V3?

Below I have my simple request that retrieves contentDetails for a specific video.
var youTubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "your-apikey",
ApplicationName = "DIGITAL.CLI"
});
var channelsListRequest = new VideosResource.ListRequest(youTubeService, "contentDetails");
channelsListRequest.Id = "FakBv-xNTeU";
var response = channelsListRequest.Execute();
Console.WriteLine(JsonConvert.SerializeObject(response));
In the response I get a list of regions where the video is blocked, but there is also a section that isn't in the response called countryRestrictions.
{
"etag": "8Dlzw_juiiGAkJUxdgfegatGe34",
"items": [
{
"contentDetails": {
"caption": "false",
"contentRating": {},
"definition": "hd",
"dimension": "2d",
"duration": "PT1M37S",
"licensedContent": true,
"projection": "rectangular",
"regionRestriction": {
"blocked": [
"US",
"FM",
"MP",
"VI",
"GU",
"MH",
"PR",
"PW",
"AS",
"UM"
]
}
},
"etag": "-DZJdN2PuXnNfuceW0s7RVa4Y9I",
"id": "FakBv-xNTeU",
"kind": "youtube#video"
}
],
"kind": "youtube#videoListResponse",
"pageInfo": {
"resultsPerPage": 1,
"totalResults": 1
}}
So this video has regionRestrictions, but no country restrictions. Is countryRestrictions still in use? The client library documentation of VideoConntentDetails has the same description for both of them.
And as a bonus question, if the allowed list contains items, then does that mean that all countries not in the allowed list are blocked?
According to the client library documentation of VideoContentDetailsRegionRestriction, this model class is deprecated; thus the client library property regionRestriction is deprecated too.
The client library is mapping its property countryRestriction from the YouTube Data API's property contentDetails.regionRestriction.
According to the official specification of the YouTube Data API's Videos resource, there's no property countryRestriction that this kind of API resource contains.
The answer to your second question is: yes, all countries not in the allowed list are blocked (the emphasis below is mine):
contentDetails.regionRestriction.allowed[] (list)
A list of region codes that identify countries where the video is viewable. If this property is present and a country is not listed in its value, then the video is blocked from appearing in that country. If this property is present and contains an empty list, the video is blocked in all countries.

Youtube API Subscription.ContentDetails.NewItemCount returning zero if querying myself but return different value from Google API Explorer

When using the youtube API to get the list of my subscriptions and all the related details I get a number of information from the snippet and contentDetails part of the response object.
When I call the service from my script the contentDetails.newItemCount always return zero, this should indicate the number of new videos on the channel since last time I've opened the channel. The contentDetails.totalItemCount (total number of videos for the channel) is accurate instead.
In contrast if I run the same query through the google api explorer, the same variable contains the correct information and not zero.
The call I make from my PHP script is exactly the same as the one run on the google api explorer so I can't explain or understand why I'm getting different results. The code I use is roughly the following
$this->_youtube = new Google_Service_YouTube($this->_connector->_googleClient);
$params = array('mine' => true,'maxResults'=>25,'order'=>'alphabetical');
$part = 'snippet,contentDetails';
$response = $this->_youtube->subscriptions->listSubscriptions(
$part,
$params
);
foreach ($response['items'] as $item) {
$this->_mysubscriptions[] = array(
'channelId'=>$item['snippet']['resourceId']['channelId'],
'title'=>$item['snippet']['title'],
'description'=>$item['snippet']['description'],
'thumb_default'=>$item['snippet']['thumbnails']['default']['url'],
'thumb_medium'=>$item['snippet']['thumbnails']['medium']['url'],
'thumb_high'=>$item['snippet']['thumbnails']['high']['url'],
'subscribedOn'=>$this->cleanDate($item['snippet']['publishedAt']),
'totalVideos'=>$item['contentDetails']['totalItemCount'],
'newVideos'=>$item['contentDetails']['newItemCount']);
}
This is how the object returned looks like (just removed few IDs from the response) from the google API explorer, while when I run it through my code I get the same data but the newItemCount is zero.
{
"kind": "youtube#subscription",
"snippet": {
"publishedAt": "2016-09-14T12:48:00.000Z",
"title": "Muselk",
"description": "\"Memes win games\" - Youtube.com/mrmuselk",
"resourceId": {
"kind": "youtube#channel",
"channelId": "UCd534c_ehOvrLVL2v7Nl61w"
},
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/-iWlz7dePNz0/AAAAAAAAAAI/AAAAAAAAAAA/smtPKh-RLTU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"medium": {
"url": "https://yt3.ggpht.com/-iWlz7dePNz0/AAAAAAAAAAI/AAAAAAAAAAA/smtPKh-RLTU/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"high": {
"url": "https://yt3.ggpht.com/-iWlz7dePNz0/AAAAAAAAAAI/AAAAAAAAAAA/smtPKh-RLTU/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
}
}
},
"contentDetails": {
"totalItemCount": 792,
"newItemCount": 4,
"activityType": "all"
}
I've looked through the revision history but can't find any reference of modifications made to this specific property of the contentDetails object
There is a bug filed with google on this property but it refers to a different behaviour.
Wondering if this happens to other as well, or if somebody can give some hints on how this works or don't.

How can I get a Youtube video ID from the Youtube API given the video url?

I have a page where users can paste a Youtube video url and then I need to extract the video's ID in order to get the video's thumbnail image. The hard part is to get a reliable way of extracting the video ID from the video url. There are a number of regex solutions here but for me none of these are 100% reliable. Here's a few:
JavaScript REGEX: How do I get the YouTube video id from a URL?
Youtube API - Extract video ID
It's like a contest of who has a longer regex. I feel like the right way would be to get this information from Youtube's api, but looking at it, seems like this option is not available:
https://developers.google.com/apis-explorer/#p/youtube/v3/
As you can see everything is based on the video id. I find it ridiculous that I need the actual video ID to get any information about the video since no real world user will ever even know what the video id is. Vimeo has this feature built into their API. Here is an example:
https://vimeo.com/api/oembed.json?url=https://vimeo.com/29474908
Does anyone have a solution for this that does not involve some regular expression?
Doing a search with the API works with different YouTube URL types. The URL is passed as the query term q.
https://www.googleapis.com/youtube/v3/search/?key=<YOUR_KEY>&part=snippet&q=youtu.be/M7lc1UVf-VE
Maybe some case could result in more than one item, but the normal search result is just one match:
{
kind: "youtube#searchListResponse",
etag: ""m2yskBQFythfE4irbTIeOgYYfBU/j2Px-5q--mgJEsrfjg4L0Mgn_L8"",
regionCode: "ES",
pageInfo: {
totalResults: 1,
resultsPerPage: 5
},
items: [
{
kind: "youtube#searchResult",
etag: ""m2yskBQFythfE4irbTIeOgYYfBU/_1gFVi_i_djlS4OZWPGtcZ3iSLQ"",
id: {
kind: "youtube#video",
videoId: "M7lc1UVf-VE"
},
snippet: {
publishedAt: "2013-04-10T17:25:04.000Z",
channelId: "UC_x5XG1OV2P6uZZ5FSM9Ttw",
title: "YouTube Developers Live: Embedded Web Player Customization",
description: "On this week's show, Jeff Posnick covers everything you need to know about using player parameters to customize the YouTube iframe-embedded player.",
thumbnails: {
default: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/default.jpg",
width: 120,
height: 90
},
medium: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/mqdefault.jpg",
width: 320,
height: 180
},
high: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/hqdefault.jpg",
width: 480,
height: 360
}
},
channelTitle: "Google Developers",
liveBroadcastContent: "none"
}
}
]
}
I tested with some of the URL variations from this answer and most worked:
var urls = [
'//www.youtube-nocookie.com/embed/M7lc1UVf-VE?rel=0',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'https://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I', // <---- invalid
'https://youtu.be/M7lc1UVf-VE',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtu.be',
'https://youtu.be/M7lc1UVf-VE',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'https://www.youtube.com/ytscreeningroom?v=M7lc1UVf-VE', // <---- invalid
'https://www.youtube.com/embed/M7lc1UVf-VE?rel=0',
'https://www.youtube.com/watch?v=M7lc1UVf-VE',
'https://youtube.com/v/M7lc1UVf-VE?feature=youtube_gdata_player',
'https://youtube.com/vi/M7lc1UVf-VE?feature=youtube_gdata_player', // <---- invalid
'https://youtube.com/?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtube.com/?vi=M7lc1UVf-VE&feature=youtube_gdata_player', // <---- invalid
'https://youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtube.com/watch?vi=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtu.be/M7lc1UVf-VE?feature=youtube_gdata_player'
];
var my_key = '<YOUR_KEY>';
function getUri(uri){
$.get('https://www.googleapis.com/youtube/v3/search/?key='+my_key+'&part=snippet&q='+uri, function(data) {
if(data.items.length !== 0)
console.log(data.items[0].snippet.publishedAt);
else
console.warn('no items for',uri)
});
}
for (i = 0; i < urls.length; ++i) {
getUri(urls[i]);
}

get video id from youtube playlist in as3

How to get video id from youtube playlist in as3, in order to play latest uploaded video from you tube playlist.
I have load pLay List and it plays properly but I want to play only latest video from play list.
Thank you
You can use the Youtube Data API to fetch information about the items in a playlist.
In order to be able to use the API, you need to generate an API key. Info about how to do so can be found here.
To get the latest video in a certain playlist you can make a GET request for this URL:
https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=1&playlistId={YOUR_PLAYLIST_ID}&key={YOUR_API_KEY}
Let's break it down to see what it does:
https://www.googleapis.com/youtube/v3/playlistItems - This is the URL endpoint to request data about playlist items in the Youtube Data API
?part=contentDetails - We define what details we want returned from the query. In this case we want the video id's, so we use contentDetails
&maxResults=1 - We are only interested in one item - the latest. (It appears that the result is ordered from latest to oldest, so by only requesting the first video it should return the latest.)
&playlistId={YOUR_PLAYLIST_ID} - Replace this value with the ID of the playlist in question.
&key={YOUR_API_KEY} - Replace this value with your API key.
Let's look at a sample request:
var playlistUrl:String = "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=1&playlistId=PL4Sz7_l-PtwAG8xye4Y9whykc4OAwbN9f&key={YOUR_API_KEY}"
var playlistReq:URLRequest = new URLRequest(playlistUrl);
var playlistLoader:URLLoader = new URLLoader();
playlistLoader.addEventListener(Event.COMPLETE, handlePlaylistUrlLoaded);
playlistLoader.load(playlistReq);
function handlePlaylistUrlLoaded(e:Event):void {
trace(playlistLoader.data); // See the response below
var playlistResponse:Object = JSON.parse(playlistLoader.data); // Parse the JSON response
trace(playlistResponse.items[0].contentDetails.videoId); // Prints "21Ox58OKFmo" which is the video id of the latest video in this playlist
}
The raw response to this sample query is:
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"FOuwADrXJjsTKgUIQJoQC6nKNFY/n3kL7MtTJyPOfHU6jmro9gAC1CI\"",
"nextPageToken": "CAEQAA",
"pageInfo": {
"totalResults": 189,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"FOuwADrXJjsTKgUIQJoQC6nKNFY/aNpryIHyioAUu4C9_WVP8kZGbuE\"",
"id": "PL88DYY_1F2muJ4Dv0iAFHEuKQuma2y_BH0WbF7AzESJw",
"contentDetails": {
"videoId": "21Ox58OKFmo"
}
}
]
}
Edit in response to further details
If you want to use the YouTube player API, it seems like you have to wait for a "video cued" event after adding the playlist to the cue.
So, in essence, this should work (untested code):
youtubePlayer.addEventListener("onStateChange", onPlayerStateChange);
youtubePlayer.cuePlaylist("{YOUTUBE_PLAYLIST_ID}");
function onPlayerStateChange(event:Event):void {
if (Object(event).data == YT.PlayerState.CUED) {
// Playlist cued, the playlist data should now be accessible
var playlist:Array = youtubePlayer.getPlaylist();
trace(playlist[0]); // This value should now exist
}
}

Get daily view counts for all video of a given channel on Youtube Analytics

I'm trying to use the Youtube Analytics API to gather daily view counts for all the videos in my channel. It seems like the video dimension throttles the result at top 10 only. Is there anyway I could get daily view count for all my videos?
At the moment you cannot get metrics for all videos via Analytics API directly. First you need to fetch the ids of all your videos and then request Analytic's data for each. I managed it this way:
Get the playlist ID for your uploaded videos via Data API https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true&maxResults=25&access_token=[TOKEN]. Gives you this result:
{
"kind": "youtube#channelListResponse",
"etag": "\"F9iA7pnxqNgrkOutjQAa9F2k8HY/SAGx1pv6myGXge51dmywGW81h8o\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"F9iA7pnxqNgrkOutjQAa9F2k8HY/g5zJtodBJms3CAfwF_ar2nVgJjU\"",
"id": "[id]",
"contentDetails": {
"relatedPlaylists": {
"likes": "[id]",
"favorites": "[id]",
"uploads": "[id]",
"watchHistory": "[id]",
"watchLater": "[id]"
},
"googlePlusUserId": "[id]"
}
}
]
}
Get all ids of your uploaded videos with the upload playlist id via Data API: https://www.googleapis.com/youtube/v3/playlistItems?part=id&pageToken=&playlistId=[UPLOADID]&maxResults=50&access_token=[TOKEN]. Note: You have to page through the results with nextPageToken.
With the collected video ids you can make a batch request to the Analytics API https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel==mine&start-date=2014-12-29&end-date=2015-01-05&metrics=views,likes&dimensions=video,day&filters=video==[videoId],[videoId],[videoId],[...]&sort=video&access_token=[TOKEN] Note: You can batch up to 200 Video Ids.

Resources