Google Drive API push notifications can't be stopped / cancelled - google-drive-api

I am watching a Drive resource. Setting up the watch (using the googleapis 0.2.13-alpha client with node.js and drive.file.watch):
exports.subscribeDriveCallbacksCmd = function( user, fileId ){
var userId = user.id;
var baseUrl = exports.BASE_URL;
var subscribeUrl = baseUrl+"/incoming/file";
var watchId = 'id-'+fileId+'-'+(new Date()).getTime();
var subscription = {
id: watchId,
token: userId+':'+fileId,
type: 'web_hook',
address: subscribeUrl,
params:{
ttl: 600
}
};
var params = {
fileId: fileId
};
//var cmd = client.drive.files.watch( params, subscription );
// FIXME - Hack around bug in RPC implememntation
var hack = {channel:subscription};
for( var key in params ){
hack[key] = params[key];
}
var cmd = client.drive.files.watch( hack );
return cmd;
};
var cmd = exports.subscribeDriveCallbacksCmd( user, '0ZZuoVaqdWGhpUk9PZZ' );
var batch = client.newBatchRequest();
batch.add(cmd);
batch.withAuthClient(user.auth).execute(cb);
After this, I'm getting a response of
{ kind: 'api#channel',
id: 'id-0ZZuoVaqdWGhpUk9PZZ-1374536746592',
resourceId: 'WT6g4bx-4or2kPWsL53z7YxZZZZ',
resourceUri: 'https://www.googleapis.com/drive/v2/files/0AHuoVaqdWGhpUkZZZZ?updateViewedDate=false&alt=json',
token: '101852559274654726533:0ZZuoVaqdWGhpUk9PZZ',
expiration: '1374537347934' }
and a sync callback with the following headers
'x-goog-channel-id': 'id-0ZZuoVaqdWGhpUk9PZZ-1374536746592',
'x-goog-channel-expiration': 'Mon, 22 Jul 2013 23:55:47 GMT',
'x-goog-resource-state': 'sync',
'x-goog-message-number': '1',
'x-goog-resource-id': 'WT6g4bx-4or2kPWsL53z7YxZZZZ',
'x-goog-resource-uri': 'https://www.googleapis.com/drive/v2/files/0AHuoVaqdWGhpUkZZZZ?updateViewedDate=false&alt=json',
'x-goog-channel-token': '101852559274654726533:0ZZuoVaqdWGhpUk9PZZ',
'user-agent': 'APIs-Google; (+http://code.google.com/apis)
There are several problems with this, however:
The resource-id returned by both of these do not match the fileId passed when I subscribed to the watch. It does match the ID given in the resource-uri
Trying to use either the resourceID returned here, or the fileId passed when I subscribed, returns an error when I try to stop the channel.
The error given for drive.channel.stop varies depending on how I do the call. If I use the API Explorer at the bottom of the Channel: Stop page, providing either the resourceId or the fileId for the resourceId parameter, I get
404 Not Found
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Channel not found"
}
],
"code": 404,
"message": "Channel not found"
}
}
If I use the node.js library with this code:
exports.cancelDriveCallbacksCmd = function( watchId, fileId, resourceId ){
var body = {
id: watchId,
resourceId: resourceId
};
var cmd = client.drive.channels.stop( body );
return cmd;
};
var cmd = exports.cancelDriveCallbacksCmd( 'id-0ZZuoVaqdWGhpUk9PZZ-1374536746592', '0ZZuoVaqdWGhpUk9PZZ', 'WT6g4bx-4or2kPWsL53z7YxZZZZ' );
var batch = client.newBatchRequest();
batch.add(cmd);
batch.withAuthClient(user.auth).execute(cb);
I get the error
{ code: 500,
message: 'Internal Error',
data:
[ { domain: 'global',
reason: 'internalError',
message: 'Internal Error' } ] }
which I suspected was related to Bug 59 which has a workaround (which was the hack code I was using above) but should have the fix in place sometime this week, I understand.
So I changed it to this code, which worked around the bug for files.watch:
exports.cancelDriveCallbacksCmd = function( watchId, fileId, resourceId ){
var params = {};
var body = {
id: watchId,
resourceId: resourceId,
fileId: fileId
};
//var cmd = client.drive.channels.stop( params, body );
// FIXME - hack around bug in RPC implementation
var hack = {channel:body};
for( var key in params ){
hack[key] = params[key];
}
var cmd = client.drive.channels.stop( hack );
console.log( 'cancelDriveCallbacksCmd', hack );
return cmd;
};
But I get the same 500 error.
Any thoughts about what I might be doing wrong or how to even go about debugging where I might be going wrong with it?

