Apps Script & Oauth2 & Youtube API v3 - google-apps-script

I have This script that lists my favorite videos of youtube using Oauth and the YTB API v2.
Now I would like to do the same with the YTB DATA API V3 and who knows an easy step ahaed is the YTB ANALYTICS API V1.
So I was looking for the URL that would get me to the favorites in V3.
var URL = "https://www.googleapis.com/youtube/v3/"
instead of
//var URL = "http://gdata.youtube.com/feeds/api/users/default/favorites?v=2";
Is that there a way to do it like this with the DATA API v3?
Or is it only possible to reach to the simple data with the long URL request with the API KEY as in the github example of #Arun Nagarajan
var url = 'https://www.googleapis.com/youtube/v3/activities?'
+'part=snippet&channelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&maxResults=20&publishedBefore=2013-02-25T00:00:00.0Z'
+'&key='+API_KEY;
Here is the part of the code that I would like to use with the YTB API v3.
//var URL = "http://gdata.youtube.com/feeds/api/users/default/favorites?v=2"; works
var URL = "https://www.googleapis.com/youtube/v3/" // cant find it
function getFavoriteVideos()
{
var data = UrlFetchApp.fetch(URL, googleOAuth_()).getContentText();
var xmlOutput = Xml.parse(data, false);
var favorites = xmlOutput.getElement().getElements('entry');
Logger.log("a" + favorites.length.toString())
var a = favorites.length.toString()
for(var i = 0; i < favorites.length; i++)
{
favorites[i].getElement('title').getText()
Logger.log(favorites[i].getElement('title').getText())
}
}
The authentication
var NAME = 'youtube';
var SCOPE = 'http://gdata.youtube.com';
function googleOAuth_() {
var oAuthConfig = UrlFetchApp.addOAuthService(NAME);
oAuthConfig.setRequestTokenUrl('https://www.google.com/accounts/OAuthGetRequestToken?scope='+SCOPE);
oAuthConfig.setAuthorizationUrl('https://www.google.com/accounts/OAuthAuthorizeToken');
oAuthConfig.setAccessTokenUrl('https://www.google.com/accounts/OAuthGetAccessToken');
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:NAME, oAuthUseToken:'always'};
}

The problem with utilizing the oAuthConfig class is that it's based on oAuth1 not oAuth2.
There is a request in at Google-Apps-Scirpt-Issues to upgrade to oAuth2:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=2580
I initially forgot to mention there is a posting in SO on using oAuth2 with GAS, Arun, in his response, posted a reference to an example he provides in GitHub: How to authorize with oauth 2.0 from appscript to Google APIs?

Related

Update google contact photo with People API using google apps script

I want to update a contact photo of my contacts using People API and google apps script. official document URL is here https://developers.google.com/people/api/rest/v1/people/updateContactPhoto
My Google Apps script code is below
function imageUpdate(){
var id = 'c6379259805458445151'
var url = 'https://admin.singlaapparels.com/Main/fileurl/64F619B8-C2BE-4EDF-BF9B-01FD60C5D957/4/RakeshKumar.jpg'
var blob = UrlFetchApp.fetch(url).getBlob();
var data = Utilities.base64EncodeWebSafe(blob.getBytes());
var resourceName = 'people/'+id;
Logger.log(data)
var reqBody = {
"photoBytes": data,
"personFields": "photos"
}
var res = People.People.updateContactPhoto(resourceName, reqBody)
Logger.log(res)
}
I got this error: API call to people.people.updateContactPhoto failed with error: Empty response
I change the position of parameters and It works for me.
from
var res = People.People.updateContactPhoto(resourceName, reqBody)
to
var res = People.People.updateContactPhoto(reqBody, resourceName)

Getting Error Daily Limit for Unauthenticated Use Exceeded in Google Sheets for URL Shortener API

I am getting "Error Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup" in google sheets with using URL Shortener API (image as below)
Below is my code in Script Editor
function shortenURL(urlField) {
var toShorten = UrlShortener.newUrl().setLongUrl(urlField);
var shortened = UrlShortener.Url.insert(toShorten);
return shortened.getId();
}
I have bonded to the API through Google Sheets build-in setting from "Cloud Platform Project", enabled URL Shortener API in "Advanced Google Services", enabled it in Google API Console, and created both API and OAuth (image as below). Besides, I was just using it for less than 20 cells in the Google Sheets, and so I am sure it is way less than the quote given by Google.
Cloud Platform Project
Advanced Google Services
Enable in Google API Console
If I use the below code (mentioned here), it works fine.
However, I want the script to run automatically as the function instead of by clicking the button. Therefore, I still want to solve the error.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Shorten")
.addItem("Go !!","rangeShort")
.addToUi()
}
function rangeShort() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
output.push([url.id]);
}
range.offset(0,1).setValues(output);
}
I found some post mentioned the solution to this error is to apply authentication to the requests to Google. However, I have already created API key and OAuth and bond them to Google Sheets through those Google Sheets build-in setting.
Is there any solution to the error?
If the error occurs due to authentication issue, how I can apply the authentication in addition to those setting I have already done?
Try sending a POST request to UrlShortener API endpoint instead of using the UrlShortener service in Apps Script. With UrlShortener.Url.insert(), I quickly hit the usage quota.
Append the API url with the 'key' parameter and set it equal to the API key you obtained from Developer console.
In the body of your POST request, set 'muteHttpExceptions' to 'true' to log all error messages as beautified JSON.
var API_KEY = "YOUR_API_KEY";
function shortenUrl(longUrl) {
var apiEndpoint = "https://www.googleapis.com/urlshortener/v1/url?key=" + API_KEY;
var data = {
"longUrl": longUrl
}
var options = {
"method": "post",
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(data)
};
var response = UrlFetchApp.fetch(apiEndpoint, options).getContentText();
var data = JSON.parse(response);
return data.id;
}

