Youtube api channel selector - youtube-api

Now you can create more than one Youtube channel. In my Android app I need to let user select one of these channels and work with it (get subscription videos, etc..).
I'd like to emulate the official Youtube app where you can choose one of my channels that I have created in my Youtube account.
EDIT:
Finally I solved the problem with the Ibrahim suggestion. In a webview I used the oAuth2 authentication like this:
https://accounts.google.com/o/oauth2/auth?client_id=CLIENT_ID&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/youtube&response_type=code&access_type=offline
Then receive the token to use to get the access_token:
String url = "https://accounts.google.com/o/oauth2/token";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("client_id", YoutubeBase.CLIENT_ID_NUMBER));
nameValuePairs.add(new BasicNameValuePair("client_secret", YoutubeBase.CLIENT_SECRET));
nameValuePairs.add(new BasicNameValuePair("code", code));
nameValuePairs.add(new BasicNameValuePair("redirect_uri", YoutubeBase.REDIRECT_URI));
response = RestClient.postGoogleData(url, nameValuePairs);
And finally use the access_token to call to Youtube Data API:
https://gdata.youtube.com/feeds/api/users/default?v2.1&access_token=" + accesToken
I've used with API v2 but works with v3.

There is no Page selector built-in with the current Android native OAuth2 client. Till that is built, the only workaround is that, doing the web version Oauth2, get the token, and use that token in your requests later on.

Related

Youtube V3 Data API - Channels.list function not fetching all the channels

I am trying to get a list of youtube channels under one google account. But the api returns only one channel, although I have two channels inside my google account. Is there a way to get all the channels under one google account ? Is there any suggested workaround to this ? I have seen posts saying this is not possible, is this same now ?
Thanks
const service = google.youtube({ version: 'v3', headers: { Authorization: Bearer ${user.youtubeToken}}});
const result = service.channels.list({part: 'snippet,contentDetails,statistics', mine: true});

Accessing Twilio MMS images

In Twilio when the ImageMedia URL is given it is accessing the twilio api as follows
https://api.twilio.com/2010-04-01/Accounts/{account sid}/Messages/{message sid}/Media/{media sid}
If you have manually logged into the twilio API that url redirects to the image located at
http://media.twiliocdn.com.s3-website-us-east-1.amazonaws.com/{account sid}/{image id}
How can I get the direct image ID from the twilio API to include in my web app?
I am working with node.js and every time I try to poll the media resources all I receive is the link to the api.twilio.com and not the mdeia.twiliocdn.com
The library doesn't handle this feature that I can find
However, if anyone else comes across the same problem here is the solution
install request.
Then just get NumMedia and MediaUrl parameters...
if(req.body.NumMedia > 0){
var request = require('request')
request.get(req.body.MediaUrl0).auth(config.twilio.sid, config.twilio.auth, false).pipe(fs.createWriteStream("/var/www/app/public/mms/" + sid + '1.jpg' ));
}
Remember that up to 10 images can be sent so you would just need the logic too gather those extra images.

Trouble accessing youtube API via VPN