Push notification is designed to watch any api resource, although it only supports Changes and Files for now. Thus, it needs unique resourceId for all resource type. That is the reason why they have resourceId that is not equal to fileId.
Confirmations do come back with info about which file it is watching. Check header of your response. Also, you can make use of token to save channel specific information if you want.
If you are using API explorer, you cannot unsubscribe from the channel because as you know, push notification requires additional verification of url through apis console and apis explorer is not authenticated to access your notification. It is working as intended by security reason. I will report about this issue to stop people from getting confused with this.
fileId doesn't go to request body. It should be one of the parameters. Also, you should make request to Channels.stop() to unsubscribe. Something like this:
Code to subscribe:
var channel= {
'id': 'yourchannelid',
'type': 'web_hook',
'address': 'https://notification.endpoint'
};
var request = client.drive.files.watch({'fileId': fileId, 'channel':channel});
Code to unsubscribe
var request = client.drive.channels.stop({'id': channelId, 'resourceId':resourceId});

Related

Having trouble to run the Google Drive API on Google Chrome

Here I am again still trying to run my platform with the Google Drive API. It works perfectly on Mozilla, but it does not work on Google Chrome. I keep getting this error:
Uncaught TypeError: Cannot read property 'init' of undefined
at initClient (google_drive:370)
at api.js:15
at fa (api.js:8)
at A (api.js:15)
at Array.r. (api.js:15)
at Object.x. [as loaded_0] (api.js:15)
at cb=gapi.loaded_0:1
Here is the code I am running:
var CLIENT_ID = '';
var API_KEY = '';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/drive.readonly';
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
var localdriveButton = document.getElementById('localdrive_button');
var FILES = {};
function handleClientLoad() {
setTimeout(function(){ gapi.load('client:auth2', initClient); }, 3000);
}
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick();
signoutButton.onclick = handleSignoutClick();
}, function(error) {
console.log(JSON.stringify(error, null, 2));
});
return gapi;
}
Does anyone have any idea of what problem I might have and how to fix it?

API call to directory.members.list failed with error: Insufficient Permission: Request had insufficient authentication scopes

****Edited 3/13/2020*****
Hi guys, this is the full function:
function AddNewMember(LastEntryMail)
{
var NewMember =
{
email: LastEntryMail,
role: 'MEMBER'
};
var MemberExist = false;
var pageToken, page;
var groupEmail = 'members#mydomain.com';
var groupDomainName = 'mydomain.com';
do
{
page = AdminDirectory.Members.list(groupEmail,{
domain: groupDomainName,
orderBy: 'Email',
maxResults: 1000,
pageToken: pageToken
});
var GroupMembers = page.members;
for (var m in GroupMembers)
{
var email = GroupMembers[m].email;
if(email.toLowerCase() == LastEntryMail)
{
MemberExist = true;
break; //stop the for loop
}
}
if(MemberExist == true)
{
break; //stop the do loop
}
else //new member email was not found in current page members list. go to next page
{
pageToken = page.nextPageToken;
}
} while (pageToken && !MemberExist);
if(MemberExist == false)
{
try
{
AdminDirectory.Members.insert(NewMember, groupEmail);
Logger.log('User %s added as a member of group %s.', LastEntryMail, groupEmail);
var AddNewMember = 'MemberAddedToGroup';
}
catch(e)
{
Logger.log(LastEntryMail+"has invoked an error"+groupEmail);
}
}
}
Thing is, it is also not reproducing on my end. I haven't changed a thing in the code or in the project settings.
could it be a tweak on the google server?
Thanks
******End Update 03/13/2020*********************
I have a function for adding new members to my group. bellow is the part where I'm reading the list from the domain:
page = AdminDirectory.Members.list(groupEmail,{
domain: groupDomainName,
orderBy: 'Email',
maxResults: 1000,
pageToken: pageToken
});
var GroupMembers = page.members;
Problem is, every time I run the function, I get:
GoogleJsonResponseException: API call to directory.members.list failed with error: Insufficient Permission: Request had insufficient authentication scopes
I have turned on the Admin Directory API under the project Advanced Google Services
I also checked in the AppScript Console under Project OAuth Scopes that I have the correct scope URL:
https://www.googleapis.com/auth/admin.directory.group
I have the same exact function running under another one of my projects, with the same access permissions and it runs OK.
What am I missing? thanks

"Bad Request" error for chromeosdevices.list