How to pull all user sharing activity using the Activity API inside App Script

I am new to Google API and got training wheels on for the App Script.
I need to know if there is a way to utilize the Activity API or any other inside App Script to pull sharing activity for all domain users.
Thanks in advance.
I got the following working for me but it is not showing me the "shared_externally" in particular, I need to use https://developers.google.com/admin-sdk/reports/v1/reference/activities/list api for all users on drive app, externally and internally shared filter.
function listShares() {
var userKey = 'all';
var applicationName = 'drive';
var optionalArgs = {
visibility: 'shared_externally'
};
var response = AdminReports.Activities.list(userKey, applicationName,
optionalArgs)
Logger.log(response);
}
My output is the same with or without the optionalArgs for shared_externally, can someone help with the proper syntax for the visibility arguments?
Ok I got it to work, yay.
function listShares() {
var userKey = 'all';
var applicationName = 'drive';
var optionalArgs = {
filters: 'visibility==shared_externally'
};
var response = AdminReports.Activities.list(userKey, applicationName,
optionalArgs)
Logger.log(response);}

Authorizing Google Apps Script to access Drive files

The code below works fine for getting my own Google+ user attributes:
// Google oAuth
function getAuth(service, scopes) {
var oAuthConfig = UrlFetchApp.addOAuthService(service);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken? scope="+scopes);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:service, oAuthUseToken:"always"};
}
function test_API_Key() {
var gPlusAuth = getAuth("plus", "https://www.googleapis.com/auth/plus.me");
var url = "https://www.googleapis.com/plus/v1/people/me?key=" + API_KEY;
var httpResponse = UrlFetchApp.fetch(url, gPlusAuth);
Logger.log(httpResponse);
}
When I use the same approach for accessing metadata about files on my Google Drive, I run into the HTTP error, 403, and "access not configured." Below is the code. What am I doing wrong?
function getFileMetaData(fileId) {
var driveAuth = getAuth("drive", "https://www.googleapis.com/auth/drive");
var url = "https://www.googleapis.com/drive/v2/files/" +
documentID + "?key=" + API_KEY;
var response = UrlFetchApp.fetch(url, driveAuth);
Logger.log(response);
}
Taken from google developer site[1]
At a high-level, all apps follow the same basic authorization pattern:
Register the application in the Google Developers Console.
Request that the user grant access to data in their Google account.
If the user consents, your application requests and receives credentials to access the Drive API.
Refresh the credentials (if necessary).
<script type="text/javascript">
var CLIENT_ID = '<YOUR_CLIENT_ID>';
var SCOPES = [
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
// Add other scopes needed by your application.
];
[1] https://developers.google.com/drive/web/about-auth

Google Apps Script: How to share calendar with another user?

I am trying to share google calendars of a user in domain with another user in other domain using google apps script and OAuth authorization. But i am not able to perform this task. I fetched all the calendars events of user but couldn't do the sharing.
Any solution would be appreciated.
Thank You
Solution of this problem is here:
function calenderSharing(user1,user2){
var scope = 'https://www.google.com/calendar/feeds/';
var fetchArgs = googleOAuth_('calenders', scope);
var rawXml= "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007'>"+
"<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/acl/2007#accessRule'/>"+
"<gAcl:scope type='user' value='"+user2+"'></gAcl:scope>"+
"<gAcl:role value='http://schemas.google.com/gCal/2005#owner'> </gAcl:role></entry>"
fetchArgs.method = 'POST';
fetchArgs.payload = rawXml
fetchArgs.contentType = 'application/atom+xml';
try{
var url='https://www.google.com/calendar/feeds/'+user1+'/acl/full'
var urlFetch=UrlFetchApp.fetch(url,fetchArgs) //Giving Permission To personal account as a owner
}
catch(err){
var err1=err.toString()
var ex='Exception: Request failed for returned code 302'
if(ex==err1.split('.')[0]){
var tempCalenderUrl=[]
tempCalenderUrl.id = err1.split('<A HREF="')[1];
tempCalenderUrl.id = tempCalenderUrl.id.split('"')[0];
var url=tempCalenderUrl.id
try{
var urlFetch=UrlFetchApp.fetch(url,fetchArgs)
}
catch(err){}
}
}
}
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey(consumerKey);
oAuthConfig.setConsumerSecret(consumerSecret);
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
In Google Script you can't. The Calendar Script API does not support sharing of calendars (at this time).
Your workaround might be to get the calendar ID using script and using UrlFetch (with OAuth) to call the Google Calendar API https://developers.google.com/google-apps/calendar/v3/reference/. Ensure you authenticate, perform a 'get' to get the calendar based on the ID you retrieved from your script, get the ACL and add a new entry to share with the user outside your domain.
Not an easy solution. Sorry.
Why don't you make an App that would allow this user to simply subscribe to this new calendar instead?
All the necessary tools are in the gas calendar service-
Here is an example of such an application