Youtube is not accessible in my region, I use a VPN (cyberghost VPN) and use it to hit youtube APIs, to be specific this is how im requesting (through .NET client library):
below is my sample code
YouTubeRequestSettings settings = new YouTubeRequestSettings(Config.YoutubeApplicationName, Config.YouTubeDeveloperKey, Config.YouTubeConnectionUserName, Config.YouTubeConnectionPassword);
YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "XXXXXXXXXXXXXX";
newVideo.Tags.Add(new MediaCategory("XXXXXXXXXXX", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "xxxxx";
newVideo.Description = "XXXXXXXXXXXXXXXXXXXXXXXX";
newVideo.YouTubeEntry.Private = true;
FormUploadToken token = request.CreateFormUploadToken(newVideo);
i get an email about "suspicious login attempt" which makes sense...since Im now logging in through a different country, but I thought I would be able to whitelist some IPs and get through...CANT find any such option there!!
question 1:
Is there an option in youtube developer account to whitelist an IP (a set of IPs)?
Question 2:
If its not possible, HOW else do I do it ? (one possible solution seems to be generation of "Application specific password" )?
I'd recommend switching to OAuth 2 instead of ClientLogin. Using OAuth 2, you authenticate once in a browser using your Google Account, authorize access, and then you get back a token that can be reused to make API calls without having to login again.
https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2

Which is the right Youtube Api URL to rate a video with an authenticated user?

I'm doing a Android App and I've done that an user can authenticate with OAuth 2.0 in a Youtube account. But when I try to rate a video which is the right URL to rate it.
I send a POST request with this string:
https://gdata.youtube.com/feeds/api/videos/sxbHyiwYDiw/ratings?value=like&key=my_access_token&v=2
https://gdata.youtube.com/feeds/api/videos/video_id/ratings?value=like_or_dislike&key=my_access_token&v=2
It return this response: "Response contains no content type"
Edit:
I use this link to check it: http://gdata.youtube.com/demo/index.html
I can do this action sending this POST URL: "https://gdata.youtube.com/feeds/api/videos/sxbHyiwYDiw/ratings"
Adding this headers
httppost.setHeader("POST", "/feeds/api/videos/sxbHyiwYDiw/ratings");
httppost.setHeader("GData-Version", "2");
httppost.setHeader("X-GData-Key", "key=*********");
httppost.setHeader("Authorization", "AuthSub token=" + getAccessToken());
httppost.setHeader("Content-Type", "application/atom+xml");
...and adding a xml body
You can check it in the first link: Youtube Demo.

OAuth 2.0 with Google Analytics API v3

I used to be able to query the Google Analytics API with my account's login & password.
Google is now using OAuth for authentication which is great...
The only issue is that I only need ONE access token.
I don't wanna allow other users to fetch THEIR analytics data.
I just wanna be able to fetch MY data.
Is there a way I can generate an access token only for my app or my analytics account?
I know such solutions exists... For instance, Twitter provides what they call a "single-user oauth" for apps that don't require a specific user to sign in.
One again, all I'm trying to accomplish here is to fetch MY OWN analytics data via the API.
Is there a way to properly do that?
I'm adding a PHP answer - you may be able to adjust or convert it to garb / ruby code.
You should be able to use Analytics with service accounts now. You will indeed have to use a private key instead of an access token.
Create an app in the API Console
Basically, you go to the Google API Console and create an App.
Enable Google Analytics in the services tab.
In the API Access tab, create a new OAuth ID (Create another client ID... button), select service account and download your private key (Generate new key... link). You'll have to upload the key to your web server later.
On the API Access page, in the Service account section, copy the email address (#developer.gserviceaccount.com) and add a new user with this email address to your Google Analytics profile. If you do not do this, you'll get some nice errors
Code
Download the latest Google PHP Client off SVN (from the command line svn checkout http://google-api-php-client.googlecode.com/svn/trunk/ google-api-php-client-read-only).
You can now access the Analytics API in code:
require_once 'Google_Client.php';
require_once 'contrib/Google_AnalyticsService.php';
$keyfile = 'dsdfdss0sdfsdsdfsdf44923dfs9023-privatekey.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Your product name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'11122233344#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('11122233344.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:1234';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
Terry Seidler answered this nicely for php. I want to add a java code example.
Api console setup
Start by doing the required steps in the google api console as Terry explained:
Basically, you go to the Google API Console and create an App. Enable
Google Analytics in the services tab. In the API Access tab, create a
new OAuth ID (Create another client ID... button), select service
account and download your private key (Generate new key... link).
You'll have to upload the key to your web server later.
On the API Access page, in the Service account section, copy the email
address (#developer.gserviceaccount.com) and add a new user with this
email address to your Google Analytics profile. If you do not do this,
you'll get some nice errors
Get the necessary libraries
Download the google analytics java client from:
https://developers.google.com/api-client-library/java/apis/analytics/v3
Or add the following maven dependencies:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analytics</artifactId>
<version>v3-rev94-1.18.0-rc</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.18.0-rc</version>
</dependency>
Now for the code:
public class HellowAnalyticsV3Api {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public void analyticsExample() {
// This is the .p12 file you got from the google api console by clicking generate new key
File analyticsKeyFile = new File(<p12FilePath>);
// This is the service account email address that you can find in the api console
String apiEmail = <something#developer.gserviceaccount.com>;
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(apiEmail)
.setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
.setServiceAccountPrivateKeyFromP12File(analyticsPrivateKeyFile).build();
Analytics analyticsService = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(<your application name>)
.build();
String startDate = "2014-01-03";
String endDate = "2014-03-03";
String mertrics = "ga:sessions,ga:timeOnPage";
// Use the analytics object build a query
Get get = analyticsService.data().ga().get(tableId, startDate, endDate, mertrics);
get.setDimensions("ga:city");
get.setFilters("ga:country==Canada");
get.setSort("-ga:sessions");
// Run the query
GaData data = get.execute();
// Do something with the data
if (data.getRows() != null) {
for (List<String> row : data.getRows()) {
System.out.println(row);
}
}
}
You can use a refresh token. Store the refresh token in a db or secure config file, then use it to show the stats.
Google API Offline Access Using OAuth 2.0 Refresh Token will give you an idea of how to capture then store your refresh token.
See also Using OAuth 2.0 for Web Server Applications - Offline Access
Hello I found a solution, it works for me
you have to change this one
immediate: true
to
immediate: false
and it looks like
function checkAuth() {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
}
Google has the 'Service Account' (Calls Google APIs on behalf of your application instead of an end-user), but the way it works is a bit different as it won't use access tokens but a private key instead.
You can find more details at https://developers.google.com/accounts/docs/OAuth2ServiceAccount

Resources