I am trying to figure out how to get device information about Chromebooks that my organization uses (using Google Apps Scripts.) Being new to this, I basically tried to modify a tutorial code that would get users from the organization. When I execute the code for users, it works fine, but gives me a "Bad Request (line 7, file "Code") error when I try to run it as below:
function getDevices() {
var optionalArgs = {
customerId: 'XXXXXXXXXXX',
maxResults: 10,
orderBy: 'serialNumber'
};
var response = AdminDirectory.Chromeosdevices.list(optionalArgs);
var devices = response.devices;
if (devices && devices.length > 0) {
Logger.log('Devices:');
for (i = 0; i < devices.length; i++) {
var device = devices[i];
Logger.log('%s (%s)', device.serialNumber, device.lastSync);
}
} else {
Logger.log('No devices found.');
}
}
I know it's referencing this line for the error:
var response = AdminDirectory.Chromeosdevices.list(optionalArgs);
I checked with Google's Directory API documentation to make sure I was passing parameters correctly, but I don't see that being an issue. I have enabled the API under Advanced Google Services, and enabled it on the Cloud Platform API Dashboard (the dashboard shows the requests and errors of my attempts.)
Any ideas?
I tinkered around with the script and tried entering the customerID directly to the parameters instead of passing it with the other arguments, and I no longer receive the error:
function getDevices() {
var optionalArgs = {
maxResults: 200,
orderBy: 'serialNumber'
};
var response = (AdminDirectory.Chromeosdevices.list("my_customer", optionalArgs));
I realize the that my_customer parameter is optional with the Users.list request, it is required with Chromeosdevices.list. I am not sure why it does not like having that argument passed, it seems to have been the root of my problem. While it didn't list any devices for me in the log, it did post "No devices found", which means the everything else executed.

console logs 'The provider id_provider is not a valid one'

Trying to get head around when debugging a Viewer app. Chrome console shows 'The provider id_provider is not a valid one'. Any suggestion?
If options is like this:
var options = {
env: 'AutodeskProduction',
getAccessToken: getToken }
}
function getToken () {
var response;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
response = JSON.parse(
xhr.responseText);
return response.access_token;
}
if forcing 2.9, 'The provider id_provider is not a valid one'.
If forcing 2.7 or 2.8, not log but the viewer doesn't show up.
If no specified version, 'Warning : no access token is provided. Use built in token : YtTb8vRA4XQfTorjm9c8eVZJTYP6'.
it stops in Autodesk360App.js
var initialItem = app.getDefaultGeometry(geometryItems);
Chrome logs 'Uncaught TypeError: app.getDefaultGeometry is not a function'
If I directly feed token:
accessToken: 'MorPwhKARIS3VGIrcd3FrZSjsnOx5'
it works beautifully in 2.7,2.8 and 2.9. But if no version, it stops in Autodesk360App.js, the same as above.
Thank you!
Aren't you missing the url on the http request? Maybe something line:
function getToken() {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", '/yourTokenEndPoint', false);
xmlHttp.send(null);
var response = JSON.parse(xmlHttp.responseText);
return response.access_token;
}
For the Viewer, it must be synchronous.

OAuth2 with Google Cloud Print

