Get a playlist entry by ID with YouTube API (PHP)? - youtube

I'm currently in the middle of a project that involves YouTube API. I'm using the Zend Gdata, and everything has gone nicely until this.
I need to get a Zend_Gdata_YouTube_PlaylistListEntry based on the ID of the playlist. I have managed to retrieve the videos with some fiddling:
$feed = $yt->getVideoFeed('http://gdata.youtube.com/feeds/api/playlists/'.$id.'?v=2');
$playlist = new Zend_Gdata_YouTube_PlaylistListEntry($feed->getDOM());
However, I need to use the method $playlist->getPlaylistVideoFeedUrl(), and it returns NULL in this case.
Any help regarding this is appreciated =)

Got it:
$url = 'http://gdata.youtube.com/feeds/api/playlists/'.$input['id'].'?v=2';
$feed = $yt->getPlaylistVideoFeed($url);

Related

Can't get any account info, or review info

I've tried for hours now to figure this out but I'm completely stuck.
I have been approved for My Business APi and I created a service account and downloaded the json file for authentication.
I am using google-api-php-client and with google-api-my-business-php-client which provides the 'Google_Service_MyBusiness' class for use.
My code looks like this: -
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/google-api-my-business-php-client/MyBusiness.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/myfile.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
if (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
// use the application default credentials
$client->useApplicationDefaultCredentials();
} else {
echo missingServiceAccountDetailsWarning();
return;
}
$client->setApplicationName("my_app");
$client->addScope('https://www.googleapis.com/auth/plus.business.manage');
$service = new Google_Service_MyBusiness($client);
$accounts = $service->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();
But all that I ever get back is
Google_Service_Exception: That’s an error. The requested URL <code>/v3/accounts</code> was not found on this server. That’s all we know.
I notice that the documentation is now v4, i.e. v4/accounts, could this be the issue? Are these libraries out of date? How can I retrieve account and review data with v3?
Any help would be appreciated.
My end goal is the retrieve all the reviews for a location but right now just trying to get this to work as a prelude.
Answering my own question - I think the main issue is it turns out that My Business api doesn't support service accounts, you need to use oauth2.
Turns out that V3 is depreciated also so the libray I was using for MyBusiness API is useless, the other one works fine for updating access tokens.
For the reviews I am just using Curl and Simply building the URL with the ?access-token= value on the end of it.
For example to list all reviews
https://mybusiness.googleapis.com/v4/accounts/[acc-number]/locations/[location-id]/reviews?access_token=

How to fetch top 10 channel with youtube api

Hello I'm am now on a project that using YouTube api,
I am bit of stuck on how to fetch top 10 channel of a content owner at YouTube by using their api.
Right now what i am doing is that i need to loop all the channel i had and sort it by their views.
loop {
$analytics = $youtube->reports->query('contentOwner==$content_id', $start_date , $end_date , 'views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration,shares,estimatedRevenue,estimatedAdRevenue,monetizedPlaybacks,adImpressions',array('filters'=> $id ,'max-results'=>$max_result));
}
It is fine but as it need to loop all the channel it takes quite some time. Is there any other way to fetch top 10 channel directly ?
By the way, is there any other way to by pass user consent?
problem solved after i do a lot of try and error,
youtube provide an api explorer for developer to test query parameter right away.
as i explain in the question i had successfully able to fetch/retrieve the data for a channel by using loop.
actually i can just put every channel id with comma to retrieve all the channel i manage.
before PHP example
loop {
$id = 'channel==' . $id;
$analytics = $youtube->reports->query('contentOwner==$content_id', $start_date , $end_date , 'views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration,shares,estimatedRevenue,estimatedAdRevenue,monetizedPlaybacks,adImpressions',array('filters'=> $id ,'max-results'=>$max_result));
}
new or solved php example
$id = 'channel==' . implode(',', $id);
$analytics = $youtube->reports->query('contentOwner==$content_id', $start_date , $end_date,'views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration,shares,estimatedRevenue,estimatedAdRevenue,monetizedPlaybacks,adImpressions',array('filters'=> $id ,'max-results'=>$max_result));
youtube already give the documentation on how to use their api, but i think it is quite hard to understand. Therefore i am able to use the api only when i do alot of try and error.
Thank you.

YouTube API V3 - Get recommended video for new feed