I had written a Google Apps Script that connected to Google Cloud Print to automate some printing. The script would auto-run on a time interval, search for relevant files, and if found it would sent them to my printer. My code used OAuthConfig and was working fine, but now that class has been deprecated and after a weekend of trial & error and scouring the interwebs I can't get it to work with OAuth2.
Here's the OAuthConfig code that was working fine:
function printDoc(docId, docTitle, myPrinterId) {
var scope = 'https://www.googleapis.com/auth/cloudprint';
var url = 'https://www.google.com/cloudprint/submit';
var payloadOfSubmit = {
"printerid" : myPrinterId,
"title" : docTitle,
"content" : docId,
"contentType" : "google.kix"
};
var fetchArgs = googleOAuth_('google', scope, payloadOfSubmit);
fetchArgs.method = 'POST';
var responseOfSubmit = UrlFetchApp.fetch(url, fetchArgs);
var jsonOfSubmit = JSON.parse(responseOfSubmit.getContentText());
return jsonOfSubmit;
}
function googleOAuth_(name, scope, payloadData) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {
oAuthServiceName:name,
oAuthUseToken:"always",
muteHttpExceptions:true,
payload:payloadData
};
}
I've successfully connected the github library for OAuth2. However, what's different about the instructions provided there, and on many other sites, is that they assume that the code will be deployed as a web service where a user is prompted to manually click to authorize the request. In my case the code will be saved on a Google Apps Script file, and the Cloud Printer is on the same Google account, so I never needed this manual intervention or back & forth with my original OAuthconfig.
My first attempt by adapting the instructions was:
function printDoc2(docId, docTitle, myPrinterId) {
var url = 'https://www.google.com/cloudprint/submit';
var scope = 'https://www.googleapis.com/auth/cloudprint';
var payloadOfSubmit = {
"printerid" : myPrinterId,
"title" : docTitle,
"content" : docId,
"contentType" : "google.kix",
};
var accessToken = googleOAuth_('google', scope).getAccessToken();
var params = {
method:"POST",
headers: {"Authorization": "Bearer " + accessToken},
muteHttpExceptions:true,
payload:payloadOfSubmit
};
var responseOfSubmit = UrlFetchApp.fetch(url, params);
//Logger.log(responseOfSubmit);
var jsonOfSubmit = JSON.parse(responseOfSubmit.getContentText());
return jsonOfSubmit;
}
function googleOAuth2_(name, scope) {
return OAuth2.createService(name)
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId("anonymous")
.setClientSecret("anonymous")
.setProjectKey(ScriptApp.getProjectKey())
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(scope)
.setCallbackFunction('authCallback');
}
function authCallback(request) {
var driveService = getDriveService();
var isAuthorized = driveService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
But this gives me an error "Access not granted or expired" when it tries to run the line:
var accessToken = googleOAuth_('google', scope).getAccessToken();
So I found a apps ScriptApp Method getOAuthToken which seemed like it might give me the token I need. I replaced the above line with:
var accessToken = ScriptApp.getOAuthToken();
And the code executes but my response from the server is "Error 403 User credentials required".
Here's my third attempt based on #Mogsdad's suggestion:
function sendPrintJob(docId,myPrinterId,docTitle) {
var payloadOfSubmit = {
"printerid" : myPrinterId,
"title" : docTitle,
"content" : docId,
"contentType" : "google.kix" ,
};
var request = {
"method": "POST",
"headers":{"Authorization": "Bearer "+ScriptApp.getOAuthToken()},
"muteHttpExceptions": true
};
var responseOfSubmit = UrlFetchApp.fetch("https://www.google.com/cloudprint/submit", request);
Logger.log(responseOfSubmit);
}
I've tried a number of variations, including creating a Developer Console Project and using the Client ID provided there, but I keep getting stuck at these two issues (access not granted, or credentials required). If anyone can provide any help I'd really appreciate it.
Here are the steps that allowed me to connect Google Apps Script to Google Cloud Print, so I could then submit GCP jobs (these steps are all started from within Google Apps Script):
Add the OAuth2 library
(https://github.com/googlesamples/apps-script-oauth2) to your Google
Apps Script by going to: Resources > Libraries > Find Library
MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48 > Select
Create new web application in Developer Console Resources > Developer Console Project > Click the project link > APIs & Auth >
Credentials > Add Credentials > OAuth2.0 Client ID > Web
Application > Set Authorized redirect URIs to the format
https://script.google.com/macros/d/{PROJECT KEY}/usercallback
where project key is under File > Project Properties and copy
your client ID and client secret
Add the ID and Secret to "getCloudPrintService()" code below (replace client_id and client_secret)
Go to Run > ShowURL and authorize the script.
Open the Logger (Cmd + Enter), copy the URL and paste it in a new browser tab to complete the authorization.
Go to https://www.google.com/cloudprint/#printers , select your printer, click details, expand advanced details, and copy your Printer ID (it will be of the format 555aa555-5a55-5555-5555-55555a55a555)
Add the printer id to "printGoogleDocument()" code below (replace myPrinterId)
This resource was helpful in figuring the steps out: http://ctrlq.org/code/20061-google-cloud-print-with-apps-script, and you may also find these links helpful:
https://developers.google.com/cloud-print/docs/appInterfaces
https://mashe.hawksey.info/2015/10/setting-up-oauth2-access-with-google-apps-script-blogger-api-example/
function showURL() {
var cpService = getCloudPrintService();
if (!cpService.hasAccess()) {
Logger.log(cpService.getAuthorizationUrl());
} else {
Logger.log("You already have access to this service.");
}
}
function getCloudPrintService() {
return OAuth2.createService('print')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(client_id)
.setClientSecret(client_secret)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/cloudprint')
.setParam('login_hint', Session.getActiveUser().getEmail())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var isAuthorized = getCloudPrintService().handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('You can now use Google Cloud Print from Apps Script.');
} else {
return HtmlService.createHtmlOutput('Cloud Print Error: Access Denied');
}
}
function getPrinterList() {
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/search', {
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
muteHttpExceptions: true
}).getContentText();
var printers = JSON.parse(response).printers;
for (var p in printers) {
Logger.log("%s %s %s", printers[p].id, printers[p].name, printers[p].description);
}
}
function printGoogleDocument(docId, docTitle) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid" : myPrinterId,
"content" : docId,
"title" : docTitle,
"contentType" : "google.kix", // allows you to print google docs
"ticket" : JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
The scope "https://www.googleapis.com/auth/cloudprint" has to be included explicitly in the
manifest file
appscript.json (View > Show manifest file)
{
"timeZone": "Europe/Paris",
"dependencies": {
},
"oauthScopes": [
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/script.container.ui",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/cloudprint"
],
"exceptionLogging": "STACKDRIVER"
}
Code.gs
function listPrinters() {
var options = {
headers: {
authorization: 'OAuth ' + ScriptApp.getOAuthToken()
}
}
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/search', options);
Logger.log(response);
}