As YouTube official documentation about implement and immigrate to API V3, they said:
YouTube Data API (v2) functionality: Retrieve video recommendations
The v3 API does not retrieve a list that only contains videos recommended for the current API user. However, you can use the v3 API to find recommended videos by calling the activities.list method and setting the home parameter value to true.
But now the parameter home has been deprecated too.
Currently, when I set the home parameter to true, I only retrieve the recently uploaded video in the channel: Popular video in YouTube. There are no video with snippet.type=recommendation at all.
I need to show recommended videos of authenticated user in new feed, but seem like this feature is completely deprecated by YouTube.
Anyone has solution for that?
Thanks first!
Unfortunately, I can't find any documentation or example about this feature. It seems that this has been deprecated. However, you may check this documentation with sample JSON structure that shows the format of a activities resource such as recommendation:
"recommendation": {
"resourceId": {
"kind": string,
"videoId": string,
"channelId": string,
},
Hope this helps!
I found this youtubes search api. All we need to do is put a video id in the relatedToVideoId and it'll giveout a list of videos related to it.
The docs for the api include a way to test the request. code samples there show how to set 'mine' for an authenticated request.
youtube activities
This is android sample code. it would need to be in some background thread. The setmine = true on the channelList response is like the home (I think). Was not sure if your implementation was for the web or an app.
this is android code:
YouTube youtube = new YouTube.Builder(transport, jsonFactory,
credential).setApplicationName(getString(R.string.app_name))
.build();
YouTube.Activities.List activities;
ActivityListResponse activityListResponse = null;
List<ActivityData> activitiesData = new ArrayList<ActivityData>();
try {
/*
* Now that the user is authenticated, the app makes a
* channels list request to get the authenticated user's
* channel. Returned with that data is the playlist id for
* the uploaded videos.
* https://developers.google.com/youtube
* /v3/docs/channels/list
*/
ChannelListResponse clr = youtube.channels().list("contentDetails")
.setMine(true).execute();
activities = youtube.activities().list("id,snippet,subscriberSnippet");
activities.setChannelId(clr.getItems().get(0).getId());
activities.setMaxResults((long) 50);
activityListResponse = activities.execute();
ArrayList<String> subscriptionListIdentifier = new ArrayList<String>()
,listTitles = new ArrayList<String>()
,listThumbnails = new ArrayList<String>();
List<Activity> results = activityListResponse.getItems();
for (Activity activity : results) {
listTitles.add(activity.getSnippet().getTitle());
listThumbnails.add(activity.getSnippet().getThumbnails().getDefault().getUrl());
subscriptionListIdentifier.add(activity.getId());
//if ("public".equals(playlist.getStatus()
// .getPrivacyStatus())) {
ActivityData data = new ActivityData();
data.setActivity(activity);
activitiesData.add(data);
//}
}
return activitiesData;
You can retrieve them using the following API call:
GET https://www.googleapis.com/youtube/v3/activitiespart=snippet%2CcontentDetails&channelId={channel—_Id}&maxResults=25&regionCode=tw&key={YOUR_API_KEY}

Accessing public Instagram content via Instagram API without expiring accesstoken

i want to show public contents from instagram related to a specific hashtag (everything works fine with that) but i can't to renew the access_token everytime it expires.
("do not assume your access_token is valid forever." -
https://www.instagram.com/developer/authentication/)
To renew it manually is not an option i have to make sure there is a valid access_token at ANY time without re-authenticating.
Any ideas or questions? :)
I have one idea, but without API (and access_token). You can make requests to the web-version of Instagram with ?__a=1 parameter. I do not know how long it will work but now there is workflow:
You want to show public content with hashtag space, for example.
Add it to url and add GET-parameter ?__a=1: https://www.instagram.com/explore/tags/space/?__a=1
Make the GET-request. It returns json with nodes in top_posts (8) and media (18). Each node has owner, caption, number of comments and likes. But the most important part is in thumbnail_src and display_src.
There is page_info in media object which helps to paginate results. You need end_cursor (for example, J0HWE9rjAAAAF0HWE9qvgAAAFiYA)
Add the value from end_cursor to the url: https://www.instagram.com/explore/tags/space/?__a=1&max_id=J0HWE9rjAAAAF0HWE9qvgAAAFiYA
Repeat 3-6 to get newest posts with specific hashtag.
Update to the ?__a=1 url param. This appears to have stopped working with users '/account/?__a=1' endpoints.:( Still works on tags apparently.
Instagram shut down their public API. Here's a quick and dirty workaround in PHP:
<?php
function getPublicInfo($username) {
$url = sprintf("https://www.instagram.com/$username");
$content = file_get_contents($url);
$content = explode("window._sharedData = ", $content)[1];
$content = explode(";</script>", $content)[0];
$data = json_decode($content, true);
return $data['entry_data']['ProfilePage'][0];
}
Not sure for how long it's gonna work. Here's one for Javascript.

Retrieving individual videos view count - Youtube API V3.0 - JavaScript

I've been trying to get the view count on videos that I query through the following method:
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
channelId: 'IRRELEVANT',
order: 'date',
maxResults: '25'
});
request.execute(function(response){
YoutubeResponse(response);
});
While the documentation tells me that there's a statistics portion to every video, after the snippet I have __proto__ which I guess means there was an error somewhere? or did the API change? Essentially I need the view count of those 25 most recent videos...
I tried changing part: 'snippet' to part: 'statistics' but got back a code: -32602...
Thanks for the help,
Cheers!
EDIT: Apparently the search.list doesn't have the "statistics" but rather I need to search every video individually... The thing is, when using googles "Try It" feature (https://developers.google.com/youtube/v3/docs/videos/list#try-it) when you ask for the statistics in the "Fields" part at the bottom, it doesn't do anything... So I am VERY confused as to how the heck can I get the view counts & length of all 25 videos (if individually or all at once - preferably-)
The link you gave https://developers.google.com/youtube/v3/docs/videos/list#try-it is working for me.
To get duration and viewCount: Fill in for part: contentDetails,statistics and for id: a comma-separated-list of video-id's like: TruIq5IxuiU,-VoFbH8jTzE,RPNDXrAvAMg,gmQmYc9-zcg
This will create a request as:
GET https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=TruIq5IxuiU,-VoFbH8jTzE,RPNDXrAvAMg,gmQmYc9-zcg&key={YOUR_API_KEY}
Agree with the answer provided by #Als.
But I found a code snippet which might be more convenient for some of you:
function youtube_view_count_shortcode($params)
{
$videoID = $params['id']; // view id here
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?
part=statistics&id=" . $videoID . "&key=xxxxxxxxxxxxxxxxxxxxxxxx");
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return number_format($views);
}
Replace the key value with the google api key for youtube data API and the video id with the youtube video id and Voila you get the total number of views for the youtube video.
Source: https://www.codementor.io/rajharajesuwari/how-to-get-youtube-views-count-aftojpxhj

Resources